import {
  mdiAccountGroup,
  mdiAlertCircleOutline,
  mdiCashRegister,
  mdiChartBoxOutline,
  mdiClockOutline,
  mdiCurrencyUsd,
  mdiFileDocumentOutline,
  mdiRefresh,
  mdiStoreMarker,
} from '@mdi/js';
import axios from 'axios';
import dayjs from 'dayjs';
import Head from 'next/head';
import Link from 'next/link';
import React, { ReactElement, useCallback, useEffect, useMemo, useState } from 'react';
import BaseButton from '../components/BaseButton';
import BaseDivider from '../components/BaseDivider';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import FormField from '../components/FormField';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { hasPermission } from '../helpers/userPermissions';
import LayoutAuthenticated from '../layouts/Authenticated';
import { useAppSelector } from '../stores/hooks';

type OutletOption = {
  id: string;
  code: string;
  name: string;
  address?: string;
  gps_radius_m?: number;
};

type RecentRun = {
  id: string;
  name: string;
  status: string;
  period_start: string;
  period_end: string;
  generated_at: string;
  employeeCount: number;
  totalTakeHomePay: number;
  outlet?: {
    id: string;
    name: string;
    code: string;
  } | null;
  generated_by_user?: string | null;
};

type PreviewEmployee = {
  id: string;
  employee_code?: string;
  full_name: string;
  workdays: number;
  late_count: number;
  kpi_score: number;
  overtime_hours_total: number;
  take_home_pay: number;
  attendance_record_count: number;
  has_kpi_score: boolean;
  job_position?: {
    name?: string;
  } | null;
};

type PreviewResponse = {
  config: {
    periodMonth: string;
    periodStart: string;
    periodEnd: string;
    standardWorkdays: number;
    maxKpiAllowance: number;
    latePenaltyAmount: number;
    distributionMethod: 'equal' | 'weighted_by_position';
  };
  outlet: {
    id: string;
    name: string;
    code: string;
    address?: string;
    gps_radius_m?: number;
  };
  readiness: {
    blockers: string[];
    warnings: string[];
    employeeCount: number;
    missingAttendanceCount: number;
    missingKpiCount: number;
    existingRunCount: number;
    latestExistingRun?: {
      id: string;
      name: string;
      status: string;
      generated_at: string;
      generated_by_user?: string | null;
    } | null;
  };
  totals: {
    projectedTakeHomePay: number;
    averageTakeHomePay: number;
    totalBaseSalary: number;
    totalMealTransport: number;
    totalPositionAllowance: number;
    totalKpiAllowance: number;
    totalRevenueBonus: number;
    totalServiceCharge: number;
    totalOvertime: number;
    totalDeductions: number;
    totalOvertimeHours: number;
    grossRevenue: number;
    serviceChargePool: number;
    bonusPool: number;
    bonusRate: number;
    bonusTierLabel: string;
  };
  employees: PreviewEmployee[];
};

type GenerateResponse = {
  success: boolean;
  payrollPeriod: {
    id: string;
    name: string;
    status: string;
    generated_at: string;
  };
  generatedCount: number;
  payslipCount: number;
  totals: PreviewResponse['totals'];
  warnings: string[];
};

type WorkbenchResponse = {
  outlets: OutletOption[];
  recentRuns: RecentRun[];
};

type WorkbenchForm = {
  outletId: string;
  periodMonth: string;
  standardWorkdays: number;
  maxKpiAllowance: number;
  latePenaltyAmount: number;
  distributionMethod: 'equal' | 'weighted_by_position';
};

const initialForm: WorkbenchForm = {
  outletId: '',
  periodMonth: dayjs().subtract(1, 'month').format('YYYY-MM'),
  standardWorkdays: 26,
  maxKpiAllowance: 500000,
  latePenaltyAmount: 1000,
  distributionMethod: 'weighted_by_position',
};

const formatCurrency = (value: number) =>
  new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency: 'IDR',
    maximumFractionDigits: 0,
  }).format(Number.isFinite(value) ? value : 0);

const formatShortDate = (value?: string | null) => {
  if (!value) {
    return '—';
  }

  return dayjs(value).format('DD MMM YYYY');
};

