
import * as ActionIcons from '@/components/Icons';
import { api } from '@/lib/api';
import { n, PUBLIC_SITE } from '@/lib/format';
import { Card, Flash, Kpi, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { BuildingIcon, EyeIcon, ExternalLinkIcon, ImageIcon, InboxIcon, MapPinIcon, PlusIcon, SaveIcon, UsersIcon } from '@/components/Icons';
import { addOffice, removeOffice, updateFirmProfile, updateOffice, uploadFirmLogo } from '../../actions';

type Office = { id: number; name: string; addressLine1: string | null; addressLine2: string | null; postalCode: string | null; cityId: number | null; phone: string | null; email: string | null; isPrimary: boolean };
type Firm = {
  organization: { id: number; name: string };
  role: string;
  firms: { id: number; name: string; slug: string }[];
  firm: {
    id: number;
    name: string;
    slug: string;
    description: string | null;
    websiteUrl: string | null;
    phone: string | null;
    email: string | null;
    foundedYear: number | null;
    addressLine1: string | null;
    addressLine2: string | null;
    logoUrl: string | null;
    verificationStatus: string;
    city: string | null;
  } | null;
  offices: Office[];
  seats: { plan: string; used: number; limit: number };
  features: string[];
  stats: { lawyers: number; verified: number; open_leads: number; leads_30d: number; views_30d: number };
  cities: { id: number; name: string }[];
};

function OfficeFields({ o, cities }: { o?: Office; cities: { id: number; name: string }[] }) {
  return (
    <div className="grid gap-3 sm:grid-cols-2">
      <label className="block">
        <span className="field-label"><ActionIcons.BuildingIcon />Office name</span>
        <input name="name" required minLength={2} maxLength={150} defaultValue={o?.name ?? ''} className="field" />
      </label>
      <label className="block">
        <span className="field-label"><ActionIcons.MapPinIcon />City</span>
        <select name="cityId" defaultValue={o?.cityId ?? ''} className="field">
          <option value="">—</option>
          {cities.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      </label>
      <label className="block">
        <span className="field-label"><ActionIcons.MapPinIcon />Address</span>
        <input name="addressLine1" maxLength={300} defaultValue={o?.addressLine1 ?? ''} className="field" />
      </label>
      <label className="block">
        <span className="field-label"><ActionIcons.MapPinIcon />Address line 2</span>
        <input name="addressLine2" maxLength={300} defaultValue={o?.addressLine2 ?? ''} className="field" />
      </label>
      <label className="block">
        <span className="field-label"><ActionIcons.MapPinIcon />Postal code</span>
        <input name="postalCode" maxLength={20} defaultValue={o?.postalCode ?? ''} className="field" />
      </label>
      <label className="block">
        <span className="field-label"><ActionIcons.PhoneIcon />Phone</span>
        <input name="phone" type="tel" maxLength={100} defaultValue={o?.phone ?? ''} className="field" />
      </label>
      <label className="block">
        <span className="field-label"><ActionIcons.MailIcon />Email</span>
        <input name="email" type="email" maxLength={255} defaultValue={o?.email ?? ''} className="field" />
      </label>
      <label className="flex items-center gap-2 self-end pb-2 text-sm">
        <input type="checkbox" name="isPrimary" defaultChecked={o?.isPrimary} /> Main office
      </label>
    </div>
  );
}

export default async function FirmPage({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const d = await api<Firm>(`/firm${sp.firm ? `?firmId=${encodeURIComponent(sp.firm)}` : ''}`);
  // Editing the firm page is a Firm-plan feature; owners/admins without it see a read-only page
  const canManagePage = d.features.includes('firm.manage');
  const manage = (d.role === 'owner' || d.role === 'admin') && canManagePage;
  const f = d.firm;
  return (
    <>
      <PageHeader
        title={f?.name ?? d.organization.name}
        icon={<BuildingIcon className="h-5 w-5" />}
        description={f ? <span className="flex flex-wrap items-center gap-2">Firm page <Pill value={f.verificationStatus} /> {f.city && `· ${f.city}`}</span> : 'Your organization has no public firm page yet. Contact support to link one.'}
        actions={
          f && (
            <a href={`${PUBLIC_SITE}/firms/${f.slug}/`} target="_blank" rel="noopener" className="btn btn-quiet btn-sm">
              <ExternalLinkIcon className="h-4 w-4" /> Public page
            </a>
          )
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      {!canManagePage && (d.role === 'owner' || d.role === 'admin') && (
        <p className="mb-6 rounded-lg border border-brass/40 bg-brass-soft px-4 py-3 text-sm text-ink-2">
          Editing the firm page, logo and offices is part of the <strong>Firm</strong> plan.{' '}
          <a href="/portal/billing" className="link">
            See plans
          </a>
        </p>
      )}
      {d.firms.length > 1 && (
        <nav className="mb-4 flex flex-wrap gap-2 text-sm">
          {d.firms.map((x) => (
            <a key={x.id} href={`?firm=${x.id}`} className={`btn btn-sm ${x.id === f?.id ? 'btn-primary' : 'btn-quiet'}`}>
              {x.name}
            </a>
          ))}
        </nav>
      )}
      <div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-4">
        <Kpi label="Lawyers" icon={<UsersIcon className="h-4 w-4" />} value={n(d.stats.lawyers)} hint={`${n(d.stats.verified)} verified`} href="/portal/firm/lawyers" />
        <Kpi label="Open enquiries" icon={<InboxIcon className="h-4 w-4" />} value={n(d.stats.open_leads)} tone={d.stats.open_leads ? 'warn' : 'default'} hint={`${n(d.stats.leads_30d)} in 30 days`} href="/portal/firm/leads" />
        <Kpi label="Profile views" icon={<EyeIcon className="h-4 w-4" />} value={n(d.stats.views_30d)} hint="all lawyers, 30 days" />
        <Kpi label="Seats" icon={<UsersIcon className="h-4 w-4" />} value={`${d.seats.used} / ${d.seats.limit}`} tone={d.seats.used >= d.seats.limit ? 'warn' : 'default'} hint={`${d.seats.plan.replace('_', ' ')} plan`} href="/portal/firm/team" />
      </div>

      {f && (
        <div className="grid gap-6 xl:grid-cols-[1.5fr_1fr]">
          <Card title="Firm profile" icon={<BuildingIcon className="h-4 w-4" />}>
            <form action={updateFirmProfile} className="grid gap-4 p-5 text-sm">
              <input type="hidden" name="firmId" value={f.id} />
              <label className="block">
                <span className="field-label"><ActionIcons.FileTextIcon />Description</span>
                <textarea name="description" rows={6} maxLength={5000} defaultValue={f.description ?? ''} disabled={!manage} className="field" />
              </label>
              <div className="grid gap-4 sm:grid-cols-2">
                <label className="block">
                  <span className="field-label"><ActionIcons.GlobeIcon />Website</span>
                  <input name="websiteUrl" inputMode="url" defaultValue={f.websiteUrl ?? ''} disabled={!manage} className="field" />
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.PhoneIcon />Phone</span>
                  <input name="phone" type="tel" maxLength={100} defaultValue={f.phone ?? ''} disabled={!manage} className="field" />
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.MailIcon />Email</span>
                  <input name="email" type="email" maxLength={255} defaultValue={f.email ?? ''} disabled={!manage} className="field" />
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.CalendarIcon />Founded</span>
                  <input name="foundedYear" type="number" min={1700} max={new Date().getFullYear()} defaultValue={f.foundedYear ?? ''} disabled={!manage} className="field" />
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.BuildingIcon />Head office address</span>
                  <input name="addressLine1" maxLength={300} defaultValue={f.addressLine1 ?? ''} disabled={!manage} className="field" />
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.MapPinIcon />Address line 2</span>
                  <input name="addressLine2" maxLength={300} defaultValue={f.addressLine2 ?? ''} disabled={!manage} className="field" />
                </label>
              </div>
              <p className="text-xs text-muted">The firm name and verification come from official sources. Ask support to correct them.</p>
              {manage && (
                <div>
                  <SubmitButton pendingLabel="Saving…">
                    <SaveIcon className="h-4 w-4" /> Save firm profile
                  </SubmitButton>
                </div>
              )}
            </form>
          </Card>

          <Card title="Logo" icon={<ImageIcon className="h-4 w-4" />}>
            <div className="space-y-4 p-5 text-sm">
              {f.logoUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={f.logoUrl} alt={`${f.name} logo`} className="h-24 max-w-[12rem] rounded-lg border border-rule bg-white object-contain p-2" />
              ) : (
                <div className="grid h-24 w-40 place-items-center rounded-lg border border-dashed border-rule-strong text-muted">
                  <ImageIcon className="h-8 w-8" />
                </div>
              )}
              {manage && (
                <form action={uploadFirmLogo} className="space-y-2">
                  <input type="hidden" name="firmId" value={f.id} />
                  <input name="file" type="file" required accept="image/jpeg,image/png,image/webp" className="field" />
                  <p className="text-xs text-muted">JPG, PNG or WebP, up to 2 MB.</p>
                  <SubmitButton pendingLabel="Uploading…"><ActionIcons.UploadIcon />Upload logo</SubmitButton>
                </form>
              )}
            </div>
          </Card>
        </div>
      )}

      {f && (
        <Card title={`Offices (${d.offices.length})`} icon={<MapPinIcon className="h-4 w-4" />} className="mt-6">
          <ul className="divide-y divide-rule">
            {d.offices.map((o) => (
              <li key={o.id} className="p-4">
                {manage ? (
                  <details>
                    <summary className="flex cursor-pointer flex-wrap items-center gap-2 text-sm">
                      <strong>{o.name}</strong> {o.isPrimary && <Pill value="main" tone="good" />}
                      <span className="text-muted">
                        {[o.addressLine1, d.cities.find((c) => c.id === o.cityId)?.name].filter(Boolean).join(', ') || 'No address'}
                      </span>
                    </summary>
                    <form action={updateOffice} className="mt-3 space-y-3">
                      <input type="hidden" name="id" value={o.id} />
                      <OfficeFields o={o} cities={d.cities} />
                      <div className="flex gap-2">
                        <SubmitButton pendingLabel="Saving…"><ActionIcons.SaveIcon />Save office</SubmitButton>
                        <SubmitButton formAction={removeOffice} formNoValidate className="btn btn-danger-quiet btn-sm" confirm={`Remove ${o.name}?`}>
                          <ActionIcons.TrashIcon />Remove
                        </SubmitButton>
                      </div>
                    </form>
                  </details>
                ) : (
                  <p className="text-sm">
                    <strong>{o.name}</strong> · {[o.addressLine1, o.phone].filter(Boolean).join(' · ')}
                  </p>
                )}
              </li>
            ))}
            {!d.offices.length && <li className="p-4 text-sm text-muted">No offices listed.</li>}
          </ul>
          {manage && (
            <details className="border-t border-rule p-4">
              <summary className="inline-flex cursor-pointer items-center gap-1.5 text-sm font-medium text-ledger">
                <PlusIcon className="h-4 w-4" /> Add an office
              </summary>
              <form action={addOffice} className="mt-3 space-y-3">
                <input type="hidden" name="firmId" value={f.id} />
                <OfficeFields cities={d.cities} />
                <SubmitButton pendingLabel="Adding…"><ActionIcons.PlusIcon />Add office</SubmitButton>
              </form>
            </details>
          )}
        </Card>
      )}
    </>
  );
}
