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, mdiViewDashboard } 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";

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 [showPassword, setShowPassword] = useState(false);
  const { currentUser, isFetching, errorMessage, token, notify:notifyState } = useAppSelector(
    (state) => state.auth,
  );
  const [initialValues, setInitialValues] = React.useState({ email:'super_admin@flatlogic.com',
    password: 'db9589f7',
    remember: true })

  const title = 'TrialTracker ERP'

  // 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 ?? '',
      }));
  };

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

        <div className="flex flex-col items-center justify-center min-h-screen p-6">
            <div className="w-full max-w-md space-y-8">
                <div className="text-center mb-8">
                    <div className="inline-flex items-center justify-center w-16 h-16 rounded-xl bg-blue-600 text-white mb-4 shadow-lg">
                        <BaseIcon path={mdiViewDashboard} size={36} />
                    </div>
                    <h2 className="text-3xl font-extrabold text-gray-900 tracking-tight">{title}</h2>
                    <p className="mt-2 text-sm text-gray-500 font-medium">Enterprise Breeding & Trial Management</p>
                </div>

                <CardBox className="shadow-xl border-gray-100">
                    <Formik
                        initialValues={initialValues}
                        enableReinitialize
                        onSubmit={(values) => handleSubmit(values)}
                    >
                        <Form className="space-y-4">
                            <FormField
                                label='Email Address'
                                labelColor="text-gray-700"
                                 help='Enter your registered enterprise email'>
                                <Field name='email' placeholder="name@company.com" className="focus:ring-blue-500 border-gray-300" />
                            </FormField>

                            <div className='relative'>
                                <FormField
                                    label='Password'
                                    labelColor="text-gray-700"
                                     help='Enter your secure password'>
                                    <Field name='password' type={showPassword ? 'text' : 'password'} className="focus:ring-blue-500 border-gray-300" />
                                </FormField>
                                <div
                                    className='absolute top-9 right-0 pr-3 flex items-center cursor-pointer'
                                    onClick={togglePasswordVisibility}
                                >
                                    <BaseIcon
                                        className='text-gray-400 hover:text-gray-600'
                                        size={20}
                                        path={showPassword ? mdiEyeOff : mdiEye}
                                    />
                                </div>
                            </div>

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

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

                            <div className="pt-2">
                                <BaseButton
                                    className={'w-full py-3 font-bold text-lg'}
                                    type='submit'
                                    label={isFetching ? 'Authenticating...' : 'Sign In'}
                                    color='info'
                                    disabled={isFetching}
                                />
                            </div>
                        </Form>
                    </Formik>
                </CardBox>

                <div className="bg-blue-50 border border-blue-100 rounded-xl p-4 text-sm text-blue-800">
                    <div className="flex gap-3">
                        <BaseIcon path={mdiInformation} size={20} className="text-blue-500 flex-shrink-0" />
                        <div>
                            <p className="font-bold mb-1">Quick Access for Review:</p>
                            <div className="space-y-1 opacity-90">
                                <p>Admin: <code className="cursor-pointer font-bold underline" onClick={(e) => setLogin(e.target)} data-password="db9589f7">admin@flatlogic.com</code></p>
                                <p>Staff: <code className="cursor-pointer font-bold underline" onClick={(e) => setLogin(e.target)} data-password="259e6bfdf548">client@hello.com</code></p>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="text-center text-gray-400 text-xs">
                    <p>© 2026 {title}. Confidential & Proprietary.</p>
                </div>
            </div>
        </div>
        <ToastContainer />
      </div>
  );
}

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