
import * as ActionIcons from '@/components/Icons';
import { api, me } from '@/lib/api';
import { date, n } from '@/lib/format';
import { BarChart } from '@/components/BarChart';
import { Card, Empty, Flash, Kpi, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { ChartIcon, CheckIcon, DollarIcon, EyeIcon, InboxIcon, SaveIcon, SparklesIcon, TrendingUpIcon, UserIcon } from '@/components/Icons';
import { LeadList } from '@/components/LeadList';
import { updateOwnProfile } from '../actions';

type Dash = {
  role: 'professional' | 'firm_admin';
  organization: { id: number; name: string; kind: string } | null;
  /** Always set for professionals; set for firm admins only when they have their own profile */
  lawyer: { id: number; slug: string; firstName: string; lastName: string; verificationStatus: string; lastVerifiedAt: string | null; acceptsLeads: boolean; title: string | null; bio: string | null; phone: string | null; email: string | null; websiteUrl: string | null } | null;
  rankings: { city: string; area: string; rank: number; score: number }[];
  views: { day: string; views: number }[];
  leads: { routingId: number; status: string; respondBy: string | null; deliveredAt: string | null; respondedAt: string | null; lawyer: string; lead: { id: string; name: string; email: string; phone: string | null; description: string; city: string | null; practiceArea: string | null; createdAt: string } }[];
  subscriptions: { plan: string; status: string; currentPeriodEnd: string | null }[];
  plans: Record<string, { name: string; price: number; features: string[] }>;
  paymentsEnabled: boolean;
};

const OPEN = ['pending', 'delivered', 'viewed'];

export default async function Portal({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  await me();
  const d = await api<Dash>('/me/dashboard');
  const l = d.lawyer;
  const firm = d.role === 'firm_admin';
  const open = d.leads.filter((x) => OPEN.includes(x.status));
  const totalViews = d.views.reduce((s, v) => s + v.views, 0);
  const active = d.subscriptions.find((s) => s.status === 'active');
  // Best = lowest position number, not whatever the API listed first
  const best = [...d.rankings].sort((a, b) => a.rank - b.rank)[0];
  return (
    <>
      <PageHeader
        title={l ? `Welcome back, ${l.firstName}` : `Welcome back${d.organization ? `, ${d.organization.name}` : ''}`}
        icon={<UserIcon className="h-5 w-5" />}
        description={
          l ? (
            <span className="flex flex-wrap items-center gap-2">
              <span className="font-medium text-ink">
                {l.firstName} {l.lastName}
              </span>
              <Pill value={l.verificationStatus} /> Last verified {date(l.lastVerifiedAt)}
            </span>
          ) : (
            'Enquiries and billing for every lawyer in your firm.'
          )
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <Kpi label="Profile views" icon={<EyeIcon className="h-4 w-4" />} value={n(totalViews)} hint={firm ? 'all firm lawyers, last 30 days' : 'last 30 days'} />
        <Kpi label="Open enquiries" icon={<InboxIcon className="h-4 w-4" />} tone={open.length ? 'warn' : 'default'} value={n(open.length)} hint={`${n(d.leads.length)} received in total`} />
        <Kpi label="Best ranking" icon={<TrendingUpIcon className="h-4 w-4" />} value={best ? `#${best.rank}` : '—'} hint={best ? `${best.area}, ${best.city}` : 'not ranked'} />
        <Kpi label="Plan" icon={<DollarIcon className="h-4 w-4" />} value={<span className="capitalize">{active ? active.plan.replace(/_/g, ' ') : 'Free'}</span>} hint={active ? `renews ${date(active.currentPeriodEnd)}` : 'upgrade below'} />
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-[1.5fr_1fr]">
        <Card title="Enquiries" icon={<InboxIcon className="h-4 w-4" />} actions={open.length > 0 && <span className="num rounded-full bg-brass-soft px-2 py-0.5 text-xs font-bold text-brass">{open.length} open</span>}>
          {d.leads.length ? (
            <LeadList
              items={d.leads.slice(0, 15).map((x) => ({ ...x.lead, routingId: x.routingId, status: x.status, respondBy: x.respondBy, receivedAt: x.lead.createdAt, lawyer: x.lawyer }))}
              back="/portal"
              showLawyer={firm}
              canRespond
            />
          ) : (
            <Empty icon={<InboxIcon className="h-6 w-6" />}>No enquiries yet. Complete your profile and keep “accepting enquiries” on.</Empty>
          )}
          <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">Responding quickly improves your client-experience score, which is 5% of your ranking.</p>
        </Card>
        <div className="space-y-6">
          <Card title="Profile views, last 30 days" icon={<EyeIcon className="h-4 w-4" />}>
            <div className="p-4">
              <BarChart data={d.views.map((v) => ({ x: v.day.slice(5), y: v.views }))} label="Daily profile views" />
            </div>
          </Card>
          {l && (
            <Card title="Your rankings" icon={<ChartIcon className="h-4 w-4" />}>
              {d.rankings.length ? (
                <table className="tbl">
                  <tbody>
                    {d.rankings.map((r) => (
                      <tr key={`${r.city}-${r.area}`}>
                        <td className="w-12">
                          <span className="rank-figure text-2xl">{r.rank}</span>
                        </td>
                        <td>
                          {r.area}, {r.city}
                        </td>
                        <td className="num text-right font-semibold">{r.score.toFixed(1)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <p className="p-4 text-sm text-muted">Not ranked yet — rankings need an active, verified licence.</p>
              )}
              <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">Rankings depend on verified evidence only. Paid plans do not change them.</p>
            </Card>
          )}
        </div>
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-2">
        {l && (
          <Card title="Edit your profile" icon={<UserIcon className="h-4 w-4" />}>
            <form action={updateOwnProfile} className="grid gap-4 p-5 text-sm">
              <input type="hidden" name="id" value={l.id} />
              <label className="block">
                <span className="field-label"><ActionIcons.FileTextIcon />Title</span>
                <input name="title" maxLength={150} defaultValue={l.title ?? ''} className="field" />
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.FileTextIcon />Biography</span>
                <textarea name="bio" rows={5} maxLength={5000} defaultValue={l.bio ?? ''} className="field" />
              </label>
              <div className="grid gap-4 sm:grid-cols-2">
                <label className="block">
                  <span className="field-label"><ActionIcons.PhoneIcon />Phone</span>
                  <input name="phone" type="tel" maxLength={100} defaultValue={l.phone ?? ''} className="field" />
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.GlobeIcon />Website</span>
                  <input name="websiteUrl" type="text" inputMode="url" placeholder="https://" defaultValue={l.websiteUrl ?? ''} className="field" />
                </label>
              </div>
              <label className="flex items-center gap-2.5 font-medium">
                <input type="checkbox" name="acceptsLeads" defaultChecked={l.acceptsLeads} /> Accept enquiries through Justice Choice
              </label>
              <p className="text-xs text-muted">Licences, practice areas and verification are managed by our data team. Use “Report inaccurate information” on your public profile to request a change.</p>
              <div className="border-t border-rule pt-4">
                <SubmitButton pendingLabel="Saving…">
                  <SaveIcon className="h-4 w-4" /> Save profile
                </SubmitButton>
              </div>
            </form>
          </Card>
        )}
        <Card title="Plan & billing" icon={<SparklesIcon className="h-4 w-4" />}>
          <div className="space-y-3 p-5 text-sm">
            <p>
              Current plan: <strong className="capitalize">{active ? active.plan.replace(/_/g, ' ') : 'Free'}</strong>
              {active?.currentPeriodEnd && <span className="text-muted"> · renews {date(active.currentPeriodEnd)}</span>}
            </p>
            <p className="text-xs text-muted">Paid plans add tools and clearly labelled sponsored placement. They never change your organic ranking.</p>
            <a href="/portal/billing" className="btn btn-quiet btn-sm">
              Plans, invoices and Featured placement
            </a>
          </div>
        </Card>
      </div>
    </>
  );
}
