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 LayoutGuest from '../layouts/Guest';
import { getPageTitle } from '../config';
import { findMe, 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-[#72798a]',
  accent: 'text-[#35b7a5]',
  gold: 'text-[#35b7a5]',
  border: 'border-[#19192d]/10',
  surface: 'bg-white',
  softSurface: 'bg-[#fffdf9]',
  darkPanel: 'bg-[#19192d] text-white',
  button: 'bg-[#35b7a5] 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-[#35b7a5]',
  heading: 'font-serif font-semibold tracking-tight text-[#19192d]',
};

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

const demoAccounts = [
  {
    label: 'Admin',
    description: 'Full workspace access',
    email: 'admin@flatlogic.com',
    password: 'f76d928f',
  },
  {
    label: 'Coach',
    description: 'Coach workspace access',
    email: 'john@doe.com',
    password: '2226f6026f52',
  },
  {
    label: 'Client',
    description: 'Client portal access',
    email: 'client@hello.com',
    password: '2226f6026f52',
  },
];

function Nav() {
  return (
    <header className='sticky top-3 z-50 px-5 pt-5'>
      <div
        className={`mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-2.5 backdrop-blur-xl md:px-5 md:py-3 ${ui.navShell}`}
      >
        <Link
          href='/'
          className='flex items-center gap-3 text-lg font-semibold tracking-tight'
        >
          <span className='flex h-9 w-9 items-center justify-center rounded-none bg-[#fffdf9] text-xl font-black text-[#35b7a5]'>
            C
          </span>
          <span className='sr-only'>Coaching SaaS Workspace</span>
        </Link>
        <nav
          className={`hidden items-center gap-6 text-base font-medium ${ui.ink} md:flex`}
        >
          <Link href='/how-it-works/'>How it works</Link>
          <Link href='/client-portal/'>Coachee</Link>
          <Link href='/#pricing'>Pricing</Link>
          <Link href='/#trust'>Trust</Link>
        </nav>
        <Link
          href='/intake/'
          className={`rounded-none px-5 py-2.5 text-sm font-semibold ${ui.button}`}
        >
          Start free
        </Link>
      </div>
    </header>
  );
}

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: 'admin@flatlogic.com',
    password: 'f76d928f',
    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>

        <Nav />

        <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>

              <Formik
                initialValues={initialValues}
                enableReinitialize
                onSubmit={(values) => handleSubmit(values)}
              >
                {({ setValues }) => (
                  <Form className='space-y-5'>
                    <div>
                      <p className='mb-3 text-sm font-semibold'>Sign in as</p>
                      <div className='grid gap-2 sm:grid-cols-3'>
                        {demoAccounts.map((account) => (
                          <button
                            key={account.email}
                            type='button'
                            className='rounded-none border border-[#19192d]/10 bg-[#fffdf9] px-3 py-3 text-left transition hover:border-[#35b7a5] hover:bg-[#fffdf9]'
                            onClick={() =>
                              setValues({
                                email: account.email,
                                password: account.password,
                                remember: true,
                              })
                            }
                          >
                            <span className='block text-sm font-semibold text-[#19192d]'>
                              {account.label}
                            </span>
                            <span className='mt-1 block text-xs leading-5 text-[#72798a]'>
                              {account.description}
                            </span>
                          </button>
                        ))}
                      </div>
                    </div>

                    <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-[#35b7a5] focus:ring-4 focus:ring-[#35b7a5]/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-[#35b7a5] focus:ring-4 focus:ring-[#35b7a5]/10 ${ui.border}`}
                        />
                        <button
                          type='button'
                          className='absolute right-4 top-1/2 -translate-y-1/2 text-[#72798a] 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-[#35b7a5]'
                        />
                        <span className={ui.muted}>Remember me</span>
                      </label>
                      <Link
                        href='/forgot'
                        className='font-semibold text-[#35b7a5] 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}`}>
                Don&apos;t have an account yet?{' '}
                <Link
                  href='/register'
                  className='font-semibold text-[#35b7a5] hover:underline'
                >
                  Create one
                </Link>
              </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>;
};
