
import * as ActionIcons from '@/components/Icons';
import { cookies } from 'next/headers';
import { api, canEdit, me } from '@/lib/api';
import { Card, Flash, Forbidden, PageHeader, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { CheckCircleIcon, FileTextIcon, InfoIcon, UploadIcon } from '@/components/Icons';
import { runImport } from '../../actions';

const SAMPLE = `firstName,lastName,city,country,practiceAreas,licenseNumber,jurisdiction,issuingBody,admittedYear,firm,email,yearsExperience
Priya,Raman,New York,us,divorce;family,NY-123456,New York,New York State Unified Court System,2012,Raman Family Law,priya@example.com,13`;

const COLUMNS = ['firstName', 'lastName (or fullName)', 'city', 'country', 'practiceAreas (;-separated)', 'licenseNumber', 'jurisdiction', 'issuingBody', 'admittedYear', 'licenseStatus', 'firm', 'email', 'phone', 'website', 'yearsExperience', 'languages', 'bio'];

export default async function Imports({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const user = await me();
  if (!canEdit(user.role)) return <Forbidden what="data imports" />;
  const ref = await api<{ sources: { id: number; name: string; sourceType: string }[] }>('/admin/reference');
  const result = (await cookies()).get('lr_import_result')?.value;
  let pretty: Record<string, unknown> | null = null;
  try {
    pretty = result?.startsWith('{') ? JSON.parse(result) : null;
  } catch {
    pretty = null;
  }
  return (
    <>
      <PageHeader
        title="Data import"
        icon={<UploadIcon className="h-5 w-5" />}
        description="Raw records are stored untouched, normalised, matched against existing lawyers (licence number first, then name + city) and either merged into a profile or created as a new one. Probable duplicates go to the duplicates queue; non-registry licences go to verification."
      />
      <Flash ok={sp.ok} err={sp.err} />
      {result && (
        <Card title="Last import" icon={<CheckCircleIcon className="h-4 w-4" />} className="mb-6">
          {pretty ? (
            <dl className="grid grid-cols-2 gap-3 p-4 sm:grid-cols-4 lg:grid-cols-6">
              {Object.entries(pretty).map(([k, v]) => (
                <div key={k} className="rounded-lg bg-paper p-3">
                  <dt className="text-xs capitalize text-muted">{k.replace(/([A-Z])/g, ' $1').toLowerCase()}</dt>
                  <dd className="num font-serif text-xl font-semibold">{String(v)}</dd>
                </div>
              ))}
            </dl>
          ) : (
            <p className="p-4 text-sm">{result}</p>
          )}
        </Card>
      )}
      <div className="grid gap-6 xl:grid-cols-[1fr_20rem]">
        <Card>
          <form action={runImport} className="space-y-5 p-5">
            <label className="block">
              <span className="field-label">
                Source <span className="text-danger">*</span>
              </span>
              <select name="sourceId" required defaultValue="" className="field max-w-md">
                <option value="" disabled>
                  Choose where these records came from…
                </option>
                {ref.sources.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.name} ({s.sourceType.replace(/_/g, ' ')})
                  </option>
                ))}
              </select>
            </label>
            <label className="block">
              <span className="field-label"><ActionIcons.UploadIcon />Upload CSV or JSON</span>
              <input
                type="file"
                name="file"
                accept=".csv,.json,text/csv,application/json"
                className="block w-full cursor-pointer rounded-lg border border-dashed border-rule-strong bg-paper p-3 text-sm text-muted transition-colors file:mr-3 file:cursor-pointer file:rounded-md file:border-0 file:bg-ledger file:px-3 file:py-1.5 file:text-sm file:font-semibold file:text-ledger-ink hover:border-ledger"
              />
              <span className="mt-1 block text-xs text-muted">Up to 8 MB. A file takes priority over pasted records.</span>
            </label>
            <label className="block">
              <span className="field-label"><ActionIcons.FileTextIcon />…or paste records</span>
              <textarea name="payload" rows={8} spellCheck={false} className="field num font-mono text-xs" defaultValue={SAMPLE} />
            </label>
            <label className="flex items-center gap-2.5 text-sm">
              <input type="checkbox" name="publish" /> Publish new profiles immediately (otherwise they start as drafts)
            </label>
            <div className="border-t border-rule pt-4">
              <SubmitButton pendingLabel="Importing…">
                <UploadIcon className="h-4 w-4" /> Run import
              </SubmitButton>
            </div>
          </form>
        </Card>
        <Card title="Format" icon={<FileTextIcon className="h-4 w-4" />} className="self-start">
          <div className="space-y-3 p-4 text-xs text-ink-2">
            <p>CSV with a header row, or a JSON array of objects with these keys:</p>
            <ul className="flex flex-wrap gap-1">
              {COLUMNS.map((c) => (
                <li key={c} className="num rounded bg-sunken px-1.5 py-0.5">
                  {c}
                </li>
              ))}
            </ul>
            <p className="flex items-start gap-1.5 text-muted">
              <InfoIcon className="mt-0.5 h-3.5 w-3.5" /> Batches over 200 records run on the import worker.
            </p>
          </div>
        </Card>
      </div>
    </>
  );
}
