import {
  mdiBankOutline,
  mdiCheckDecagramOutline,
  mdiClipboardClockOutline,
  mdiFileDocumentOutline,
  mdiLogin,
  mdiMapMarkerRadiusOutline,
  mdiOfficeBuildingCogOutline,
  mdiShieldCheckOutline,
  mdiWalletOutline,
} from '@mdi/js';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useEffect, useMemo } from 'react';
import BaseButton from '../components/BaseButton';
import BaseDivider from '../components/BaseDivider';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import { getPageTitle } from '../config';
import { getLoginRoute, getWorkspaceRoute } from '../helpers/workspace';
import LayoutGuest from '../layouts/Guest';
import { findMe } from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';

const moduleCards = [
  {
    title: 'Budgeting and fund allocation',
    description: 'Approved allocations, commitment exposure, reallocations, and fiscal-year control across funding programs.',
    icon: mdiBankOutline,
  },
  {
    title: 'Procurement and approvals',
    description: 'Requisition-to-award workflow with internal approvals, tender visibility, and contract handoff.',
    icon: mdiClipboardClockOutline,
  },
  {
    title: 'Contracts and vendors',
    description: 'Vendor qualification, compliance review, contract expiry monitoring, and payment readiness.',
    icon: mdiFileDocumentOutline,
  },
  {
    title: 'Projects and rollout oversight',
    description: 'Province-level implementation tracking for school broadband, digital centers, rural connectivity, and ICT programs.',
    icon: mdiMapMarkerRadiusOutline,
  },
];

const controlPoints = [
  'Approval-aware procurement workflow from requisition to payment',
  'Vendor compliance, document expiry, and audit-ready record trails',
  'Executive summary with budget, contract, project, and risk visibility',
  'Operational links into the existing admin interface and CRUD work areas',
];

