
import * as ActionIcons from '@/components/Icons';
import Link from 'next/link';
import { api, isAdmin, me } from '@/lib/api';
import { n } from '@/lib/format';
import { Card, Flash, Forbidden, Kpi, PageHeader, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { AlertIcon, ClockIcon, InboxIcon, RefreshIcon, SaveIcon, SendIcon, ShieldCheckIcon } from '@/components/Icons';
import { runLeadSweep, saveLeadRules } from '../../actions';

type Rules = {
  maxRecipients: number;
  maxTotalRecipients: number;
  responseSlaHours: number;
  reminderAfterHours: number;
  rerouteOnDecline: boolean;
  rerouteOnExpiry: boolean;
  closeOthersOnAccept: boolean;
  leadExpiryDays: number;
  retentionDays: number;
  notifyClientOnAccept: boolean;
};
type D = {
  rules: Rules;
  defaults: Rules;
  snapshot: { open: number; overdue_for_reminder: number; sla_expired_30d: number; failed_deliveries: number; pending_deliveries: number; leads_expired_30d: number; anonymised: number };
};

function Num({ name, label, help, min, max, value, unit }: { name: keyof Rules; label: string; help: string; min: number; max: number; value: number; unit: string }) {
  return (
    <label className="block">
      <span className="field-label"><ActionIcons.GaugeIcon />{label}</span>
      <span className="flex items-center gap-2">
        <input name={name} type="number" required min={min} max={max} defaultValue={value} className="field w-28" />
        <span className="text-xs text-muted">{unit}</span>
      </span>
      <span className="mt-1 block text-xs text-muted">{help}</span>
    </label>
  );
}

function Toggle({ name, label, help, checked }: { name: keyof Rules; label: string; help: string; checked: boolean }) {
  return (
    <label className="flex items-start gap-2.5">
      <input type="checkbox" name={name} defaultChecked={checked} className="mt-1" />
      <span>
        <span className="font-medium">{label}</span>
        <span className="block text-xs text-muted">{help}</span>
      </span>
    </label>
  );
}

export default async function LeadRules({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const viewer = await me();
  if (!isAdmin(viewer.role)) return <Forbidden what="lead rules" />;
  const d = await api<D>('/admin/lead-rules');
  const r = d.rules;
  const s = d.snapshot;
  return (
    <>
      <PageHeader
        title="Lead rules"
        icon={<SendIcon className="h-5 w-5" />}
        description="How enquiries are routed, how long lawyers have to answer, what happens when they don’t, and how long client details are kept. The lifecycle check runs every 10 minutes."
        actions={
          <form action={runLeadSweep}>
            <SubmitButton className="btn btn-quiet btn-sm" pendingLabel="Running…" confirm="Run reminders, expiry and retention now?">
              <RefreshIcon className="h-4 w-4" /> Run now
            </SubmitButton>
          </form>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-5">
        <Kpi label="Waiting on lawyers" icon={<InboxIcon className="h-4 w-4" />} value={n(s.open)} hint={`${n(s.overdue_for_reminder)} past reminder time`} tone={s.overdue_for_reminder ? 'warn' : 'default'} />
        <Kpi label="Expired unanswered" icon={<ClockIcon className="h-4 w-4" />} value={n(s.sla_expired_30d)} hint="routings, last 30 days" />
        <Kpi label="Enquiries expired" icon={<ClockIcon className="h-4 w-4" />} value={n(s.leads_expired_30d)} hint="no lawyer accepted, 30 days" />
        <Kpi label="Failed deliveries" icon={<AlertIcon className="h-4 w-4" />} value={n(s.failed_deliveries)} tone={s.failed_deliveries ? 'warn' : 'default'} hint={`${n(s.pending_deliveries)} still retrying`} href="/leads/deliveries" />
        <Kpi label="Anonymised" icon={<ShieldCheckIcon className="h-4 w-4" />} value={n(s.anonymised)} hint="past retention period" tone="muted" />
      </div>

      <form action={saveLeadRules}>
        <div className="grid gap-6 xl:grid-cols-2">
          <Card title="Routing" icon={<SendIcon className="h-4 w-4" />}>
            <div className="grid gap-5 p-5 text-sm sm:grid-cols-2">
              <Num name="maxRecipients" label="First-round recipients" unit="lawyers" min={1} max={10} value={r.maxRecipients} help="How many matching lawyers get a new enquiry at once." />
              <Num name="maxTotalRecipients" label="Total recipients (consent limit)" unit="lawyers" min={1} max={20} value={r.maxTotalRecipients} help="Shown to clients in the consent text; reroutes never exceed what each client agreed to." />
              <div className="space-y-3 sm:col-span-2">
                <Toggle name="rerouteOnDecline" label="Offer to the next lawyer when one declines" help="Matched enquiries only — a direct enquiry never goes to anyone the client didn’t choose." checked={r.rerouteOnDecline} />
                <Toggle name="rerouteOnExpiry" label="Offer to the next lawyer when one doesn’t answer in time" help="Same consent limits apply." checked={r.rerouteOnExpiry} />
                <Toggle name="closeOthersOnAccept" label="Close the enquiry for other lawyers when one accepts" help="Off: the client may hear from several lawyers and choose." checked={r.closeOthersOnAccept} />
              </div>
            </div>
          </Card>

          <Card title="Response deadline (SLA)" icon={<ClockIcon className="h-4 w-4" />}>
            <div className="grid gap-5 p-5 text-sm sm:grid-cols-2">
              <Num name="responseSlaHours" label="Time to accept or decline" unit="hours" min={1} max={336} value={r.responseSlaHours} help="After this an unanswered routing expires (it counts against client experience)." />
              <Num name="reminderAfterHours" label="Reminder after" unit="hours (0 = off)" min={0} max={335} value={r.reminderAfterHours} help="One reminder (in-app + email). Must be shorter than the deadline." />
              <Num name="leadExpiryDays" label="Close unanswered enquiries after" unit="days" min={1} max={90} value={r.leadExpiryDays} help="The client is told by email and pointed to the directory." />
              <div className="self-end">
                <Toggle name="notifyClientOnAccept" label="Email the client when a lawyer accepts" help="Includes the lawyer’s name and profile link." checked={r.notifyClientOnAccept} />
              </div>
            </div>
          </Card>

          <Card title="Privacy & retention" icon={<ShieldCheckIcon className="h-4 w-4" />} className="xl:col-span-2">
            <div className="grid gap-5 p-5 text-sm sm:grid-cols-[16rem_1fr]">
              <Num name="retentionDays" label="Keep client details for" unit="days" min={30} max={3650} value={r.retentionDays} help="Then name, email, phone, case description and IP data are anonymised. Statistics stay." />
              <p className="rounded-lg bg-paper p-3 text-xs leading-relaxed text-ink-2">
                Enquiries often contain sensitive personal circumstances. Pick the shortest period your legal and business needs allow, and match it to your privacy policy. Opening an enquiry in the admin console is recorded in the audit log, and only owners and admins can see client details.
              </p>
            </div>
          </Card>
        </div>
        <div className="mt-6 flex items-center gap-3">
          <SubmitButton pendingLabel="Saving…">
            <SaveIcon className="h-4 w-4" /> Save rules
          </SubmitButton>
          <span className="text-xs text-muted">
            Defaults: {d.defaults.maxRecipients} first, {d.defaults.maxTotalRecipients} total, {d.defaults.responseSlaHours} h deadline, reminder at {d.defaults.reminderAfterHours} h, {d.defaults.leadExpiryDays} days, keep {d.defaults.retentionDays} days. <Link href="/audit?entityType=settings" className="link">Change history</Link>
          </span>
        </div>
      </form>
    </>
  );
}
