
import * as ActionIcons from '@/components/Icons';
import { api, me } from '@/lib/api';
import { PUBLIC_SITE } from '@/lib/format';
import { Card, Empty, Flash, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { ExternalLinkIcon, UsersIcon } from '@/components/Icons';
import { inviteFirmLawyer, setLawyerAcceptsLeads } from '../../../actions';

type L = {
  id: number;
  slug: string;
  name: string;
  title: string | null;
  verificationStatus: string;
  profileStatus: string;
  acceptsLeads: boolean;
  email: string | null;
  portalUser: string | null;
  invitePending: boolean | null;
  openLeads: number;
  bestRank: number | null;
  activeLicense: boolean;
};

export default async function FirmLawyers({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const [rows, user] = await Promise.all([api<L[]>('/firm/lawyers'), me()]);
  const manage = user.organization?.role === 'owner' || user.organization?.role === 'admin';
  return (
    <>
      <PageHeader
        title="Lawyers"
        icon={<UsersIcon className="h-5 w-5" />}
        description="Every lawyer listed under your firm. Each lawyer can get their own login to manage their profile and enquiries — it uses one seat. Profiles, licences and rankings stay independent of your plan."
      />
      <Flash ok={sp.ok} err={sp.err} />
      <Card>
        {rows.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Lawyer</th>
                  <th>Status</th>
                  <th className="text-right">Best rank</th>
                  <th className="text-right">Open</th>
                  <th>Enquiries</th>
                  <th>Portal access</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((l) => (
                  <tr key={l.id}>
                    <td>
                      <a href={`${PUBLIC_SITE}/lawyers/${l.slug}/`} target="_blank" rel="noopener" className="inline-flex items-center gap-1 font-semibold hover:text-ledger hover:underline">
                        {l.name} <ExternalLinkIcon className="h-3 w-3 text-muted" />
                      </a>
                      {l.title && <span className="block text-xs text-muted">{l.title}</span>}
                    </td>
                    <td className="space-x-1 whitespace-nowrap">
                      <Pill value={l.verificationStatus} />
                      {!l.activeLicense && <Pill value="no active licence" tone="warn" />}
                      {l.profileStatus !== 'published' && <Pill value={l.profileStatus} />}
                    </td>
                    <td className="num text-right">{l.bestRank ? `#${l.bestRank}` : '—'}</td>
                    <td className="num text-right">{l.openLeads}</td>
                    <td>
                      {manage ? (
                        <form action={setLawyerAcceptsLeads}>
                          <input type="hidden" name="id" value={l.id} />
                          <input type="hidden" name="acceptsLeads" value={l.acceptsLeads ? 'false' : 'true'} />
                          <SubmitButton className={`btn btn-xs ${l.acceptsLeads ? 'btn-quiet' : 'btn-primary'}`}><ActionIcons.RefreshIcon />{l.acceptsLeads ? 'Accepting · pause' : 'Paused · resume'}</SubmitButton>
                        </form>
                      ) : (
                        <Pill value={l.acceptsLeads ? 'accepting' : 'paused'} />
                      )}
                    </td>
                    <td className="min-w-[16rem]">
                      {l.portalUser ? (
                        <span className="text-xs">
                          {l.portalUser} {l.invitePending && <Pill value="invited" tone="info" />}
                        </span>
                      ) : manage ? (
                        <form action={inviteFirmLawyer} className="flex gap-1.5">
                          <input type="hidden" name="id" value={l.id} />
                          <input name="email" type="email" required defaultValue={l.email ?? ''} placeholder="lawyer@firm.com" aria-label={`Email for ${l.name}`} className="field h-8 text-xs" />
                          <SubmitButton className="btn btn-quiet btn-xs"><ActionIcons.SendIcon />Invite</SubmitButton>
                        </form>
                      ) : (
                        <span className="text-xs text-muted">none</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<UsersIcon className="h-6 w-6" />}>No lawyers are listed under your firm yet. Ask support to link them.</Empty>
        )}
      </Card>
    </>
  );
}
