import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { toast, ToastContainer } from 'react-toastify';

import LayoutGuest from '../layouts/Guest';
import { getPageTitle } from '../config';
import { findMe, loginUser, resetAction } from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { hasPermission } from '../helpers/userPermissions';

const heroImage =
  'https://images.pexels.com/photos/1126728/pexels-photo-1126728.jpeg?auto=compress&cs=tinysrgb&w=1800';

const demoCredentials = [
  {
    label: 'Supplier admin',
    role: 'Administrator',
    name: 'Northstar Operations',
    email: 'admin@flatlogic.com',
    password: '3ab96dc1',
    note: 'Full access to catalog, buyer accounts, price lists, orders, samples, and fulfillment workflows.',
  },
  {
    label: 'Buyer admin',
    role: 'Customer Buyer Admin',
    name: 'Maria Alvarez',
    email: 'maria.alvarez@harbortable.com',
    password: 'a04a876c6d59',
    note: 'Purchasing lead with order, sample, quote, saved guide, and team queue access.',
  },
  {
    label: 'Buyer user',
    role: 'Customer Buyer',
    name: 'Owen Price',
    email: 'owen.price@harbortable.com',
    password: 'a04a876c6d59',
    note: 'Restaurant buyer focused on contract catalog, reorder history, sample requests, and PO checkout.',
  },
];

