import Link from 'next/link';
import type { Metadata } from 'next';
import { api } from '@/lib/api';
import { Breadcrumbs } from '@/components/Breadcrumbs';
import { Monogram, Stars, VerificationBadge } from '@/components/Badges';
import { SaveButton } from '@/components/AccountWidgets';
import { InfoIcon, LayersIcon } from '@/components/Icons';
import type { LawyerCard } from '@/lib/types';

export const metadata: Metadata = { title: 'Compare lawyers', robots: { index: false, follow: true } };

type C = LawyerCard & {
  acceptsLeads: boolean;
  activeLicenses: number;
  verifiedLicenses: number;
  firstAdmitted: number | null;
  education: number;
  awards: number;
  trackRecords: number;
  rankings: { rank: number; city: string; area: string; score: number }[] | null;
};

export default async function Compare({ searchParams }: { searchParams: Promise<{ lawyers?: string }> }) {
  const { lawyers = '' } = await searchParams;
  const d = lawyers ? await api<{ lawyers: C[]; note: string }>(`/compare?lawyers=${encodeURIComponent(lawyers)}`, { revalidate: 300 }) : { lawyers: [], note: '' };
  const L = d.lawyers;
  const rows: [string, (l: C) => React.ReactNode][] = [
    ['Verification', (l) => <VerificationBadge status={l.verificationStatus} compact />],
    ['Active licences', (l) => `${l.activeLicenses} (${l.verifiedLicenses} verified)`],
    ['Admitted since', (l) => l.firstAdmitted ?? '—'],
    ['Years in practice', (l) => l.yearsExperience ?? '—'],
    ['Firm', (l) => l.firm?.name ?? 'Independent'],
    ['City', (l) => l.city?.name ?? '—'],
    ['Practice areas', (l) => l.practiceAreas.map((a) => a.name).join(', ') || '—'],
    ['Languages', (l) => l.languages.join(', ') || '—'],
    [
      'Best rankings',
      (l) =>
        l.rankings?.length ? (
          <ul className="space-y-0.5">
            {l.rankings.slice(0, 3).map((r) => (
              <li key={`${r.city}-${r.area}`}>
                <strong>#{r.rank}</strong> {r.area}, {r.city}
              </li>
            ))}
          </ul>
        ) : (
          'Not ranked'
        ),
    ],
    ['Reviews', (l) => (l.reviewCount && l.averageRating != null ? <span className="inline-flex items-center gap-1"><Stars value={l.averageRating} /> ({l.reviewCount})</span> : 'None yet')],
    ['Verified awards', (l) => l.awards],
    ['Public court matters', (l) => l.trackRecords],
    ['Education on file', (l) => l.education],
    ['Accepting enquiries', (l) => (l.acceptsLeads ? 'Yes' : 'No')],
  ];
  return (
    <div className="mx-auto max-w-6xl px-4 py-8 sm:px-6 sm:py-10">
      <Breadcrumbs items={[{ label: 'Home', href: '/' }, { label: 'Compare', href: '/compare/' }]} />
      <h1 className="mt-6 flex items-center gap-3 font-serif text-3xl font-semibold tracking-tight sm:text-4xl">
        <LayersIcon className="h-7 w-7 text-ledger" /> Compare lawyers
      </h1>
      {L.length < 2 ? (
        <p className="card mt-6 p-6 text-sm text-ink-2">
          Pick at least two lawyers with the <strong>Compare</strong> button on their profiles — up to four.{' '}
          <Link href="/search/" className="link">
            Search lawyers
          </Link>
        </p>
      ) : (
        <>
          <div className="mt-6 overflow-x-auto rounded-xl border border-rule bg-surface">
            <table className="w-full min-w-[40rem] text-sm">
              <thead>
                <tr className="border-b border-rule">
                  <th className="w-44 p-4 text-left text-xs font-semibold uppercase tracking-wide text-muted" />
                  {L.map((l) => (
                    <th key={l.id} className="p-4 text-left align-top">
                      <div className="flex items-center gap-3">
                        <Monogram name={l.name} size={40} />
                        <div>
                          <Link href={`/lawyers/${l.slug}/`} className="font-serif text-base font-semibold hover:text-ledger hover:underline">
                            {l.name}
                          </Link>
                          {l.title && <p className="text-xs font-normal text-muted">{l.title}</p>}
                        </div>
                      </div>
                      <div className="mt-3 flex flex-wrap gap-2 font-normal">
                        <Link href={`/lawyers/${l.slug}/#contact`} className="btn btn-primary btn-sm">
                          Contact
                        </Link>
                        <SaveButton kind="lawyers" slug={l.slug} name={l.name} />
                      </div>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {rows.map(([label, cell]) => (
                  <tr key={label} className="border-b border-rule last:border-b-0">
                    <th scope="row" className="p-4 text-left align-top text-xs font-semibold uppercase tracking-wide text-muted">
                      {label}
                    </th>
                    {L.map((l) => (
                      <td key={l.id} className="p-4 align-top text-ink-2">
                        {cell(l)}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <p className="mt-4 flex items-start gap-2 text-xs text-muted">
            <InfoIcon className="mt-0.5 h-3.5 w-3.5" /> {d.note} Rankings compare lawyers only within the same city and practice area.
          </p>
        </>
      )}
    </div>
  );
}
