import { useMemo, useState } from 'react';
import { ClipboardCheck } from 'lucide-react';

import { usePolicyAcknowledgmentReport } from '@/business/policies/hooks';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ModuleHeader } from '@/components/ui/module-header';
import { PageSkeleton } from '@/components/ui/page-skeleton';
import { StatePanel } from '@/components/ui/state-panel';
import { getErrorMessage } from '@/shared/errors/errorMessages';
import type { PolicyAcknowledgmentReportStaffDto } from '@/shared/types/policyDocuments';

function formatDate(value: string | null): string {
  if (!value) return 'Missing';
  return new Intl.DateTimeFormat(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  }).format(new Date(value));
}

function roleLabel(value: string | null): string {
  return value ? value.replace(/_/g, ' ') : 'staff';
}

export default function AcknowledgmentsPage() {
  const reportQuery = usePolicyAcknowledgmentReport();
  const [missingOnly, setMissingOnly] = useState(false);

  const staffRows = useMemo<readonly PolicyAcknowledgmentReportStaffDto[]>(() => {
    const rows = reportQuery.data?.staff ?? [];
    return missingOnly ? rows.filter((row) => row.missingCount > 0) : rows;
  }, [missingOnly, reportQuery.data]);

  if (reportQuery.isLoading) {
    return <PageSkeleton />;
  }

  if (reportQuery.error) {
    return (
      <div className="p-4 md:p-6">
        <StatePanel tone="red" role="alert">
          {getErrorMessage(reportQuery.error, 'Could not load acknowledgments report')}
        </StatePanel>
      </div>
    );
  }

  const report = reportQuery.data;
  if (!report) {
    return null;
  }

  return (
    <div className="space-y-6 p-4 md:p-6">
      <ModuleHeader
        title="Acknowledgments"
        description="Policy and safety acknowledgment status for the current scope."
        icon={ClipboardCheck}
        iconClassName="bg-gradient-to-br from-emerald-500 to-emerald-700"
      />

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="p-4">
            <p className="text-xs text-slate-400">Completion</p>
            <p className="mt-1 text-2xl font-semibold text-white">{report.summary.completionRate}%</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs text-slate-400">Staff</p>
            <p className="mt-1 text-2xl font-semibold text-white">{report.summary.totalStaff}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs text-slate-400">Documents</p>
            <p className="mt-1 text-2xl font-semibold text-white">{report.summary.totalDocuments}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs text-slate-400">Missing</p>
            <p className="mt-1 text-2xl font-semibold text-white">{report.summary.missingCount}</p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Documents</CardTitle>
        </CardHeader>
        <CardContent className="overflow-x-auto">
          <table className="min-w-full text-sm">
            <thead className="text-left text-xs uppercase text-slate-500">
              <tr>
                <th className="py-2 pr-4">Document</th>
                <th className="py-2 pr-4">Category</th>
                <th className="py-2 pr-4">Version</th>
                <th className="py-2 pr-4">Acknowledged</th>
                <th className="py-2 pr-4">Missing</th>
                <th className="py-2 pr-4">Rate</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700/50 text-slate-200">
              {report.documents.map((document) => (
                <tr key={document.id}>
                  <td className="py-3 pr-4 font-medium">{document.title}</td>
                  <td className="py-3 pr-4">{document.category.replace('_', ' ')}</td>
                  <td className="py-3 pr-4">{document.version}</td>
                  <td className="py-3 pr-4">{document.acknowledgedCount}/{document.totalStaff}</td>
                  <td className="py-3 pr-4">{document.missingCount}</td>
                  <td className="py-3 pr-4">{document.completionRate}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <div className="flex flex-wrap items-center justify-between gap-3">
            <CardTitle className="text-base">Staff Detail</CardTitle>
            <label className="flex items-center gap-2 text-sm text-slate-300">
              <input
                type="checkbox"
                checked={missingOnly}
                onChange={(event) => setMissingOnly(event.target.checked)}
              />
              Missing only
            </label>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {staffRows.length === 0 ? (
            <p className="text-sm text-slate-400">No staff rows match the current filter.</p>
          ) : (
            staffRows.map((staff) => (
              <div key={staff.userId} className="rounded-lg border border-slate-700/50 p-4">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <p className="font-medium text-white">{staff.name}</p>
                    <p className="text-xs text-slate-400">{staff.email} · {roleLabel(staff.role)}</p>
                  </div>
                  <Badge variant={staff.missingCount > 0 ? 'secondary' : 'default'}>
                    {staff.acknowledgedCount}/{staff.documents.length} acknowledged
                  </Badge>
                </div>
                <div className="mt-3 grid gap-2 md:grid-cols-2">
                  {staff.documents
                    .filter((document) => !missingOnly || document.missing)
                    .map((document) => (
                      <div
                        key={`${staff.userId}-${document.policyDocumentId}`}
                        className="flex items-center justify-between gap-3 rounded-md bg-slate-900/60 px-3 py-2 text-sm"
                      >
                        <span className="min-w-0 truncate text-slate-200">{document.title}</span>
                        <span className={document.missing ? 'text-amber-300' : 'text-emerald-300'}>
                          {formatDate(document.acknowledgedAt)}
                        </span>
                      </div>
                    ))}
                </div>
              </div>
            ))
          )}
        </CardContent>
      </Card>
    </div>
  );
}