export default function Login() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [email, setEmail] = useState(demoCredentials[0].email);
  const [password, setPassword] = useState(demoCredentials[0].password);
  const [remember, setRemember] = useState(true);
  const [showPassword, setShowPassword] = useState(false);
  const {
    currentUser,
    isFetching,
    errorMessage,
    token,
    notify: notifyState,
  } = useAppSelector((state) => state.auth);

  const getReturnTo = () => {
    const value = Array.isArray(router.query.returnTo)
      ? router.query.returnTo[0]
      : router.query.returnTo;

    if (value && value.startsWith('/') && !value.startsWith('//')) {
      return value;
    }

    return '';
  };

  useEffect(() => {
    if (!router.isReady) {
      return;
    }

    if (getReturnTo().startsWith('/buyer-portal')) {
      setEmail(demoCredentials[1].email);
      setPassword(demoCredentials[1].password);
    }
  }, [router.isReady]);

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

  useEffect(() => {
    if (currentUser?.id) {
      const returnTo = getReturnTo();

      if (returnTo) {
        router.push(returnTo);
        return;
      }

      const hasSupplierAccess = hasPermission(currentUser, [
        'READ_ACCOUNTS',
        'READ_PRODUCTS',
        'READ_ORDERS',
        'READ_INVENTORY_ITEMS',
      ]);

      if (
        hasPermission(currentUser, 'READ_BUYER_PORTAL') &&
        !hasSupplierAccess
      ) {
        router.push('/buyer-portal/');
        return;
      }

      router.push('/dashboard/');
    }
  }, [currentUser, 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]);

  const applyCredentials = (credentials: (typeof demoCredentials)[number]) => {
    setEmail(credentials.email);
    setPassword(credentials.password);
    setRemember(true);
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    await dispatch(loginUser({ email, password }));
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Login')}</title>
        <meta
          name='description'
          content='Unified sign in for the Northstar Foodservice supplier and distributor portal.'
        />
      </Head>

      <main className='min-h-screen bg-stone-50 text-slate-950'>
        <section className='grid min-h-screen lg:grid-cols-[minmax(0,1.1fr)_500px]'>
          <div className='relative hidden overflow-hidden lg:block'>
            <img
              src={heroImage}
              alt='Fresh foodservice ingredients ready for distributor operations'
              className='absolute inset-0 h-full w-full object-cover'
            />
            <div className='absolute inset-0 bg-gradient-to-r from-slate-950/80 via-slate-950/35 to-transparent' />
            <div className='relative flex h-full flex-col justify-between p-12 text-white'>
              <div>
                <p className='text-sm font-semibold uppercase tracking-[0.24em] text-emerald-200'>
                  Northstar Foodservice
                </p>
                <h1 className='mt-5 max-w-2xl text-5xl font-semibold leading-tight'>
                  One sign-in for supplier teams and foodservice buyers
                </h1>
                <p className='mt-5 max-w-xl text-base leading-8 text-stone-100'>
                  Route each role into the right workspace for contract
                  pricing, product catalogs, purchase orders, sample requests,
                  saved lists, and fulfillment handoff.
                </p>
              </div>

              <div className='grid max-w-2xl gap-3 sm:grid-cols-3'>
                <div className='border-l-4 border-emerald-300 bg-slate-950/45 p-4 backdrop-blur'>
                  <p className='text-xs uppercase tracking-[0.18em] text-stone-300'>
                    Catalog
                  </p>
                  <p className='mt-2 font-semibold'>Contract SKUs</p>
                </div>
                <div className='border-l-4 border-amber-300 bg-slate-950/45 p-4 backdrop-blur'>
                  <p className='text-xs uppercase tracking-[0.18em] text-stone-300'>
                    Accounts
                  </p>
                  <p className='mt-2 font-semibold'>Buyer pricing</p>
                </div>
                <div className='border-l-4 border-sky-300 bg-slate-950/45 p-4 backdrop-blur'>
                  <p className='text-xs uppercase tracking-[0.18em] text-stone-300'>
                    Workflow
                  </p>
                  <p className='mt-2 font-semibold'>Orders to dock</p>
                </div>
              </div>
            </div>
          </div>

          <div className='flex items-center justify-center px-5 py-4 lg:py-2'>
            <div className='w-full max-w-md'>
              <div className='flex items-center justify-between gap-4'>
                <Link
                  href='/'
                  className='inline-flex text-sm font-semibold text-emerald-700'
                >
                  Back to portal overview
                </Link>
                <span className='text-sm font-semibold text-slate-500'>
                  One login for every role
                </span>
              </div>

              <div className='mt-3 overflow-hidden border border-stone-200 bg-white shadow-sm'>
                <div className='h-1 bg-emerald-500' />
                <div className='p-3 sm:p-4'>
                  <p className='text-xs font-semibold uppercase tracking-[0.22em] text-emerald-700'>
                    Unified sign in
                  </p>
                  <h2 className='mt-2 text-2xl font-semibold'>
                    Open your workspace
                  </h2>
                  <p className='mt-2 text-sm leading-6 text-slate-600'>
                    Use supplier or buyer credentials. The app routes each user
                    into the right workspace based on role permissions.
                  </p>

                  <div className='mt-3 grid gap-2'>
                    {demoCredentials.map((credentials) => {
                      const isActive =
                        email === credentials.email &&
                        password === credentials.password;

                      return (
                        <button
                          key={credentials.email}
                          type='button'
                          onClick={() => applyCredentials(credentials)}
                          className={`rounded-xl border px-3 py-2.5 text-left transition ${
                            isActive
                              ? 'border-emerald-300 bg-emerald-50'
                              : 'border-stone-200 bg-stone-50 hover:border-emerald-200 hover:bg-emerald-50'
                          }`}
                        >
                          <div className='grid gap-2 sm:grid-cols-[minmax(0,1fr)_170px] sm:items-center'>
                            <div className='min-w-0'>
                              <div className='flex items-center gap-2'>
                                <p className='truncate text-sm font-bold text-slate-950'>
                                  {credentials.label}
                                </p>
                                {isActive && (
                                  <span className='rounded-full bg-emerald-600 px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.12em] text-white'>
                                    Active
                                  </span>
                                )}
                              </div>
                              <p className='mt-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-emerald-700'>
                                {credentials.role}
                              </p>
                            </div>
                            <div className='flex min-w-0 items-center justify-between gap-2 sm:block'>
                              <div className='min-w-0'>
                                <p className='truncate text-xs font-semibold text-slate-900 sm:hidden'>
                                  {credentials.name}
                                </p>
                                <p className='truncate font-mono text-xs text-slate-600'>
                                  {credentials.email}
                                </p>
                                <p className='font-mono text-xs text-slate-500'>
                                  {credentials.password}
                                </p>
                              </div>
                              <span className='shrink-0 rounded-full bg-white px-2.5 py-1 text-xs font-semibold text-slate-600 shadow-sm sm:hidden'>
                                Use
                              </span>
                            </div>
                          </div>
                          <div className='mt-1 hidden items-center justify-between gap-2 sm:flex'>
                            <p className='truncate text-xs font-semibold text-slate-900'>
                              {credentials.name}
                            </p>
                            <span className='rounded-full bg-white px-2.5 py-1 text-xs font-semibold text-slate-600 shadow-sm'>
                              Use
                            </span>
                          </div>
                        </button>
                      );
                    })}
                  </div>

                  {errorMessage && (
                    <div className='mt-4 rounded-xl border border-rose-200 bg-rose-50 p-3 text-sm text-rose-800'>
                      {errorMessage}
                    </div>
                  )}

                  <form className='mt-4 space-y-3' onSubmit={handleSubmit}>
                    <label className='block'>
                      <span className='text-sm font-semibold text-slate-900'>
                        Email
                      </span>
                      <input
                        name='email'
                        value={email}
                        onChange={(event) => setEmail(event.target.value)}
                        type='email'
                        autoComplete='email'
                        className='mt-1.5 h-11 w-full rounded-xl border border-stone-300 bg-white px-4 text-slate-950 outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100'
                      />
                    </label>

                    <label className='block'>
                      <span className='text-sm font-semibold text-slate-900'>
                        Password
                      </span>
                      <div className='mt-1.5 flex h-11 overflow-hidden rounded-xl border border-stone-300 bg-white focus-within:border-emerald-500 focus-within:ring-2 focus:ring-emerald-100'>
                        <input
                          name='password'
                          value={password}
                          onChange={(event) => setPassword(event.target.value)}
                          type={showPassword ? 'text' : 'password'}
                          autoComplete='current-password'
                          className='min-w-0 flex-1 border-0 bg-transparent px-4 text-slate-950 outline-none'
                        />
                        <button
                          type='button'
                          onClick={() => setShowPassword((value) => !value)}
                          className='px-4 text-sm font-semibold text-slate-500 hover:text-emerald-700'
                        >
                          {showPassword ? 'Hide' : 'Show'}
                        </button>
                      </div>
                    </label>

                    <div className='flex items-center justify-between gap-4 text-sm'>
                      <label className='inline-flex items-center gap-2 font-semibold text-slate-600'>
                        <input
                          type='checkbox'
                          checked={remember}
                          onChange={(event) =>
                            setRemember(event.target.checked)
                          }
                          className='h-4 w-4 rounded border-stone-300 text-emerald-600 focus:ring-emerald-500'
                        />
                        Remember
                      </label>
                      <Link
                        href='/forgot'
                        className='font-semibold text-emerald-700'
                      >
                        Forgot password?
                      </Link>
                    </div>

                    <button
                      type='submit'
                      disabled={isFetching}
                      className='h-11 w-full rounded-xl bg-emerald-500 px-5 text-sm font-bold text-slate-950 shadow-sm transition hover:bg-emerald-400 disabled:cursor-not-allowed disabled:opacity-70'
                    >
                      {isFetching ? 'Signing in...' : 'Sign in'}
                    </button>
                  </form>

                </div>
              </div>
            </div>
          </div>
        </section>
      </main>
      <ToastContainer />
    </>
  );
}

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