import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { Field, Form, Formik } from 'formik';
import { mdiEye, mdiEyeOff } from '@mdi/js';
import { toast, ToastContainer } from 'react-toastify';
import { useRouter } from 'next/router';
import BaseIcon from '../components/BaseIcon';
import PublicSiteNav from '../components/PublicSiteNav';
import LayoutGuest from '../layouts/Guest';
import { getPageTitle } from '../config';
import { findMe, loginDemoUser, loginUser, resetAction } from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';

const ui = {
  page: 'bg-[#fffdf9] text-[#19192d]',
  banner: 'bg-[#19192d] text-white',
  navShell: 'rounded-none bg-white  ring-1 ring-[#19192d]/5',
  ink: 'text-[#19192d]',
  muted: 'text-[#5f6675]',
  accent: 'text-[#147568]',
  gold: 'text-[#147568]',
  border: 'border-[#19192d]/10',
  surface: 'bg-white',
  softSurface: 'bg-[#fffdf9]',
  darkPanel: 'bg-[#19192d] text-white',
  button: 'bg-[#147568] text-white  transition hover:brightness-105',
  card: 'rounded-none border border-[#19192d]/10 bg-white ',
  overline: 'text-sm font-bold uppercase tracking-[0.28em] text-[#147568]',
  heading: 'font-serif font-semibold tracking-tight text-[#19192d]',
};

type LoginValues = {
  email: string;
  password: string;
  remember: boolean;
};

