import React, { useEffect, useMemo, 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 { ToastContainer, toast } from 'react-toastify';
import { mdiEye, mdiEyeOff, mdiInformation } from '@mdi/js';

import BaseButton from '../components/BaseButton';
import BaseButtons from '../components/BaseButtons';
import BaseDivider from '../components/BaseDivider';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import FormCheckRadio from '../components/FormCheckRadio';
import FormField from '../components/FormField';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import { getPageTitle } from '../config';
import { findMe, loginUser, resetAction } from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { useRouter } from 'next/router';

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

type DemoAccount = {
  email: string;
  password: string;
  role: string;
  accent: string;
  summary: string;
};

const DEMO_ACCOUNTS: DemoAccount[] = [
  {
    email: 'super_admin@flatlogic.com',
    password: '946cafba',
    role: 'Super Admin',
    accent: 'border-stone-300 bg-stone-900 text-white',
    summary: 'Global workspace control across organizations and roles.',
  },
  {
    email: 'admin@flatlogic.com',
    password: '946cafba',
    role: 'Admin',
    accent: 'border-amber-200 bg-amber-50 text-stone-900',
    summary: 'Day-to-day operating visibility with organization context.',
  },
  {
    email: 'john@doe.com',
    password: 'bc40952c93f4',
    role: 'Concierge',
    accent: 'border-stone-200 bg-white text-stone-900',
    summary: 'Service coordination, reservation readiness, and updates.',
  },
  {
    email: 'client@hello.com',
    password: 'bc40952c93f4',
    role: 'Customer',
    accent: 'border-amber-200 bg-white text-stone-900',
    summary: 'Customer-side request access and stay visibility.',
  },
];

const ACCESS_CHIPS = ['Super Admin', 'Admin', 'Concierge', 'Customer'];

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

const DEFAULT_LOGIN_VALUES: LoginValues = {
  email: DEMO_ACCOUNTS[0].email,
  password: DEMO_ACCOUNTS[0].password,
  remember: true,
};

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

  const notify = (type, msg) => toast(msg, { type });
  const title = 'Gracey Corporate Stay Portal';

  const registeredOrg = typeof router.query.registeredOrg === 'string' ? router.query.registeredOrg : '';
  const registeredRole = typeof router.query.registeredRole === 'string' ? router.query.registeredRole : '';
  const registeredTenants =
    typeof router.query.registeredTenants === 'string'
      ? router.query.registeredTenants.split(' | ').filter(Boolean)
      : [];

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

  useEffect(() => {
    if (currentUser?.id) {
      router.push('/command-center');
    }
  }, [currentUser?.id, router]);

  useEffect(() => {
    if (errorMessage) {
      notify('error', errorMessage);
    }
  }, [errorMessage]);

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

  const handleSubmit = async (value: LoginValues) => {
    const { remember, ...rest } = value;
    await dispatch(loginUser(rest));
  };

  const chooseLogin = (email: string, password: string) => {
    setInitialValues((prev) => ({
      ...prev,
      email,
      password,
    }));
  };

  const registeredMessage = useMemo(() => {
    if (!registeredOrg) {
      return null;
    }

    return (
      <CardBox className='border border-amber-200 bg-amber-50/90 text-stone-900 shadow-none'>
        <div className='flex items-start gap-3'>
          <BaseIcon className='mt-1 text-amber-700' size={20} path={mdiInformation} />
          <div className='min-w-0 space-y-2'>
            <p className='font-semibold'>
              Your {registeredRole || 'customer'} account was created for {registeredOrg}.
            </p>
            {registeredTenants.length ? (
              <div>
                <p className='text-xs font-semibold uppercase tracking-[0.18em] text-amber-800'>Linked tenants</p>
                <div className='mt-2 flex flex-wrap gap-2'>
                  {registeredTenants.map((tenantName) => (
                    <span
                      key={tenantName}
                      className='inline-flex items-center rounded-full border border-amber-200 bg-white/90 px-3 py-1 text-xs font-medium text-stone-900'
                    >
                      {tenantName}
                    </span>
                  ))}
                </div>
              </div>
            ) : (
              <p className='text-sm text-stone-700'>No linked tenant is shown for that organization yet.</p>
            )}
            <p className='text-xs text-stone-700'>
              Admin and Super Admin accounts are provisioned internally, not through self-signup.
            </p>
          </div>
        </div>
      </CardBox>
    );
  }, [registeredOrg, registeredRole, registeredTenants]);

  return (
    <>
      <Head>
        <title>{getPageTitle('Login')}</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.06fr_0.94fr]'>
            <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'>
                      Portal access
                    </p>
                    <div className='space-y-3'>
                      <h1 className='max-w-2xl text-3xl font-semibold leading-tight text-stone-950 sm:text-[2.6rem]'>
                        {title}
                      </h1>
                      <p className='max-w-2xl text-sm leading-7 text-stone-700 sm:text-base'>
                        Sign in to the private workspace used for booking intake, guest coordination, and billing
                        follow-through.
                      </p>
                    </div>
                    <div className='flex flex-wrap gap-2'>
                      {ACCESS_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.18em] 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'>
                        Operator view
                      </p>
                      <p className='mt-2 text-sm text-stone-700'>Multi-tenant workspace</p>
                    </div>
                    <div>
                      <p className='text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-800'>
                        Service posture
                      </p>
                      <p className='mt-2 text-sm text-stone-700'>Calm, selective, precise</p>
                    </div>
                    <div>
                      <p className='text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-800'>
                        Execution model
                      </p>
                      <p className='mt-2 text-sm text-stone-700'>Request to reservation to billing</p>
                    </div>
                  </div>

                  <div className='space-y-4'>
                    <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'>
                        Demo account access
                      </p>
                    </div>
                    <div className='grid gap-3 lg:grid-cols-2'>
                      {DEMO_ACCOUNTS.map((account) => {
                        const isSelected =
                          initialValues.email === account.email && initialValues.password === account.password;

                        return (
                          <button
                            key={account.email}
                            type='button'
                            onClick={() => chooseLogin(account.email, account.password)}
                            className={`rounded-[1.5rem] border p-4 text-left transition duration-150 hover:-translate-y-0.5 hover:shadow-lg ${account.accent} ${
                              isSelected ? 'ring-2 ring-amber-400/70' : 'ring-1 ring-transparent'
                            }`}
                          >
                            <div className='flex flex-wrap items-center justify-between gap-2'>
                              <p className='text-[11px] font-semibold uppercase tracking-[0.25em] text-current/70'>
                                {account.role}
                              </p>
                              <span className='rounded-full border border-current/15 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-current/70'>
                                Tap to fill
                              </span>
                            </div>
                            <p className='mt-3 break-all text-sm font-medium'>{account.email}</p>
                            <p className='mt-2 font-mono text-sm opacity-80'>{account.password}</p>
                            <p className='mt-3 text-xs leading-5 opacity-75'>{account.summary}</p>
                          </button>
                        );
                      })}
                    </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'>
                  The public experience stays polished and restrained. Operational depth appears only where it
                  belongs: inside the authenticated workspace.
                </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'>
                {registeredMessage}

                <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'>Member sign in</p>
                      <h2 className='text-3xl font-semibold text-stone-950'>Welcome back</h2>
                      <p className='text-sm leading-6 text-stone-600'>
                        Enter your credentials to open the Gracey workspace.
                      </p>
                      <div className='flex flex-wrap gap-2 pt-1'>
                        {ACCESS_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={initialValues} enableReinitialize onSubmit={handleSubmit}>
                      <Form>
                        <FormField label='Login' help='Please enter your login'>
                          <Field name='email' className={AUTH_INPUT_CLASS} />
                        </FormField>

                        <div className='relative'>
                          <FormField label='Password' help='Please enter your password'>
                            <Field name='password' type={showPassword ? 'text' : 'password'} className={AUTH_INPUT_CLASS} />
                          </FormField>
                          <button
                            type='button'
                            className='absolute bottom-8 right-0 flex items-center pr-3 text-stone-500 transition hover:text-stone-800'
                            onClick={() => setShowPassword((prev) => !prev)}
                          >
                            <BaseIcon size={20} path={showPassword ? mdiEyeOff : mdiEye} />
                          </button>
                        </div>

                        <div className='flex flex-col gap-3 text-sm sm:flex-row sm:items-center sm:justify-between'>
                          <FormCheckRadio type='checkbox' label='Remember'>
                            <Field type='checkbox' name='remember' />
                          </FormCheckRadio>

                          <Link className={`${textColor} text-sm font-medium`} href='/forgot'>
                            Forgot password?
                          </Link>
                        </div>

                        <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={isFetching ? 'Loading...' : 'Login'}
                            color='white'
                            disabled={isFetching}
                          />
                        </BaseButtons>

                        <p className='mt-4 text-center text-sm text-stone-600'>
                          Don’t have an account yet?{' '}
                          <Link className={`${textColor} font-medium`} href='/register'>
                            New Account
                          </Link>
                        </p>
                      </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 />
    </>
  );
}

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