export default function HomePage() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { currentUser, token } = useAppSelector((state) => state.auth);

  const workspaceRoute = useMemo(
    () => getWorkspaceRoute(currentUser?.app_role?.name),
    [currentUser?.app_role?.name],
  );

  useEffect(() => {
    const existingToken = token || (typeof window !== 'undefined' ? localStorage.getItem('token') : '');

    if (existingToken && !currentUser?.id) {
      dispatch(findMe());
    }
  }, [currentUser?.id, dispatch, token]);

  useEffect(() => {
    if (currentUser?.id) {
      router.replace(workspaceRoute);
    }
  }, [currentUser?.id, router, workspaceRoute]);

  const getProtectedHref = (href: string) => (currentUser?.id ? href : getLoginRoute(href));

  const primaryWorkspaceHref = currentUser?.id ? workspaceRoute : getLoginRoute('/executive-summary');
  const dashboardHref = currentUser?.id ? '/dashboard' : getLoginRoute('/dashboard');

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

      <div className='min-h-screen bg-slate-100 text-slate-900'>
        <header className='border-b border-slate-200 bg-white'>
          <div className='mx-auto flex max-w-7xl items-center justify-between gap-4 px-6 py-4'>
            <div>
              <p className='text-xs font-semibold uppercase tracking-[0.24em] text-slate-500'>National public fund authority platform</p>
              <h1 className='mt-1 text-2xl font-semibold tracking-tight text-slate-950'>FDSU ERP</h1>
            </div>
            <div className='flex flex-wrap items-center gap-3'>
              <BaseButton href={currentUser?.id ? workspaceRoute : '/login'} color='whiteDark' icon={mdiLogin} label={currentUser?.id ? 'My workspace' : 'Login'} />
              <BaseButton href={dashboardHref} color='info' icon={mdiOfficeBuildingCogOutline} label='Admin interface' />
            </div>
          </div>
        </header>

        <main className='mx-auto max-w-7xl px-6 py-8'>
          <section className='grid gap-6 xl:grid-cols-[1.55fr,1fr]'>
            <CardBox className='border border-slate-200 bg-slate-950 text-slate-100'>
              <div className='max-w-4xl'>
                <p className='text-xs font-semibold uppercase tracking-[0.24em] text-slate-400'>Institutional ERP foundation</p>
                <h2 className='mt-4 text-4xl font-semibold tracking-tight text-white'>
                  Operational control for budgeting, procurement, contract management, compliance, and digital inclusion rollout.
                </h2>
                <p className='mt-5 max-w-3xl text-base leading-7 text-slate-300'>
                  FDSU ERP is designed as a serious working environment for finance, procurement, project delivery, internal control, audit, and executive leadership.
                  It centralizes recordkeeping, approvals, payment oversight, vendor qualification, contract obligations, and province-level implementation in one platform.
                </p>

                <div className='mt-8 flex flex-wrap gap-3'>
                  <BaseButton href={primaryWorkspaceHref} color='info' label={currentUser?.id ? 'Open my workspace' : 'Open executive summary'} />
                  <BaseButton href={getProtectedHref('/requisitions/requisitions-new')} color='whiteDark' label='Create requisition' />
                  <BaseButton href={getProtectedHref('/approvals/approvals-list')} color='whiteDark' label='Open approval inbox' />
                </div>
              </div>
            </CardBox>

            <CardBox className='border border-slate-200 bg-white'>
              <p className='text-xs font-semibold uppercase tracking-[0.24em] text-slate-500'>What the first delivery includes</p>
              <div className='mt-5 space-y-3'>
                {controlPoints.map((item) => (
                  <div key={item} className='flex items-start gap-3 rounded-md border border-slate-200 bg-slate-50 px-4 py-3'>
                    <span className='mt-0.5 flex h-6 w-6 items-center justify-center rounded-full bg-slate-900 text-white'>
                      <BaseIcon path={mdiShieldCheckOutline} size={14} />
                    </span>
                    <p className='text-sm leading-6 text-slate-700'>{item}</p>
                  </div>
                ))}
              </div>
              <BaseDivider />
              <div className='grid grid-cols-2 gap-3'>
                <div className='rounded-md border border-slate-200 p-4'>
                  <p className='text-xs uppercase tracking-[0.18em] text-slate-400'>Interface style</p>
                  <p className='mt-2 text-sm font-medium text-slate-900'>Dense, audit-conscious, line-of-business layout</p>
                </div>
                <div className='rounded-md border border-slate-200 p-4'>
                  <p className='text-xs uppercase tracking-[0.18em] text-slate-400'>Access</p>
                  <p className='mt-2 text-sm font-medium text-slate-900'>Public landing with role-aware sign-in routing into the secured workspace</p>
                </div>
              </div>
            </CardBox>
          </section>

          <section className='mt-8 grid gap-4 lg:grid-cols-2 xl:grid-cols-4'>
            {moduleCards.map((card) => (
              <CardBox key={card.title} className='h-full border border-slate-200 bg-white'>
                <div className='flex items-start justify-between gap-3'>
                  <div>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-slate-500'>ERP module</p>
                    <h3 className='mt-3 text-lg font-semibold text-slate-900'>{card.title}</h3>
                    <p className='mt-3 text-sm leading-6 text-slate-600'>{card.description}</p>
                  </div>
                  <div className='flex h-11 w-11 items-center justify-center rounded-md border border-slate-200 bg-slate-50'>
                    <BaseIcon path={card.icon} size={20} className='text-slate-700' />
                  </div>
                </div>
              </CardBox>
            ))}
          </section>

          <section className='mt-8 grid gap-6 xl:grid-cols-[1.2fr,1fr]'>
            <CardBox className='border border-slate-200 bg-white'>
              <p className='text-xs font-semibold uppercase tracking-[0.24em] text-slate-500'>Operational workflow</p>
              <h3 className='mt-2 text-2xl font-semibold text-slate-900'>Thin-slice journey now wired into the app</h3>
              <div className='mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4'>
                {[
                  ['1', 'Create requisition', 'Capture procurement demand and route it into the formal approval chain.'],
                  ['2', 'Review approvals', 'Use the new executive summary and approval inbox to identify pending actions.'],
                  ['3', 'Inspect contracts', 'Track contracts nearing expiry and top-value commitments in one place.'],
                  ['4', 'Monitor rollout', 'Review project concentration by province and outstanding operational risk.'],
                ].map(([step, title, text]) => (
                  <div key={step} className='rounded-md border border-slate-200 bg-slate-50 p-4'>
                    <div className='flex h-8 w-8 items-center justify-center rounded-full bg-slate-900 text-sm font-semibold text-white'>{step}</div>
                    <p className='mt-4 font-medium text-slate-900'>{title}</p>
                    <p className='mt-2 text-sm leading-6 text-slate-600'>{text}</p>
                  </div>
                ))}
              </div>
            </CardBox>

            <CardBox className='border border-slate-200 bg-white'>
              <p className='text-xs font-semibold uppercase tracking-[0.24em] text-slate-500'>Quick access</p>
              <div className='mt-5 grid gap-3'>
                {[
                  { href: currentUser?.id ? workspaceRoute : getLoginRoute('/executive-summary'), icon: mdiWalletOutline, title: 'Executive summary', text: 'Operational overview, approval queue, risk panel, and rollout indicators.' },
                  { href: getProtectedHref('/requisitions/requisitions-list'), icon: mdiClipboardClockOutline, title: 'Requisitions', text: 'Create, list, and review procurement requests.' },
                  { href: getProtectedHref('/contracts/contracts-list'), icon: mdiFileDocumentOutline, title: 'Contracts', text: 'Open the contract register and milestone detail views.' },
                  { href: getProtectedHref('/vendors/vendors-list'), icon: mdiCheckDecagramOutline, title: 'Vendor master', text: 'Access qualification, banking data, compliance, and related history.' },
                ].map((item) => (
                  <Link key={item.href} href={item.href} className='rounded-md border border-slate-200 p-4 transition hover:border-slate-300 hover:bg-slate-50'>
                    <div className='flex items-start gap-3'>
                      <div className='mt-0.5 flex h-10 w-10 items-center justify-center rounded-md border border-slate-200 bg-slate-50'>
                        <BaseIcon path={item.icon} size={18} className='text-slate-700' />
                      </div>
                      <div>
                        <p className='font-medium text-slate-900'>{item.title}</p>
                        <p className='mt-1 text-sm leading-6 text-slate-600'>{item.text}</p>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            </CardBox>
          </section>
        </main>
      </div>
    </>
  );
}

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