import React from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { Field, Form, Formik } from 'formik';
import { ToastContainer, toast } from 'react-toastify';
import axios from 'axios';

import BaseButton from '../components/BaseButton';
import BaseButtons from '../components/BaseButtons';
import BaseDivider from '../components/BaseDivider';
import CardBox from '../components/CardBox';
import FormField from '../components/FormField';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';
import { useRouter } from 'next/router';

type ForgotValues = {
  email: string;
};

const TITLE = 'Gracey Corporate Stay Portal';
const RECOVERY_CHIPS = ['Booking access', 'Service access', 'Billing access'];

const AUTH_INPUT_CLASS = '!bg-white !text-stone-900 placeholder:!text-stone-400 dark:!bg-white dark:!text-stone-900 dark:placeholder:!text-stone-400';

export default function Forgot() {
  const [loading, setLoading] = React.useState(false);
  const router = useRouter();
  const textColor = useAppSelector((state) => state.style.linkColor);
  const notify = (type, msg) => toast(msg, { type, position: 'bottom-center' });

  const handleSubmit = async (value: ForgotValues) => {
    setLoading(true);

    try {
      await axios.post('/auth/send-password-reset-email', value);
      notify('success', 'Please check your email for a password reset link.');
      setTimeout(async () => {
        await router.push('/login');
      }, 3000);
    } catch (error) {
      console.error('Password reset email request failed:', error);
      notify('error', 'Something was wrong. Try again.');
    } finally {
      setLoading(false);
    }
  };

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

      <SectionFullScreen bg='violet'>
        <div className='min-h-screen w-full bg-gradient-to-br from-[#fbf6ee] via-[#f3eadb] to-[#dfc8a5] px-3 py-4 text-stone-900 sm:px-5 sm:py-6 lg:px-8 lg:py-8'>
          <div className='mx-auto flex min-h-[calc(100vh-2rem)] w-full max-w-7xl flex-col overflow-hidden rounded-[2rem] border border-stone-200/90 bg-white/75 shadow-[0_30px_80px_rgba(68,44,23,0.12)] backdrop-blur md:grid md:grid-cols-[1.04fr_0.96fr]'>
            <div className='relative overflow-hidden border-b border-stone-200/80 bg-[linear-gradient(180deg,rgba(255,250,243,0.98),rgba(243,233,216,0.98))] px-5 py-6 sm:px-8 sm:py-8 lg:px-12 lg:py-10 md:border-b-0 md:border-r'>
              <div className='absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(199,152,87,0.18),transparent_28%),radial-gradient(circle_at_bottom_left,rgba(255,255,255,0.85),transparent_34%)]' />

              <div className='relative z-10 flex h-full flex-col justify-between gap-6'>
                <div className='space-y-6 sm:space-y-8'>
                  <div className='space-y-4'>
                    <p className='text-[11px] font-semibold uppercase tracking-[0.34em] text-stone-500'>
                      Credential recovery
                    </p>
                    <div className='space-y-3'>
                      <h1 className='max-w-2xl text-3xl font-semibold leading-tight text-stone-950 sm:text-[2.55rem]'>
                        Restore access without losing your operating context.
                      </h1>
                      <p className='max-w-2xl text-sm leading-7 text-stone-700 sm:text-base'>
                        Request a reset link for the email you use in Gracey and return to the workspace with a fresh
                        password.
                      </p>
                    </div>
                    <div className='flex flex-wrap gap-2'>
                      {RECOVERY_CHIPS.map((chip) => (
                        <span
                          key={chip}
                          className='inline-flex items-center rounded-full border border-stone-200 bg-white/80 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-stone-600'
                        >
                          {chip}
                        </span>
                      ))}
                    </div>
                  </div>

                  <div className='grid gap-3 rounded-[1.75rem] border border-amber-200/70 bg-white/60 p-4 sm:grid-cols-3 sm:p-5'>
                    <div>
                      <p className='text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-800'>
                        Delivery path
                      </p>
                      <p className='mt-2 text-sm text-stone-700'>Email-based reset flow</p>
                    </div>
                    <div>
                      <p className='text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-800'>
                        Access posture
                      </p>
                      <p className='mt-2 text-sm text-stone-700'>Private and credential-safe</p>
                    </div>
                    <div>
                      <p className='text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-800'>
                        Return path
                      </p>
                      <p className='mt-2 text-sm text-stone-700'>Back to portal login</p>
                    </div>
                  </div>

                  <div className='rounded-[1.75rem] border border-stone-200/90 bg-white/55 p-5'>
                    <div className='flex items-center gap-3'>
                      <span className='h-px w-10 bg-amber-400/80' />
                      <p className='text-xs font-semibold uppercase tracking-[0.28em] text-stone-600'>Recovery notes</p>
                    </div>

                    <div className='mt-4 space-y-4 text-sm leading-7 text-stone-700'>
                      <p>
                        Use the same email address you rely on for booking, service, or billing access inside the
                        workspace.
                      </p>
                      <p>
                        Once the request is submitted, Gracey sends a time-sensitive link so you can create a new
                        password and re-enter the portal securely.
                      </p>
                      <p className='text-stone-600'>
                        If you no longer have access to the original inbox, contact an internal administrator before
                        attempting another reset.
                      </p>
                    </div>
                  </div>
                </div>

                <div className='rounded-[1.5rem] border border-stone-200/90 bg-white/55 p-4 text-sm leading-6 text-stone-600'>
                  Recovery links are delivered only to recognized account emails and are intended for authorized
                  operators and customers.
                </div>
              </div>
            </div>

            <div className='flex items-center justify-center bg-[linear-gradient(180deg,rgba(255,255,255,0.74),rgba(255,250,242,0.96))] px-4 py-6 sm:px-8 sm:py-8 lg:px-10 lg:py-10'>
              <div className='w-full max-w-xl space-y-5 sm:space-y-6'>
                <CardBox className='border border-stone-200/90 bg-white/95 text-stone-950 shadow-[0_22px_55px_rgba(60,38,20,0.08)] dark:!border-stone-200 dark:!bg-white dark:!text-stone-950'>
                  <div className='space-y-5 sm:space-y-6'>
                    <div className='space-y-3'>
                      <p className='text-xs font-semibold uppercase tracking-[0.28em] text-stone-500'>Password reset</p>
                      <h2 className='text-3xl font-semibold text-stone-950'>Restore your password</h2>
                      <p className='text-sm leading-6 text-stone-600'>
                        Enter your email and we’ll send the next secure step to restore access to the Gracey portal.
                      </p>
                      <div className='flex flex-wrap gap-2 pt-1'>
                        {RECOVERY_CHIPS.map((chip) => (
                          <span
                            key={chip}
                            className='inline-flex items-center rounded-full border border-stone-200 bg-stone-50 px-3 py-1 text-[11px] font-medium text-stone-600'
                          >
                            {chip}
                          </span>
                        ))}
                      </div>
                    </div>

                    <Formik
                      initialValues={{
                        email: '',
                      }}
                      onSubmit={(values) => handleSubmit(values)}
                    >
                      <Form>
                        <FormField label='Email' help='Please enter your email'>
                          <Field type='email' name='email' className={AUTH_INPUT_CLASS} />
                        </FormField>

                        <BaseDivider />

                        <BaseButtons className='w-full' type='justify-center' classAddon='mb-3' mb='mb-0'>
                          <BaseButton
                            className='w-full justify-center border-[#4d3929] bg-[#4d3929] text-white hover:bg-[#3d2d21] focus:ring-amber-300'
                            type='submit'
                            label={loading ? 'Loading...' : 'Send reset link'}
                            color='white'
                            disabled={loading}
                          />
                        </BaseButtons>

                        <div className='flex flex-col items-center gap-3 text-center sm:flex-row sm:justify-between sm:text-left'>
                          <p className='text-sm text-stone-600'>Remembered your password?</p>
                          <Link className={`${textColor} text-sm font-medium`} href='/login'>
                            Return to Login
                          </Link>
                        </div>
                      </Form>
                    </Formik>
                  </div>
                </CardBox>

                <div className='flex flex-col items-center justify-center gap-3 border-t border-stone-200 pt-1 text-center text-sm text-stone-600 sm:flex-row'>
                  <p>© 2026 {TITLE}. © All rights reserved</p>
                  <div className='flex flex-wrap items-center justify-center gap-4'>
                    <Link className={`${textColor} text-sm`} href='/privacy-policy/'>
                      Privacy Policy
                    </Link>
                    <Link className={`${textColor} text-sm`} href='/terms-of-use/'>
                      Terms of Use
                    </Link>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </SectionFullScreen>

      <ToastContainer />
    </>
  );
}

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