

import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import BaseIcon from "../components/BaseIcon";
import { mdiInformation, mdiEye, mdiEyeOff } from '@mdi/js';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import { Field, Form, Formik } from 'formik';
import FormField from '../components/FormField';
import FormCheckRadio from '../components/FormCheckRadio';
import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { useRouter } from 'next/router';
import { getPageTitle } from '../config';
import {
  findMe,
  loginUser,
  requestEmailOtp,
  resetAction,
  setAuthToken,
  verifyEmailOtp,
} from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import Link from 'next/link';
import {toast, ToastContainer} from "react-toastify";
import { getPexelsImage, getPexelsVideo } from '../helpers/pexels'

export default function Login() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const textColor = useAppSelector((state) => state.style.linkColor);
  const iconsColor = useAppSelector((state) => state.style.iconsColor);
  const notify = (type, msg) => toast(msg, { type });
  const [ illustrationImage, setIllustrationImage ] = useState({
      src: undefined,
      photographer: undefined,
      photographer_url: undefined,
  })
  const [ illustrationVideo, setIllustrationVideo ] = useState({video_files: []})
    const [contentType, setContentType] = useState('video');
    const [contentPosition, setContentPosition] = useState('right');
    const [showPassword, setShowPassword] = useState(false);
    const [otpEmail, setOtpEmail] = useState('');
    const [otpCode, setOtpCode] = useState('');
    const [otpRequested, setOtpRequested] = useState(false);
  const {
    currentUser,
    isFetching,
    isRequestingOtp,
    errorMessage,
    token,
    notify:notifyState,
  } = useAppSelector(
    (state) => state.auth,
  );
  const [initialValues, setInitialValues] = React.useState({ email:'admin@flatlogic.com',
    password: '987055cb',
    remember: true })

  const title = 'Pencari Tempat Terdekat'

  // Fetch Pexels image/video
  useEffect( () => {
      async function fetchData() {
          const image = await getPexelsImage()
          const video = await getPexelsVideo()
          setIllustrationImage(image);
          setIllustrationVideo(video);
      }
      fetchData();
  }, []);
  // Handle Google OAuth callback token
  useEffect(() => {
    const redirectToken = router.query.token;

    if (typeof redirectToken === 'string') {
      dispatch(setAuthToken(redirectToken));
      router.replace('/login', undefined, { shallow: true });
    }
  }, [dispatch, router, router.query.token]);

  // Fetch user data
  useEffect(() => {
    if (token) {
      dispatch(findMe());
    }
  }, [token, dispatch]);
  // Redirect to dashboard if user is logged in
  useEffect(() => {
    if (currentUser?.id) {
      router.push('/dashboard');
    }
  }, [currentUser?.id, router]);
  // Show error message if there is one
  useEffect(() => {
    if (errorMessage){
      notify('error', errorMessage)
    }

  }, [errorMessage])
  // Show notification if there is one
  useEffect(() => {
      if (notifyState?.showNotification) {
        notify('success', notifyState?.textNotification)
        dispatch(resetAction());
      }
    }, [notifyState?.showNotification])

  const togglePasswordVisibility = () => {
      setShowPassword(!showPassword);
  };

  const handleSubmit = async (value) => {
    const {remember, ...rest} = value
    await dispatch(loginUser(rest));
  };

  const handleGoogleSignin = () => {
    if (typeof window === 'undefined') {
      return;
    }

    window.location.href = `/api/auth/signin/google?app=${encodeURIComponent(window.location.origin)}`;
  };

  const handleRequestOtp = async () => {
    const email = otpEmail.trim();

    if (!email) {
      notify('error', 'Masukkan email terlebih dahulu');
      return;
    }

    const result = await dispatch(requestEmailOtp({ email }));

    if (requestEmailOtp.fulfilled.match(result)) {
      setOtpRequested(true);
      notify('success', 'Kode OTP sudah dikirim ke email Anda');
      return;
    }

    notify('error', String(result.payload || 'Gagal mengirim OTP'));
  };

  const handleVerifyOtp = async () => {
    const email = otpEmail.trim();
    const otp = otpCode.trim();

    if (!email || !otp) {
      notify('error', 'Masukkan email dan kode OTP');
      return;
    }

    const result = await dispatch(verifyEmailOtp({ email, otp }));

    if (verifyEmailOtp.fulfilled.match(result)) {
      notify('success', 'OTP berhasil diverifikasi');
      return;
    }

    notify('error', String(result.payload || 'Kode OTP tidak valid'));
  };

  const setLogin = (target: HTMLElement) => {
      setInitialValues(prev => ({
          ...prev,
          email   : target.innerText.trim(),
          password: target.dataset.password ?? '',
      }));
  };

  const imageBlock = (image) => (
      <div className="hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3"
           style={{
               backgroundImage: `${image ? `url(${image.src?.original})` : 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'}`,
               backgroundSize: 'cover',
               backgroundPosition: 'left center',
               backgroundRepeat: 'no-repeat',
           }}>
          <div className="flex justify-center w-full bg-blue-300/20">
              <a className="text-[8px]" href={image?.photographer_url} target="_blank" rel="noreferrer">Photo
                  by {image?.photographer} on Pexels</a>
          </div>
      </div>
  )

  const videoBlock = (video) => {
      if (video?.video_files?.length > 0) {
          return (
              <div className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'>
                  <video
                      className='absolute top-0 left-0 w-full h-full object-cover'
                      autoPlay
                      loop
                      muted
                  >
                      <source src={video.video_files[0]?.link} type='video/mp4'/>
                      Your browser does not support the video tag.
                  </video>
                  <div className='flex justify-center w-full bg-blue-300/20 z-10'>
                      <a
                          className='text-[8px]'
                          href={video.user.url}
                          target='_blank'
                          rel='noreferrer'
                      >
                          Video by {video.user.name} on Pexels
                      </a>
                  </div>
              </div>)
      }
  };

  return (
      <div style={contentPosition === 'background' ? {
          backgroundImage: `${
              illustrationImage
                  ? `url(${illustrationImage.src?.original})`
                  : 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
          }`,
          backgroundSize: 'cover',
          backgroundPosition: 'left center',
          backgroundRepeat: 'no-repeat',
      } : {}}>
        <Head>
          <title>{getPageTitle('Login')}</title>
        </Head>

        <SectionFullScreen bg='violet'>
          <div className={`flex ${contentPosition === 'right' ? 'flex-row-reverse' : 'flex-row'} min-h-screen w-full`}>
            {contentType === 'image' && contentPosition !== 'background' ? imageBlock(illustrationImage) : null}
            {contentType === 'video' && contentPosition !== 'background' ? videoBlock(illustrationVideo) : null}
            <div className='flex items-center justify-center flex-col space-y-4 w-full lg:w-full'>
              
                <CardBox id="loginRoles" className='w-full md:w-3/5 lg:w-2/3'>
                 
                    <h2 className="text-4xl font-semibold my-4">{title}</h2>
                    
                    <div className='flex flex-row text-gray-500 justify-between'>
                        <div>
                          
                            <p className='mb-2'>Use{' '}
                                <code className={`cursor-pointer ${textColor} `}
                                      data-password="987055cb"
                                      onClick={(e) => setLogin(e.target)}>admin@flatlogic.com</code>{' / '}
                                <code className={`${textColor}`}>987055cb</code>{' / '}
                                to login as Admin</p>
                            <p>Use <code
                                className={`cursor-pointer ${textColor} `}
                                data-password="c6f38187677e"
                                onClick={(e) => setLogin(e.target)}>client@hello.com</code>{' / '}
                                <code className={`${textColor}`}>c6f38187677e</code>{' / '}
                                to login as User</p>
                        </div>
                        <div>
                            <BaseIcon
                                className={`${iconsColor}`}
                                w='w-16'
                                h='h-16'
                                size={48}
                                path={mdiInformation}
                            />
                        </div>
                    </div>
                </CardBox>
              
                <CardBox className='w-full md:w-3/5 lg:w-2/3'>
                    <div className='mb-6 rounded-xl border border-blue-100 bg-blue-50/70 p-4 dark:border-dark-700 dark:bg-dark-800'>
                        <h3 className='mb-2 text-lg font-semibold text-gray-800 dark:text-white'>Masuk / Daftar Anggota</h3>
                        <p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>
                            User baru dari Google atau Email OTP otomatis dibuat sebagai Anggota. Admin tetap memakai role admin jika emailnya sudah terdaftar sebagai admin.
                        </p>
                        <BaseButtons type='justify-start' mb='mb-4'>
                            <BaseButton
                                className='w-full'
                                label='Lanjutkan dengan Google'
                                color='info'
                                onClick={handleGoogleSignin}
                            />
                        </BaseButtons>

                        <div className='rounded-lg bg-white/80 p-4 dark:bg-dark-900'>
                            <FormField label='Email OTP' help='Masukkan email untuk menerima kode OTP'>
                                <input
                                    type='email'
                                    value={otpEmail}
                                    onChange={(event) => setOtpEmail(event.target.value)}
                                    placeholder='nama@email.com'
                                />
                            </FormField>
                            {otpRequested && (
                                <FormField label='Kode OTP' help='Masukkan 6 digit kode dari email'>
                                    <input
                                        inputMode='numeric'
                                        maxLength={6}
                                        value={otpCode}
                                        onChange={(event) => setOtpCode(event.target.value.replace(/\D/g, '').slice(0, 6))}
                                        placeholder='123456'
                                    />
                                </FormField>
                            )}
                            <BaseButtons type='justify-start'>
                                <BaseButton
                                    label={isRequestingOtp ? 'Mengirim...' : otpRequested ? 'Kirim Ulang OTP' : 'Kirim OTP'}
                                    color='info'
                                    outline
                                    disabled={isRequestingOtp}
                                    onClick={handleRequestOtp}
                                />
                                {otpRequested && (
                                    <BaseButton
                                        label={isFetching ? 'Memverifikasi...' : 'Verifikasi OTP'}
                                        color='success'
                                        disabled={isFetching}
                                        onClick={handleVerifyOtp}
                                    />
                                )}
                            </BaseButtons>
                        </div>

                        <BaseDivider />
                        <p className='text-center text-xs text-gray-500'>Atau masuk dengan password admin/user yang sudah ada.</p>
                    </div>
                    <Formik
                        initialValues={initialValues}
                        enableReinitialize
                        onSubmit={(values) => handleSubmit(values)}
                    >
                        <Form>
                            <FormField
                                label='Login'
                                 help='Please enter your login'>
                                <Field name='email' />
                            </FormField>

                            <div className='relative'>
                                <FormField
                                    label='Password'
                                     help='Please enter your password'>
                                    <Field name='password' type={showPassword ? 'text' : 'password'} />
                                </FormField>
                                <div
                                    className='absolute bottom-8 right-0 pr-3 flex items-center cursor-pointer'
                                    onClick={togglePasswordVisibility}
                                >
                                    <BaseIcon
                                        className='text-gray-500 hover:text-gray-700'
                                        size={20}
                                        path={showPassword ? mdiEyeOff : mdiEye}
                                    />
                                </div>
                            </div>

                            <div className={'flex justify-between'}>
                                <FormCheckRadio type='checkbox' label='Remember'>
                                    <Field type='checkbox' name='remember' />
                                </FormCheckRadio>

                                <Link className={`${textColor} text-blue-600`} href={'/forgot'}>
                                    Forgot password?
                                </Link>
                            </div>

                            <BaseDivider />

                            <BaseButtons>
                                <BaseButton
                                    className={'w-full'}
                                    type='submit'
                                    label={isFetching ? 'Loading...' : 'Login'}
                                    color='info'
                                    disabled={isFetching}
                                />
                            </BaseButtons>
                            <br />
                            <p className={'text-center'}>
                                Don’t have an account yet?{' '}
                                <Link className={`${textColor}`} href={'/register'}>
                                    New Account
                                </Link>
                            </p>
                        </Form>
                    </Formik>
                </CardBox>
            </div>
          </div>
        </SectionFullScreen>
        <div className='bg-black text-white flex flex-col text-center justify-center md:flex-row'>
          <p className='py-6 text-sm'>© 2026 <span>{title}</span>. © All rights reserved</p>
          <Link className='py-6 ml-4 text-sm' href='/privacy-policy/'>
              Privacy Policy
          </Link>
        </div>
        <ToastContainer />
      </div>
  );
}

Login.getLayout = function getLayout(page: ReactElement) {
  return <LayoutGuest>{page}</LayoutGuest>;
};