const formatMonthLabel = (value: string) => {
  if (!value) {
    return 'Belum dipilih';
  }

  return dayjs(`${value}-01`).format('MMMM YYYY');
};

const getStatusBadgeClasses = (status?: string) => {
  switch (status) {
    case 'paid':
      return 'bg-emerald-100 text-emerald-700 border border-emerald-200';
    case 'finance_approved':
    case 'approved':
      return 'bg-sky-100 text-sky-700 border border-sky-200';
    case 'hr_approved':
    case 'generated':
      return 'bg-violet-100 text-violet-700 border border-violet-200';
    case 'draft':
    default:
      return 'bg-slate-100 text-slate-700 border border-slate-200';
  }
};

const getErrorMessage = (error: unknown) => {
  if (axios.isAxiosError(error)) {
    if (typeof error.response?.data === 'string' && error.response.data) {
      return error.response.data;
    }

    return error.message;
  }

  if (error instanceof Error) {
    return error.message;
  }

  return 'Something went wrong while loading payroll data.';
};

const StatCard = ({
  icon,
  label,
  value,
  hint,
}: {
  icon: string;
  label: string;
  value: string;
  hint: string;
}) => (
  <div className="rounded-2xl border border-slate-200/80 bg-white/90 p-4 shadow-sm">
    <div className="mb-3 flex items-center justify-between">
      <span className="text-sm font-medium text-slate-500">{label}</span>
      <span className="inline-flex h-10 w-10 items-center justify-center rounded-full bg-slate-950 text-white">
        <BaseIcon path={icon} size={20} />
      </span>
    </div>
    <div className="text-2xl font-semibold text-slate-950">{value}</div>
    <div className="mt-2 text-sm text-slate-500">{hint}</div>
  </div>
);

const PayrollWorkbenchPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const canGenerate = hasPermission(currentUser, 'CREATE_PAYROLL_PERIODS');

  const [workbench, setWorkbench] = useState<WorkbenchResponse>({ outlets: [], recentRuns: [] });
  const [form, setForm] = useState<WorkbenchForm>(initialForm);
  const [preview, setPreview] = useState<PreviewResponse | null>(null);
  const [generatedRun, setGeneratedRun] = useState<GenerateResponse | null>(null);
  const [isLoadingWorkbench, setIsLoadingWorkbench] = useState(true);
  const [isLoadingPreview, setIsLoadingPreview] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [previewDirty, setPreviewDirty] = useState(false);

  const selectedOutlet = useMemo(
    () => workbench.outlets.find((outlet) => outlet.id === form.outletId),
    [form.outletId, workbench.outlets],
  );

  const fetchWorkbench = useCallback(async () => {
    setIsLoadingWorkbench(true);
    setErrorMessage('');

    try {
      const { data } = await axios.get<WorkbenchResponse>('payroll_periods/workbench');
      setWorkbench(data);

      setForm((current) => {
        if (current.outletId || !data.outlets.length) {
          return current;
        }

        return {
          ...current,
          outletId: data.outlets[0].id,
        };
      });
    } catch (error) {
      setErrorMessage(getErrorMessage(error));
    } finally {
      setIsLoadingWorkbench(false);
    }
  }, []);

  const fetchPreview = useCallback(async (payload: WorkbenchForm) => {
    if (!payload.outletId || !payload.periodMonth) {
      return;
    }

    setIsLoadingPreview(true);
    setErrorMessage('');

    try {
      const search = new URLSearchParams({
        outletId: payload.outletId,
        periodMonth: payload.periodMonth,
        standardWorkdays: String(payload.standardWorkdays),
        maxKpiAllowance: String(payload.maxKpiAllowance),
        latePenaltyAmount: String(payload.latePenaltyAmount),
        distributionMethod: payload.distributionMethod,
      });

      const { data } = await axios.get<PreviewResponse>(`payroll_periods/workbench/preview?${search.toString()}`);
      setPreview(data);
      setPreviewDirty(false);
    } catch (error) {
      setPreview(null);
      setErrorMessage(getErrorMessage(error));
    } finally {
      setIsLoadingPreview(false);
    }
  }, []);

  useEffect(() => {
    void fetchWorkbench();
  }, [fetchWorkbench]);

  useEffect(() => {
    if (!form.outletId) {
      return;
    }

    void fetchPreview(form);
  }, [fetchPreview, form.outletId, form.periodMonth]);

  const handleFieldChange = <K extends keyof WorkbenchForm>(field: K, value: WorkbenchForm[K]) => {
    setGeneratedRun(null);
    setForm((current) => ({
      ...current,
      [field]: value,
    }));

    if (field === 'outletId' || field === 'periodMonth') {
      setPreviewDirty(false);
      return;
    }

    setPreviewDirty(true);
  };

  const handleGenerate = async () => {
    setIsGenerating(true);
    setErrorMessage('');

    try {
      const { data } = await axios.post<GenerateResponse>('payroll_periods/workbench/generate', {
        data: form,
      });

      setGeneratedRun(data);
      await fetchWorkbench();
      await fetchPreview(form);
    } catch (error) {
      setGeneratedRun(null);
      setErrorMessage(getErrorMessage(error));
    } finally {
      setIsGenerating(false);
    }
  };

  const topEmployees = preview?.employees.slice(0, 6) || [];

  return (
    <>
      <Head>
        <title>{getPageTitle('Payroll Workbench')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiCashRegister} title="Payroll Workbench" main>
          <BaseButton href="/payroll_periods/payroll_periods-list" color="info" label="Payroll periods" />
        </SectionTitleLineWithButton>

        <CardBox className="overflow-hidden border-0 bg-gradient-to-br from-slate-950 via-slate-900 to-teal-700 text-white shadow-2xl">
          <div className="grid gap-6 lg:grid-cols-[1.2fr,0.8fr]">
            <div>
              <span className="inline-flex items-center rounded-full border border-white/15 bg-white/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.24em] text-teal-100">
                HRIS FnB • Monthly Payroll Run
              </span>
              <h2 className="mt-4 text-3xl font-semibold leading-tight md:text-4xl">
                Generate payroll drafts from attendance, KPI, overtime, omzet, and service charge in one flow.
              </h2>
              <p className="mt-4 max-w-2xl text-sm leading-7 text-slate-200 md:text-base">
                This first iteration gives HR and Finance a focused command center: preview payroll assumptions,
                spot missing data, generate a new draft run, then jump directly into existing payslip and payroll detail screens.
              </p>
              <div className="mt-6 flex flex-wrap gap-3">
                <BaseButton href="/payroll_items/payroll_items-list" color="info" outline label="Payroll items" />
                <BaseButton href="/payslips/payslips-list" color="info" outline label="Payslips" />
                <BaseButton href="/employees/employees-list" color="whiteDark" outline label="Employees" />
              </div>
            </div>

            <div className="rounded-[28px] border border-white/10 bg-white/10 p-5 backdrop-blur">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <p className="text-sm font-medium text-teal-100">Current setup</p>
                  <p className="mt-2 text-2xl font-semibold text-white">{formatMonthLabel(form.periodMonth)}</p>
                </div>
                <span className="inline-flex rounded-full border border-white/15 px-3 py-1 text-xs font-medium text-slate-200">
                  {selectedOutlet ? `${selectedOutlet.code} • ${selectedOutlet.name}` : 'Choose outlet'}
                </span>
              </div>

              <div className="mt-6 grid gap-4 sm:grid-cols-2">
                <div className="rounded-2xl border border-white/10 bg-slate-950/30 p-4">
                  <div className="flex items-center gap-3 text-sm text-slate-200">
                    <BaseIcon path={mdiAccountGroup} className="text-teal-200" />
                    Employees in preview
                  </div>
                  <div className="mt-2 text-3xl font-semibold text-white">{preview?.readiness.employeeCount || 0}</div>
                </div>
                <div className="rounded-2xl border border-white/10 bg-slate-950/30 p-4">
                  <div className="flex items-center gap-3 text-sm text-slate-200">
                    <BaseIcon path={mdiFileDocumentOutline} className="text-teal-200" />
                    Recent payroll runs
                  </div>
                  <div className="mt-2 text-3xl font-semibold text-white">{workbench.recentRuns.length}</div>
                </div>
              </div>

              <p className="mt-5 text-sm leading-6 text-slate-200">
                {canGenerate
                  ? 'You have permission to preview and generate a new payroll draft.'
                  : 'You can preview payroll assumptions here, but generating a draft requires CREATE_PAYROLL_PERIODS permission.'}
              </p>
            </div>
          </div>
        </CardBox>

        {errorMessage ? (
          <div className="mt-6 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
            {errorMessage}
          </div>
        ) : null}

        {generatedRun ? (
          <div className="mt-6 rounded-3xl border border-emerald-200 bg-emerald-50 p-5 shadow-sm">
            <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <div className="inline-flex rounded-full border border-emerald-200 bg-white px-3 py-1 text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">
                  Payroll draft generated
                </div>
                <h3 className="mt-3 text-2xl font-semibold text-slate-950">{generatedRun.payrollPeriod.name}</h3>
                <p className="mt-2 text-sm leading-6 text-slate-600">
                  {generatedRun.generatedCount} payroll item(s) and {generatedRun.payslipCount} draft payslip(s) were created with a projected THP of{' '}
                  <span className="font-semibold text-slate-950">
                    {formatCurrency(generatedRun.totals.projectedTakeHomePay)}
                  </span>
                  .
                </p>
              </div>
              <div className="flex flex-wrap gap-3">
                <BaseButton
                  href={`/payroll_periods/payroll_periods-view/?id=${generatedRun.payrollPeriod.id}`}
                  color="info"
                  label="Open payroll detail"
                />
                <BaseButton href="/payslips/payslips-list" color="info" outline label="Review payslips" />
              </div>
            </div>
          </div>
        ) : null}

        <div className="mt-6 grid gap-6 xl:grid-cols-[0.95fr,1.05fr]">
          <CardBox className="border border-slate-200 shadow-sm">
            <div className="flex items-start justify-between gap-4">
              <div>
                <h3 className="text-xl font-semibold text-slate-950">Generate payroll draft</h3>
                <p className="mt-2 text-sm leading-6 text-slate-500">
                  Set the payroll month, outlet, and the few assumptions that are still manual in this first release.
                </p>
              </div>
              <button
                type="button"
                onClick={() => void fetchPreview(form)}
                className="inline-flex items-center gap-2 rounded-full border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition hover:border-slate-300 hover:text-slate-950"
              >
                <BaseIcon path={mdiRefresh} size={16} />
                Refresh preview
              </button>
            </div>

            <BaseDivider />

            {isLoadingWorkbench ? (
              <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-5 text-sm text-slate-500">
                Loading outlet and payroll context…
              </div>
            ) : !workbench.outlets.length ? (
              <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-5 text-sm text-slate-500">
                No outlet is available yet. Create outlets first so payroll can be generated per branch.
                <div className="mt-4">
                  <BaseButton href="/outlets/outlets-list" color="info" label="Open outlets" />
                </div>
              </div>
            ) : (
              <>
                <FormField label="Outlet cabang">
                  <select
                    value={form.outletId}
                    onChange={(event) => handleFieldChange('outletId', event.target.value)}
                  >
                    {workbench.outlets.map((outlet) => (
                      <option value={outlet.id} key={outlet.id}>
                        {outlet.code} — {outlet.name}
                      </option>
                    ))}
                  </select>
                </FormField>

                <FormField label="Payroll month" help="Default is previous month, so HR can close last month’s payroll quickly.">
                  <input
                    type="month"
                    value={form.periodMonth}
                    onChange={(event) => handleFieldChange('periodMonth', event.target.value)}
                  />
                </FormField>

                <div className="grid gap-4 md:grid-cols-2">
                  <FormField label="Standard workdays">
                    <input
                      type="number"
                      min={1}
                      value={form.standardWorkdays}
                      onChange={(event) =>
                        handleFieldChange('standardWorkdays', Number(event.target.value || 26))
                      }
                    />
                  </FormField>

                  <FormField label="Late penalty / minute" help="Default rule: Rp1.000 untuk setiap menit keterlambatan.">
                    <input
                      type="number"
                      min={0}
                      step={1000}
                      value={form.latePenaltyAmount}
                      onChange={(event) =>
                        handleFieldChange('latePenaltyAmount', Number(event.target.value || 0))
                      }
                    />
                  </FormField>
                </div>

                <div className="grid gap-4 md:grid-cols-2">
                  <FormField label="Max KPI allowance">
                    <input
                      type="number"
                      min={0}
                      step={10000}
                      value={form.maxKpiAllowance}
                      onChange={(event) =>
                        handleFieldChange('maxKpiAllowance', Number(event.target.value || 0))
                      }
                    />
                  </FormField>

                  <FormField label="Bonus & service-charge split">
                    <select
                      value={form.distributionMethod}
                      onChange={(event) =>
                        handleFieldChange(
                          'distributionMethod',
                          event.target.value as WorkbenchForm['distributionMethod'],
                        )
                      }
                    >
                      <option value="weighted_by_position">Weighted by job position</option>
                      <option value="equal">Equal split per employee</option>
                    </select>
                  </FormField>
                </div>

                {selectedOutlet ? (
                  <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-600">
                    <div className="flex items-center gap-2 font-medium text-slate-950">
                      <BaseIcon path={mdiStoreMarker} size={16} className="text-teal-600" />
                      {selectedOutlet.name}
                    </div>
                    <p className="mt-2 leading-6">
                      {selectedOutlet.address || 'Address is not filled yet.'} · GPS radius{' '}
                      <span className="font-semibold text-slate-950">{selectedOutlet.gps_radius_m || 0}m</span>
                    </p>
                  </div>
                ) : null}

                {previewDirty ? (
                  <div className="mt-4 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700">
                    Assumptions changed. Refresh the preview before sharing the numbers with HR or Finance.
                  </div>
                ) : null}

                <div className="mt-6 flex flex-wrap gap-3">
                  <BaseButton
                    onClick={() => void fetchPreview(form)}
                    color="info"
                    label={isLoadingPreview ? 'Refreshing preview…' : 'Preview payroll draft'}
                    disabled={isLoadingPreview || !form.outletId}
                  />
                  <BaseButton
                    onClick={handleGenerate}
                    color="info"
                    outline
                    label={isGenerating ? 'Generating draft…' : 'Generate payroll draft'}
                    disabled={isGenerating || !canGenerate || !form.outletId}
                  />
                </div>
              </>
            )}
          </CardBox>

          <div className="space-y-6">
            <CardBox className="border border-slate-200 shadow-sm">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <h3 className="text-xl font-semibold text-slate-950">Payroll preview</h3>
                  <p className="mt-2 text-sm leading-6 text-slate-500">
                    A thin but real payroll projection using the current attendance, KPI, overtime, omzet, service-charge, and loan data.
                  </p>
                </div>
                <span className="inline-flex rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs font-medium text-slate-600">
                  {preview ? `${formatMonthLabel(preview.config.periodMonth)} • ${preview.outlet.name}` : 'Waiting for preview'}
                </span>
              </div>

              <BaseDivider />

              {isLoadingPreview && !preview ? (
                <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-5 text-sm text-slate-500">
                  Building payroll preview…
                </div>
              ) : preview ? (
                <>
                  {preview.readiness.blockers.length ? (
                    <div className="mb-5 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
                      {preview.readiness.blockers[0]}
                    </div>
                  ) : null}

                  {preview.readiness.warnings.length ? (
                    <div className="mb-5 space-y-3 rounded-3xl border border-amber-200 bg-amber-50 p-4">
                      <div className="flex items-center gap-2 text-sm font-semibold text-amber-800">
                        <BaseIcon path={mdiAlertCircleOutline} size={16} />
                        Review flags before approving the final payroll
                      </div>
                      <ul className="space-y-2 text-sm leading-6 text-amber-700">
                        {preview.readiness.warnings.map((warning) => (
                          <li key={warning}>• {warning}</li>
                        ))}
                      </ul>
                      {preview.readiness.latestExistingRun?.id ? (
                        <div className="text-sm">
                          <Link
                            href={`/payroll_periods/payroll_periods-view/?id=${preview.readiness.latestExistingRun.id}`}
                            className="font-semibold text-amber-900 underline underline-offset-4"
                          >
                            Open the latest existing payroll run
                          </Link>
                        </div>
                      ) : null}
                    </div>
                  ) : null}

                  <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                    <StatCard
                      icon={mdiAccountGroup}
                      label="Employees"
                      value={String(preview.readiness.employeeCount)}
                      hint={`${preview.readiness.missingAttendanceCount} missing attendance • ${preview.readiness.missingKpiCount} missing KPI`}
                    />
                    <StatCard
                      icon={mdiCurrencyUsd}
                      label="Projected THP"
                      value={formatCurrency(preview.totals.projectedTakeHomePay)}
                      hint={`Avg ${formatCurrency(preview.totals.averageTakeHomePay)} per employee`}
                    />
                    <StatCard
                      icon={mdiChartBoxOutline}
                      label="Outlet revenue"
                      value={formatCurrency(preview.totals.grossRevenue)}
                      hint={`${preview.totals.bonusTierLabel} • bonus pool ${formatCurrency(preview.totals.bonusPool)}`}
                    />
                    <StatCard
                      icon={mdiClockOutline}
                      label="Overtime + SC"
                      value={`${preview.totals.totalOvertimeHours.toFixed(1)}h`}
                      hint={`${formatCurrency(preview.totals.totalOvertime)} overtime • ${formatCurrency(preview.totals.totalServiceCharge)} service charge`}
                    />
                  </div>

                  <div className="mt-6 grid gap-4 lg:grid-cols-2">
                    <div className="rounded-3xl border border-slate-200 bg-slate-50 p-4">
                      <div className="text-sm font-semibold text-slate-950">Earnings mix</div>
                      <div className="mt-4 space-y-3 text-sm text-slate-600">
                        <div className="flex items-center justify-between">
                          <span>Base salary</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.totals.totalBaseSalary)}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span>Meal & transport</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.totals.totalMealTransport)}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span>Position allowance</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.totals.totalPositionAllowance)}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span>KPI allowance</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.totals.totalKpiAllowance)}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span>Revenue bonus</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.totals.totalRevenueBonus)}</span>
                        </div>
                      </div>
                    </div>

                    <div className="rounded-3xl border border-slate-200 bg-slate-50 p-4">
                      <div className="text-sm font-semibold text-slate-950">Deductions & distribution</div>
                      <div className="mt-4 space-y-3 text-sm text-slate-600">
                        <div className="flex items-center justify-between">
                          <span>Total deductions</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.totals.totalDeductions)}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span>Service charge pool</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.totals.serviceChargePool)}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span>Distribution mode</span>
                          <span className="font-semibold text-slate-950">
                            {preview.config.distributionMethod === 'equal' ? 'Equal split' : 'Weighted by position'}
                          </span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span>Late penalty / minute</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.config.latePenaltyAmount)} / min</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span>KPI allowance cap</span>
                          <span className="font-semibold text-slate-950">{formatCurrency(preview.config.maxKpiAllowance)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </>
              ) : (
                <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-5 text-sm text-slate-500">
                  Choose an outlet to load the payroll preview.
                </div>
              )}
            </CardBox>

            <CardBox className="border border-slate-200 shadow-sm">
              <div className="flex items-center justify-between gap-4">
                <div>
                  <h3 className="text-xl font-semibold text-slate-950">Employee payout snapshot</h3>
                  <p className="mt-2 text-sm leading-6 text-slate-500">
                    A fast read of the top employees in the current preview, before you open the full payroll detail screens.
                  </p>
                </div>
                <BaseButton href="/employees/employees-list" color="info" outline label="Employee master data" />
              </div>

              <BaseDivider />

              {!topEmployees.length ? (
                <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-5 text-sm text-slate-500">
                  No employees are available for this preview yet.
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-slate-200 text-left text-sm">
                    <thead>
                      <tr className="text-slate-500">
                        <th className="pb-3 pr-4 font-medium">Employee</th>
                        <th className="pb-3 pr-4 font-medium">Workdays</th>
                        <th className="pb-3 pr-4 font-medium">KPI</th>
                        <th className="pb-3 pr-4 font-medium">Overtime</th>
                        <th className="pb-3 text-right font-medium">Projected THP</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {topEmployees.map((employee) => (
                        <tr key={employee.id}>
                          <td className="py-4 pr-4">
                            <div className="font-semibold text-slate-950">{employee.full_name}</div>
                            <div className="text-xs text-slate-500">
                              {employee.employee_code || 'No code'}
                              {employee.job_position?.name ? ` • ${employee.job_position.name}` : ''}
                            </div>
                          </td>
                          <td className="py-4 pr-4 text-slate-600">{employee.workdays}</td>
                          <td className="py-4 pr-4 text-slate-600">
                            {employee.has_kpi_score ? employee.kpi_score.toFixed(1) : 'Missing'}
                          </td>
                          <td className="py-4 pr-4 text-slate-600">{employee.overtime_hours_total.toFixed(1)}h</td>
                          <td className="py-4 text-right font-semibold text-slate-950">
                            {formatCurrency(employee.take_home_pay)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </CardBox>
          </div>
        </div>

        <CardBox className="mt-6 border border-slate-200 shadow-sm">
          <div className="flex items-center justify-between gap-4">
            <div>
              <h3 className="text-xl font-semibold text-slate-950">Recent payroll runs</h3>
              <p className="mt-2 text-sm leading-6 text-slate-500">
                Reuse the existing list and detail pages after generation. This table gives HR a faster overview of recent periods.
              </p>
            </div>
            <BaseButton href="/payroll_periods/payroll_periods-list" color="info" outline label="Open full list" />
          </div>

          <BaseDivider />

          {!workbench.recentRuns.length ? (
            <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-5 text-sm text-slate-500">
              No payroll periods have been generated yet.
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-slate-200 text-left text-sm">
                <thead>
                  <tr className="text-slate-500">
                    <th className="pb-3 pr-4 font-medium">Payroll run</th>
                    <th className="pb-3 pr-4 font-medium">Period</th>
                    <th className="pb-3 pr-4 font-medium">Outlet</th>
                    <th className="pb-3 pr-4 font-medium">Employees</th>
                    <th className="pb-3 pr-4 font-medium">THP total</th>
                    <th className="pb-3 pr-4 font-medium">Status</th>
                    <th className="pb-3 text-right font-medium">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {workbench.recentRuns.map((run) => (
                    <tr key={run.id}>
                      <td className="py-4 pr-4">
                        <div className="font-semibold text-slate-950">{run.name}</div>
                        <div className="text-xs text-slate-500">
                          Generated {formatShortDate(run.generated_at)}
                          {run.generated_by_user ? ` • ${run.generated_by_user}` : ''}
                        </div>
                      </td>
                      <td className="py-4 pr-4 text-slate-600">
                        {formatShortDate(run.period_start)} — {formatShortDate(run.period_end)}
                      </td>
                      <td className="py-4 pr-4 text-slate-600">{run.outlet?.name || '—'}</td>
                      <td className="py-4 pr-4 text-slate-600">{run.employeeCount}</td>
                      <td className="py-4 pr-4 font-semibold text-slate-950">
                        {formatCurrency(run.totalTakeHomePay)}
                      </td>
                      <td className="py-4 pr-4">
                        <span className={`inline-flex rounded-full px-3 py-1 text-xs font-semibold ${getStatusBadgeClasses(run.status)}`}>
                          {run.status.replaceAll('_', ' ')}
                        </span>
                      </td>
                      <td className="py-4 text-right">
                        <Link
                          href={`/payroll_periods/payroll_periods-view/?id=${run.id}`}
                          className="font-semibold text-teal-700 transition hover:text-teal-900"
                        >
                          Open detail
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardBox>
      </SectionMain>
    </>
  );
};

PayrollWorkbenchPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission="READ_PAYROLL_PERIODS">{page}</LayoutAuthenticated>;
};

export default PayrollWorkbenchPage;
