import { api } from '@/lib/api';
import { date, PUBLIC_SITE } from '@/lib/format';
import { Card, Empty, Flash, PageHeader, Pill, Tabs, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { CheckIcon, ClockIcon, ExternalLinkIcon, FlagIcon, MailIcon, XIcon } from '@/components/Icons';
import { resolveCorrection } from '../../actions';

type C = { id: number; entity_type: string; entity_id: number; entity_name: string | null; entity_slug: string | null; field: string | null; message: string; reporter_email: string | null; is_dispute: boolean; status: string; resolution: string | null; created_at: string };

const TABS = [
  { value: '', label: 'Open' },
  { value: 'resolved', label: 'Resolved' },
  { value: 'rejected', label: 'Rejected' },
];

export default async function Corrections({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const status = TABS.some((t) => t.value === sp.status) ? (sp.status ?? '') : '';
  const rows = await api<C[]>(`/admin/corrections${status ? `?status=${status}` : ''}`);
  return (
    <>
      <PageHeader
        title="Complaints and corrections"
        icon={<FlagIcon className="h-5 w-5" />}
        description="Disputes from professionals are listed first. Resolving a report records who resolved it and why."
        actions={<Tabs current={status} items={TABS.map((t) => ({ ...t, href: t.value ? `?status=${t.value}` : '/corrections' }))} />}
      />
      <Flash ok={sp.ok} err={sp.err} />
      <Card>
        {rows.length ? (
          <ul className="divide-y divide-rule">
            {rows.map((c) => (
              <li key={c.id} className="grid gap-4 p-4 lg:grid-cols-[1fr_26rem] lg:items-start">
                <div className="min-w-0 text-sm">
                  <p className="flex flex-wrap items-center gap-2">
                    <Pill value={c.status} />
                    {c.is_dispute && <Pill value="dispute" tone="bad" />}
                    <span className="rounded bg-sunken px-1.5 py-0.5 text-[11px] font-semibold uppercase text-muted">{c.entity_type}</span>
                    {c.entity_slug ? (
                      <a className="inline-flex items-center gap-1 font-semibold hover:text-ledger hover:underline" target="_blank" rel="noopener" href={`${PUBLIC_SITE}/${c.entity_type === 'firm' ? 'firms' : 'lawyers'}/${c.entity_slug}/`}>
                        {c.entity_name} <ExternalLinkIcon className="h-3 w-3 text-muted" />
                      </a>
                    ) : (
                      <span className="font-semibold">{c.entity_name ?? `#${c.entity_id}`}</span>
                    )}
                    {c.field && <span className="text-muted">· {c.field.replace(/_/g, ' ')}</span>}
                  </p>
                  <p className="mt-2 leading-relaxed text-ink">{c.message}</p>
                  <p className="mt-2 flex flex-wrap gap-x-3 text-xs text-muted">
                    <span className="inline-flex items-center gap-1">
                      <ClockIcon className="h-3.5 w-3.5" /> {date(c.created_at)}
                    </span>
                    <span className="inline-flex items-center gap-1">
                      <MailIcon className="h-3.5 w-3.5" />
                      {c.reporter_email ? (
                        <a href={`mailto:${c.reporter_email}`} className="hover:text-ink hover:underline">
                          {c.reporter_email}
                        </a>
                      ) : (
                        'no email given'
                      )}
                    </span>
                  </p>
                  {c.resolution && <p className="mt-2 rounded-md bg-paper px-3 py-2 text-xs text-ink-2">Resolution: {c.resolution}</p>}
                </div>
                {(c.status === 'open' || c.status === 'in_review') && (
                  <form className="flex flex-col gap-2">
                    <input type="hidden" name="id" value={c.id} />
                    <input name="resolution" maxLength={1000} placeholder="What was changed, or why not" aria-label="Resolution" className="field text-xs" />
                    <div className="flex flex-wrap gap-2">
                      <SubmitButton formAction={resolveCorrection.bind(null, 'resolved')} className="btn btn-primary btn-sm">
                        <CheckIcon className="h-4 w-4" /> Resolve
                      </SubmitButton>
                      {c.status !== 'in_review' && (
                        <SubmitButton formAction={resolveCorrection.bind(null, 'in_review')} className="btn btn-quiet btn-sm">
                          <ClockIcon className="h-4 w-4" /> In review
                        </SubmitButton>
                      )}
                      <SubmitButton formAction={resolveCorrection.bind(null, 'rejected')} confirm="Reject this report?" className="btn btn-danger-quiet btn-sm">
                        <XIcon className="h-4 w-4" /> Reject
                      </SubmitButton>
                    </div>
                  </form>
                )}
              </li>
            ))}
          </ul>
        ) : (
          <Empty icon={<FlagIcon className="h-6 w-6" />}>No reports here.</Empty>
        )}
      </Card>
    </>
  );
}
