
import * as ActionIcons from '@/components/Icons';
import { api, canEdit, me } from '@/lib/api';
import { date, n } from '@/lib/format';
import { Card, Empty, Flash, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { DatabaseIcon, ExternalLinkIcon, PlusIcon } from '@/components/Icons';
import { createSource, toggleSource } from '../../actions';

type S = { id: number; name: string; source_type: string; url: string | null; authority_score: string; is_active: boolean; records: number; rejected: number; reviews: number; last_fetched: string | null; notes: string | null };

const TYPES = ['bar_registry', 'court_records', 'review_platform', 'publication', 'firm_website', 'self_reported', 'editorial'];

export default async function Sources({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const [rows, user] = await Promise.all([api<S[]>('/admin/sources'), me()]);
  const editable = canEdit(user.role);
  return (
    <>
      <PageHeader
        title="Sources and evidence"
        icon={<DatabaseIcon className="h-5 w-5" />}
        description="Every fact links back to a raw record from one of these sources. Authority (0–100) weights reviews; deactivating a source removes its reviews from the next ranking run."
      />
      <Flash ok={sp.ok} err={sp.err} />
      <Card>
        {rows.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Source</th>
                  <th>Type</th>
                  <th className="w-36">Authority</th>
                  <th className="text-right">Raw records</th>
                  <th className="text-right">Rejected</th>
                  <th className="text-right">Reviews</th>
                  <th>Last fetched</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((s) => {
                  const authority = Number(s.authority_score);
                  return (
                    <tr key={s.id} className={s.is_active ? '' : 'opacity-70'}>
                      <td>
                        <p className="flex items-center gap-1.5 font-semibold">
                          {s.name}
                          {s.url && (
                            <a href={s.url} target="_blank" rel="noopener noreferrer" aria-label={`Open ${s.name}`} className="text-muted hover:text-ledger">
                              <ExternalLinkIcon className="h-3 w-3" />
                            </a>
                          )}
                        </p>
                        {s.notes && <p className="text-xs text-muted">{s.notes}</p>}
                      </td>
                      <td className="capitalize">{s.source_type.replace(/_/g, ' ')}</td>
                      <td>
                        <div className="flex items-center gap-2">
                          <span className="h-1.5 w-16 overflow-hidden rounded-full bg-sunken">
                            <span className="block h-full rounded-full bg-[var(--g-expertise)]" style={{ width: `${Math.min(100, authority)}%` }} />
                          </span>
                          <span className="num">{authority.toFixed(0)}</span>
                        </div>
                      </td>
                      <td className="num text-right">{n(s.records)}</td>
                      <td className={`num text-right ${s.rejected ? 'font-semibold text-danger' : 'text-muted'}`}>{n(s.rejected)}</td>
                      <td className="num text-right">{n(s.reviews)}</td>
                      <td className="whitespace-nowrap">{date(s.last_fetched)}</td>
                      <td>
                        <div className="flex items-center gap-2">
                          <Pill value={s.is_active ? 'active' : 'inactive'} tone={s.is_active ? 'good' : 'muted'} />
                          {editable && (
                            <form action={toggleSource}>
                              <input type="hidden" name="id" value={s.id} />
                              <input type="hidden" name="isActive" value={String(!s.is_active)} />
                              <SubmitButton
                                className={`btn btn-xs ${s.is_active ? 'btn-danger-quiet' : 'btn-quiet'}`}
                                confirm={s.is_active ? `Deactivate ${s.name}? Its reviews drop out of the next ranking run.` : undefined}
                              >
                                <ActionIcons.RefreshIcon />{s.is_active ? 'Deactivate' : 'Activate'}
                              </SubmitButton>
                            </form>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<DatabaseIcon className="h-6 w-6" />}>No sources yet. Add the registries and review platforms you import from.</Empty>
        )}
      </Card>
      {editable && (
        <Card title="Add a source" icon={<PlusIcon className="h-4 w-4" />} className="mt-6 max-w-3xl">
          <form action={createSource} className="grid gap-4 p-5 sm:grid-cols-2">
            <label className="block">
              <span className="field-label">
                Name <span className="text-danger">*</span>
              </span>
              <input name="name" required maxLength={200} className="field" />
            </label>
            <label className="block">
              <span className="field-label"><ActionIcons.LayersIcon />Type</span>
              <select name="sourceType" className="field">
                {TYPES.map((t) => (
                  <option key={t} value={t}>
                    {t.replace(/_/g, ' ')}
                  </option>
                ))}
              </select>
            </label>
            <label className="block">
              <span className="field-label"><ActionIcons.GlobeIcon />URL</span>
              <input name="url" type="text" inputMode="url" placeholder="https://" className="field" />
            </label>
            <label className="block">
              <span className="field-label"><ActionIcons.ShieldCheckIcon />Authority (0–100)</span>
              <input name="authorityScore" type="number" min={0} max={100} defaultValue={50} className="field" />
            </label>
            <div className="border-t border-rule pt-4 sm:col-span-2">
              <SubmitButton pendingLabel="Adding…">
                <PlusIcon className="h-4 w-4" /> Add source
              </SubmitButton>
            </div>
          </form>
        </Card>
      )}
    </>
  );
}