export default function Login() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [showPassword, setShowPassword] = useState(false);
  const {
    currentUser,
    isFetching,
    errorMessage,
    token,
    notify: notifyState,
  } = useAppSelector((state) => state.auth);

  const initialValues: LoginValues = {
    email: '',
    password: '',
    remember: true,
  };

  useEffect(() => {
    if (token) {
      dispatch(findMe());
    }
  }, [token, dispatch]);

  useEffect(() => {
    if (currentUser?.id) {
      if (currentUser?.app_role?.name === 'Client') {
        router.push('/client-portal');
        return;
      }

      router.push('/dashboard');
    }
  }, [currentUser?.id, currentUser?.app_role?.name, router]);

  useEffect(() => {
    if (errorMessage) {
      toast(errorMessage, { type: 'error' });
    }
  }, [errorMessage]);

  useEffect(() => {
    if (notifyState?.showNotification) {
      toast(notifyState?.textNotification, { type: 'success' });
      dispatch(resetAction());
    }
  }, [notifyState?.showNotification, notifyState?.textNotification, dispatch]);

  async function handleSubmit(values: LoginValues) {
    const { remember, ...credentials } = values;
    await dispatch(loginUser(credentials));
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Login')}</title>
      </Head>

      <main className={`min-h-screen ${ui.page}`}>
        <div className={`${ui.banner} px-5 py-4 text-center text-lg`}>
          <p className='text-xs font-bold uppercase tracking-[0.34em]'>
            Still human
          </p>
          <p className='mt-2 text-xl font-medium md:text-2xl'>
            AI is not a coach. Keep the real relationship at the center.
          </p>
        </div>

        <PublicSiteNav />

        <section className='mx-auto grid max-w-7xl grid-cols-1 items-center gap-12 px-5 pb-20 pt-14 lg:grid-cols-[0.95fr_1.05fr] lg:px-8'>
          <div>
            <p className={ui.overline}>Welcome back</p>
            <h1
              className={`${ui.heading} mt-5 text-5xl leading-tight md:text-6xl`}
            >
              Return to your coaching workspace.
            </h1>
            <p className={`mt-6 max-w-2xl text-lg leading-8 ${ui.muted}`}>
              Review session memory, prepare for the next call, and keep client
              commitments moving between sessions.
            </p>

            <div className='mt-10 grid gap-4 sm:grid-cols-3'>
              {[
                ['Session memory', 'Summaries, themes, and commitments.'],
                ['Prep briefs', 'Context before the next conversation.'],
                ['Client portal', 'Approved notes and resources.'],
              ].map(([title, copy]) => (
                <div key={title} className={`p-5 ${ui.card}`}>
                  <h2 className='font-semibold'>{title}</h2>
                  <p className={`mt-2 text-sm leading-6 ${ui.muted}`}>{copy}</p>
                </div>
              ))}
            </div>
          </div>

          <div className='mx-auto w-full max-w-md'>
            <div className={`${ui.card} p-6 md:p-8`}>
              <div className='mb-8'>
                <p className={`${ui.overline} text-xs`}>Sign in</p>
                <h2 className='mt-3 text-3xl font-semibold'>
                  Open your workspace
                </h2>
                <p className={`mt-2 ${ui.muted}`}>
                  Use your workspace credentials to continue.
                </p>
              </div>

              {process.env.NEXT_PUBLIC_DEMO_MODE === 'true' && (
                <div className={`mb-6 border p-4 ${ui.border} ${ui.softSurface}`}>
                  <p className='font-semibold'>Fictional read-only demo</p>
                  <p className={`mt-1 text-sm ${ui.muted}`}>
                    Choose a role. Changes, uploads, email, password actions, and AI usage are disabled.
                  </p>
                  <div className='mt-4 grid grid-cols-3 gap-2'>
                    {(['admin', 'coach', 'client'] as const).map((role) => (
                      <button
                        key={role}
                        type='button'
                        disabled={isFetching}
                        onClick={() => dispatch(loginDemoUser(role))}
                        className='border border-[#19192d]/15 bg-white px-3 py-2 text-sm font-semibold capitalize hover:border-[#147568] disabled:opacity-60'
                      >
                        {role}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              <Formik
                initialValues={initialValues}
                enableReinitialize
                onSubmit={(values) => handleSubmit(values)}
              >
                {() => (
                  <Form className='space-y-5'>
                    <label className='block'>
                      <span className='mb-2 block text-sm font-semibold'>
                        Email
                      </span>
                      <Field
                        name='email'
                        type='email'
                        className={`w-full rounded-none border px-4 py-3 outline-none transition focus:border-[#147568] focus:ring-4 focus:ring-[#147568]/10 ${ui.border}`}
                      />
                    </label>

                    <label className='block'>
                      <span className='mb-2 block text-sm font-semibold'>
                        Password
                      </span>
                      <div className='relative'>
                        <Field
                          name='password'
                          type={showPassword ? 'text' : 'password'}
                          className={`w-full rounded-none border px-4 py-3 pr-12 outline-none transition focus:border-[#147568] focus:ring-4 focus:ring-[#147568]/10 ${ui.border}`}
                        />
                        <button
                          type='button'
                          className='absolute right-4 top-1/2 -translate-y-1/2 text-[#5f6675] transition hover:text-[#19192d]'
                          onClick={() => setShowPassword(!showPassword)}
                          aria-label={
                            showPassword ? 'Hide password' : 'Show password'
                          }
                        >
                          <BaseIcon
                            size={20}
                            path={showPassword ? mdiEyeOff : mdiEye}
                          />
                        </button>
                      </div>
                    </label>

                    <div className='flex items-center justify-between gap-4 text-sm'>
                      <label className='flex items-center gap-2'>
                        <Field
                          type='checkbox'
                          name='remember'
                          className='h-4 w-4 rounded border-[#19192d]/20 text-[#147568]'
                        />
                        <span className={ui.muted}>Remember me</span>
                      </label>
                      <Link
                        href='/forgot'
                        className='font-semibold text-[#147568] hover:underline'
                      >
                        Forgot password?
                      </Link>
                    </div>

                    <button
                      type='submit'
                      disabled={isFetching}
                      className={`w-full rounded-none px-6 py-4 font-semibold disabled:cursor-not-allowed disabled:opacity-60 ${ui.button}`}
                    >
                      {isFetching ? 'Opening...' : 'Login'}
                    </button>
                  </Form>
                )}
              </Formik>

              <p className={`mt-6 text-center text-sm ${ui.muted}`}>
                Client access is created from a single-use coach invitation.
              </p>
            </div>
          </div>
        </section>

        <footer className={`border-t px-5 py-10 ${ui.border}`}>
          <div
            className={`mx-auto flex max-w-7xl flex-col justify-between gap-5 text-sm md:flex-row ${ui.muted}`}
          >
            <p>© 2026 Coaching SaaS Workspace. Coaching beyond the session.</p>
            <div className='flex gap-5'>
              <Link href='/privacy-policy/'>Privacy Policy</Link>
              <Link href='/terms-of-use/'>Terms of Use</Link>
            </div>
          </div>
        </footer>
      </main>

      <ToastContainer />
    </>
  );
}

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