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, mdiShieldCheck } 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, resetAction } 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'
import Logo from '../components/Logo'

export default function Login() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const textColor = 'text-emerald-600';
  const iconsColor = 'text-emerald-500';
  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('image');
    const [contentPosition, setContentPosition] = useState('left');
    const [showPassword, setShowPassword] = useState(false);
  const { currentUser, isFetching, errorMessage, token, notify:notifyState } = useAppSelector(
    (state) => state.auth,
  );
  const [initialValues, setInitialValues] = React.useState({ email:'admin@flatlogic.com',
    password: 'b2096650',
    remember: true })

  const title = 'Fix-It-Local'

  // Fetch Pexels image/video
  useEffect( () => {
      async function fetchData() {
          const image = await getPexelsImage()
          const video = await getPexelsVideo()
          setIllustrationImage(image);
          setIllustrationVideo(video);
      }
      fetchData();
  }, []);
  // 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 setLogin = (target: HTMLElement) => {
      setInitialValues(prev => ({
          ...prev,
          email   : target.innerText.trim(),
          password: target.dataset.password ?? '',
      }));
  };

  const imageBlock = (image) => (
      <div className="hidden lg:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/2 overflow-hidden"
           style={{
               backgroundImage: `${image ? `url(${image.src?.original})` : 'linear-gradient(rgba(16, 185, 129, 0.1), rgba(6, 78, 59, 0.2))'}`,
               backgroundSize: 'cover',
               backgroundPosition: 'center',
               backgroundRepeat: 'no-repeat',
           }}>
          <div className="absolute inset-0 bg-emerald-900/20 backdrop-brightness-75"></div>
          <div className="relative z-10 p-12 text-white">
              <h1 className="text-4xl font-black mb-4">Welcome Back to the Network.</h1>
              <p className="text-lg text-emerald-50/80 max-w-md leading-relaxed">
                  Join thousands of verified professionals and clients in the most transparent service ecosystem.
              </p>
          </div>
          <div className="flex justify-center w-full bg-black/40 py-2 relative z-10">
              <a className="text-[10px] text-white/60 hover:text-white transition-colors" 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 lg:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/2 overflow-hidden'>
                  <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="absolute inset-0 bg-emerald-900/20 backdrop-brightness-75"></div>
                  <div className="relative z-10 p-12 text-white">
                      <h1 className="text-4xl font-black mb-4">Welcome Back to the Network.</h1>
                      <p className="text-lg text-emerald-50/80 max-w-md leading-relaxed">
                          Join thousands of verified professionals and clients in the most transparent service ecosystem.
                      </p>
                  </div>
                  <div className='flex justify-center w-full bg-black/40 py-2 relative z-10'>
                      <a
                          className='text-[10px] text-white/60 hover:text-white transition-colors'
                          href={video.user.url}
                          target='_blank'
                          rel='noreferrer'
                      >
                          Video by {video.user.name} on Pexels
                      </a>
                  </div>
              </div>)
      }
      return imageBlock(illustrationImage);
  };

  return (
      <div className="min-h-screen bg-slate-50 font-sans">
        <Head>
          <title>{getPageTitle('Login')}</title>
        </Head>

        <div className="flex flex-row min-h-screen">
            {contentType === 'video' ? videoBlock(illustrationVideo) : imageBlock(illustrationImage)}
            
            <div className="w-full lg:w-1/2 flex items-center justify-center p-8 lg:p-16">
                <div className="w-full max-w-md space-y-8">
                    {/* Branding */}
                    <div className="flex flex-col items-center mb-8">
                        <Link href="/" className="flex items-center gap-3 group mb-6">
                            <Logo className="h-12 w-auto" />
                        </Link>
                        <h2 className="text-3xl font-bold text-slate-900">Account Login</h2>
                        <p className="text-slate-500 mt-2">Enter your credentials to access your dashboard</p>
                    </div>

                    <CardBox className="shadow-2xl border-none rounded-[2rem] p-4 lg:p-6">
                        <Formik
                            initialValues={initialValues}
                            enableReinitialize
                            onSubmit={(values) => handleSubmit(values)}
                        >
                            <Form className="space-y-4">
                                <FormField
                                    label='Email Address'
                                    labelColor="text-slate-700 font-bold"
                                >
                                    <Field name='email' placeholder="name@company.com" className="rounded-xl border-slate-200 focus:border-emerald-500 focus:ring-emerald-500" />
                                </FormField>

                                <div className='relative'>
                                    <FormField
                                        label='Password'
                                        labelColor="text-slate-700 font-bold"
                                    >
                                        <Field name='password' type={showPassword ? 'text' : 'password'} placeholder="••••••••" className="rounded-xl border-slate-200 focus:border-emerald-500 focus:ring-emerald-500" />
                                    </FormField>
                                    <div
                                        className='absolute top-[42px] right-0 pr-4 flex items-center cursor-pointer'
                                        onClick={togglePasswordVisibility}
                                    >
                                        <BaseIcon
                                            className='text-slate-400 hover:text-emerald-500'
                                            size={20}
                                            path={showPassword ? mdiEyeOff : mdiEye}
                                        />
                                    </div>
                                </div>

                                <div className={'flex justify-between items-center text-sm'}>
                                    <FormCheckRadio type='checkbox' label='Keep me logged in'>
                                        <Field type='checkbox' name='remember' />
                                    </FormCheckRadio>

                                    <Link className="font-semibold text-emerald-600 hover:text-emerald-700" href={'/forgot'}>
                                        Forgot password?
                                    </Link>
                                </div>

                                <div className="pt-4">
                                    <BaseButton
                                        className={'w-full py-4 rounded-xl font-bold text-lg shadow-lg shadow-emerald-500/20'}
                                        type='submit'
                                        label={isFetching ? 'Signing in...' : 'Sign In'}
                                        color='success'
                                        disabled={isFetching}
                                    />
                                </div>
                                
                                <div className="text-center pt-4">
                                    <p className="text-slate-500 text-sm">
                                        Don&apos;t have an account yet?{' '}
                                        <Link className="font-bold text-emerald-600 hover:text-emerald-700" href={'/register'}>
                                            Create an account
                                        </Link>
                                    </p>
                                </div>
                            </Form>
                        </Formik>
                    </CardBox>

                    {/* Demo Access Card - Styled more like a hint/badge */}
                    <div className="bg-slate-100/80 backdrop-blur rounded-2xl p-6 border border-slate-200">
                        <div className="flex items-start gap-4">
                            <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center shrink-0 shadow-sm">
                                <BaseIcon path={mdiInformation} size={20} className="text-emerald-500" />
                            </div>
                            <div>
                                <h4 className="font-bold text-slate-900 text-sm mb-2">Demo Access</h4>
                                <div className="space-y-2 text-xs text-slate-600">
                                    <p>
                                        <span className="font-semibold">Admin:</span>{' '}
                                        <code className="cursor-pointer text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded" data-password="b2096650" onClick={(e) => setLogin(e.target as HTMLElement)}>admin@flatlogic.com</code>
                                    </p>
                                    <p>
                                        <span className="font-semibold">Client:</span>{' '}
                                        <code className="cursor-pointer text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded" data-password="7302e7d1c0fe" onClick={(e) => setLogin(e.target as HTMLElement)}>client@hello.com</code>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="text-center text-slate-400 text-xs pt-8">
                        © 2026 Fix-It-Local™. All rights reserved. <br/>
                        <Link href='/privacy-policy/' className="hover:text-slate-600 mt-2 inline-block">Privacy Policy</Link>
                    </div>
                </div>
            </div>
        </div>
        <ToastContainer />
      </div>
  );
}

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