
import * as ActionIcons from '@/components/Icons';
import { api } from '@/lib/api';
import { date } from '@/lib/format';
import { Card, Empty, Flash, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { FeaturedForm } from '@/components/FeaturedForm';
import { AlertIcon, CheckIcon, DollarIcon, ExternalLinkIcon, FileTextIcon, SparklesIcon } from '@/components/Icons';
import { openBillingPortal, startCheckout, subscriptionAction } from '../../actions';

type Plan = { name: string; price: number; features: string[] };
type Sub = {
  id: number;
  plan: string;
  name: string;
  status: string;
  active: boolean;
  inGrace: boolean;
  graceEndsAt: string | null;
  currentPeriodEnd: string | null;
  cancelAtPeriodEnd: boolean;
  canManage: boolean;
  options: { cityId?: number; practiceAreaId?: number } | null;
  canceledAt: string | null;
};
type Overview = {
  organization: { id: number; name: string; hasBillingAccount: boolean };
  role: string;
  paymentsEnabled: boolean;
  portalEnabled: boolean;
  graceDays: number;
  features: { key: string; label: string }[];
  seats: number;
  subscriptions: Sub[];
  invoices: { id: number; number: string | null; amountCents: number; currency: string; status: string; paidAt: string | null; createdAt: string; hostedInvoiceUrl: string | null; invoicePdfUrl: string | null; failureMessage: string | null; plan: string | null }[];
  placements: { id: number; subscriptionId: number | null; isActive: boolean; startsAt: string; endsAt: string; city: string; practiceArea: string | null; advertiser: string }[];
  plans: Record<string, Plan>;
  featured: { slotsPerPage: number; targets: { kind: string; id: number; name: string }[]; cities: { id: number; name: string }[]; practiceAreas: { id: number; name: string }[] };
};

const money = (cents: number, cur: string) => new Intl.NumberFormat('en-US', { style: 'currency', currency: cur.toUpperCase() }).format(cents / 100);

export default async function Billing({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const d = await api<Overview>('/billing/overview');
  const live = d.subscriptions.filter((s) => ['active', 'trialing', 'past_due'].includes(s.status));
  const base = live.find((s) => s.plan === 'premium_profile' || s.plan === 'firm');
  const grace = live.filter((s) => s.inGrace);
  return (
    <>
      <PageHeader
        title="Billing"
        icon={<DollarIcon className="h-5 w-5" />}
        description={`Plans for ${d.organization.name}. Paid plans add tools and clearly labelled sponsored placement — they never change anyone’s organic ranking.`}
        actions={
          d.portalEnabled && (
            <form action={openBillingPortal}>
              <SubmitButton className="btn btn-quiet btn-sm" pendingLabel="Opening…">
                <ExternalLinkIcon className="h-4 w-4" /> Payment methods &amp; invoices
              </SubmitButton>
            </form>
          )
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      {!d.paymentsEnabled && <p className="mb-6 rounded-lg border border-rule bg-paper px-4 py-3 text-sm text-ink-2">Online payments are not configured in this environment. Plans can still be viewed.</p>}
      {grace.map((s) => (
        <p key={s.id} className="mb-6 flex items-start gap-2 rounded-lg border border-danger/30 bg-danger-soft px-4 py-3 text-sm text-danger">
          <AlertIcon className="mt-0.5 h-4 w-4" />
          <span>
            The last payment for <strong>{s.name}</strong> failed. Your features stay on until <strong>{date(s.graceEndsAt, true)}</strong> while Stripe retries — update your payment method to keep them.
          </span>
        </p>
      ))}

      <div className="grid gap-6 xl:grid-cols-[1.4fr_1fr]">
        <Card title="Your plans" icon={<SparklesIcon className="h-4 w-4" />}>
          {d.subscriptions.length ? (
            <ul className="divide-y divide-rule">
              {d.subscriptions.map((s) => (
                <li key={s.id} className="flex flex-wrap items-start justify-between gap-3 p-4 text-sm">
                  <div>
                    <p className="flex flex-wrap items-center gap-2">
                      <strong>{s.name}</strong>
                      <Pill value={s.inGrace ? 'payment failed' : s.status} tone={s.inGrace ? 'bad' : s.active ? 'good' : 'muted'} />
                      {s.cancelAtPeriodEnd && s.status !== 'canceled' && <Pill value="ends at period end" tone="warn" />}
                    </p>
                    <p className="mt-1 text-xs text-muted">
                      {s.status === 'canceled' ? `Ended ${date(s.canceledAt)}` : s.cancelAtPeriodEnd ? `Ends ${date(s.currentPeriodEnd)}` : s.currentPeriodEnd ? `Renews ${date(s.currentPeriodEnd)}` : ''}
                    </p>
                  </div>
                  {s.canManage && s.status !== 'canceled' && d.paymentsEnabled && (
                    <div className="flex flex-wrap gap-2">
                      {s.plan !== 'featured' && (
                        <form action={subscriptionAction.bind(null, 'change')}>
                          <input type="hidden" name="id" value={s.id} />
                          <input type="hidden" name="plan" value={s.plan === 'firm' ? 'premium_profile' : 'firm'} />
                          <SubmitButton className="btn btn-quiet btn-xs" confirm={`Switch to ${s.plan === 'firm' ? 'Premium profile' : 'Firm'}? Stripe prorates the difference.`}>
                            <ActionIcons.RefreshIcon />Switch to {s.plan === 'firm' ? 'Premium' : 'Firm'}
                          </SubmitButton>
                        </form>
                      )}
                      {s.cancelAtPeriodEnd ? (
                        <form action={subscriptionAction.bind(null, 'resume')}>
                          <input type="hidden" name="id" value={s.id} />
                          <SubmitButton className="btn btn-quiet btn-xs"><ActionIcons.CheckCircleIcon />Keep plan</SubmitButton>
                        </form>
                      ) : (
                        <form action={subscriptionAction.bind(null, 'cancel')}>
                          <input type="hidden" name="id" value={s.id} />
                          <SubmitButton className="btn btn-danger-quiet btn-xs" confirm="Cancel at the end of the paid period? You keep the features until then.">
                            <ActionIcons.XCircleIcon />Cancel
                          </SubmitButton>
                        </form>
                      )}
                    </div>
                  )}
                </li>
              ))}
            </ul>
          ) : (
            <Empty icon={<SparklesIcon className="h-6 w-6" />}>You’re on the free profile.</Empty>
          )}
        </Card>

        <Card title="Included in your plans" icon={<CheckIcon className="h-4 w-4" />}>
          {d.features.length ? (
            <ul className="divide-y divide-rule text-sm">
              {d.features.map((f) => (
                <li key={f.key} className="flex items-center gap-2 px-4 py-2">
                  <CheckIcon className="h-4 w-4 text-ledger" /> {f.label}
                </li>
              ))}
            </ul>
          ) : (
            <p className="p-4 text-sm text-muted">Free features only.</p>
          )}
          <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">
            {d.seats} team seats. If a payment fails, features stay on for {d.graceDays} days while Stripe retries.
          </p>
        </Card>
      </div>

      {!base && (
        <Card title="Upgrade" icon={<SparklesIcon className="h-4 w-4" />} className="mt-6">
          <ul className="grid gap-4 p-4 md:grid-cols-2">
            {(['premium_profile', 'firm'] as const).map((key) => {
              const p = d.plans[key]!;
              return (
                <li key={key} className="flex flex-col rounded-lg border border-rule p-4 text-sm">
                  <p className="font-semibold">
                    {p.name} <span className="num font-normal text-muted">${p.price}/month</span>
                  </p>
                  <ul className="mt-2 flex-1 space-y-1 text-xs text-ink-2">
                    {p.features.map((f) => (
                      <li key={f} className="flex gap-1.5">
                        <CheckIcon className="mt-0.5 h-3 w-3 shrink-0 text-ledger" /> {f}
                      </li>
                    ))}
                  </ul>
                  <form action={startCheckout} className="mt-3">
                    <input type="hidden" name="plan" value={key} />
                    <SubmitButton disabled={!d.paymentsEnabled} pendingLabel="Opening checkout…">
                      <ActionIcons.CheckCircleIcon />Choose {p.name}
                    </SubmitButton>
                  </form>
                </li>
              );
            })}
          </ul>
        </Card>
      )}

      <Card title="Featured placement" icon={<SparklesIcon className="h-4 w-4" />} className="mt-6">
        {d.placements.length > 0 && (
          <ul className="divide-y divide-rule border-b border-rule text-sm">
            {d.placements.map((p) => (
              <li key={p.id} className="flex flex-wrap items-center justify-between gap-2 px-4 py-2.5">
                <span>
                  <strong>{p.advertiser}</strong> · {p.practiceArea ?? 'all practice areas'}, {p.city}
                </span>
                <span className="flex items-center gap-2 text-xs text-muted">
                  <Pill value={p.isActive && new Date(p.endsAt) > new Date() ? 'live' : 'ended'} /> {date(p.startsAt)} – {date(p.endsAt)}
                </span>
              </li>
            ))}
          </ul>
        )}
        {d.featured.targets.length ? (
          <FeaturedForm cities={d.featured.cities} practiceAreas={d.featured.practiceAreas} targets={d.featured.targets} price={d.plans.featured!.price} enabled={d.paymentsEnabled} />
        ) : (
          <p className="p-4 text-sm text-muted">Featured placement needs a published lawyer or firm page in your organization.</p>
        )}
      </Card>

      <Card title="Invoices" icon={<FileTextIcon className="h-4 w-4" />} className="mt-6">
        {d.invoices.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Invoice</th>
                  <th>Plan</th>
                  <th className="text-right">Amount</th>
                  <th>Status</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                {d.invoices.map((i) => (
                  <tr key={i.id}>
                    <td className="whitespace-nowrap text-xs">{date(i.paidAt ?? i.createdAt)}</td>
                    <td className="text-xs">{i.number ?? '—'}</td>
                    <td className="text-xs capitalize">{i.plan?.replace(/_/g, ' ') ?? '—'}</td>
                    <td className="num text-right">{money(i.amountCents, i.currency)}</td>
                    <td>
                      <Pill value={i.status} />
                      {i.failureMessage && <span className="block text-[11px] text-danger">{i.failureMessage}</span>}
                    </td>
                    <td className="whitespace-nowrap text-xs">
                      {i.hostedInvoiceUrl && (
                        <a href={i.hostedInvoiceUrl} target="_blank" rel="noopener noreferrer" className="link mr-3">
                          View
                        </a>
                      )}
                      {i.invoicePdfUrl && (
                        <a href={i.invoicePdfUrl} target="_blank" rel="noopener noreferrer" className="link">
                          PDF
                        </a>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<FileTextIcon className="h-6 w-6" />}>No invoices yet.</Empty>
        )}
      </Card>
    </>
  );
}
