"use client";
import { useEffect, useState } from "react";
import { Building2, Plus } from "lucide-react";
import { Badge, Button, Card, Field, Input, PageHeader, Select, Sheet, Spinner, Toggle, api, useAction, useUI } from "@/components/ui";
import { compact, money, useApi } from "@/components/hooks";
import { IndustrySelect, industryExamples } from "@/components/industry-select";
import { INDUSTRIES, normalizeIndustry } from "@/lib/industry";

export default function AgencyPage() {
  const a = useApi<{ data: { agency: any; workspaces: any[] } }>("/agency");
  const [brand, setBrand] = useState<any>(null);
  const [newWs, setNewWs] = useState(false);
  const { busy, run } = useAction();
  const { push } = useUI();
  useEffect(() => { if (a.data) setBrand({ name: a.data.data.agency.name, ...a.data.data.agency.branding }); }, [a.data]);
  if (a.error) return <p className="text-[13px] text-bad">{a.error}</p>;
  if (!a.data || !brand) return <Spinner />;
  return (
    <>
      <PageHeader title="Agency & white-label" subtitle="Client sub-accounts with isolated data, cross-client overview and your own branding"
        actions={<Button variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setNewWs(true)}>New client workspace</Button>} />
      <Card title="Client workspaces (last 30 days)" bodyClass="p-0">
        <table className="table-mac">
          <thead><tr><th>Workspace</th><th>Industry</th><th>Plan</th><th>Region</th><th className="text-right">Contacts</th><th className="text-right">Leads</th><th className="text-right">Won</th><th className="text-right">Revenue</th><th className="text-right">Ad spend</th><th /></tr></thead>
          <tbody>{a.data.data.workspaces.map((w) => (
            <tr key={w.id}><td className="font-medium"><span className="inline-flex items-center gap-2"><Building2 className="h-4 w-4 text-brand" />{w.name}</span></td><td className="text-[12px] text-ink-2">{INDUSTRIES[normalizeIndustry(w.industry)]!.label}</td><td><Badge>{w.plan}</Badge></td><td className="text-ink-3">{w.timezone} · {w.currency}</td>
              <td className="text-right">{compact(w.contacts)}</td><td className="text-right">{w.leads30d}</td><td className="text-right">{w.won30d}</td><td className="text-right">{money(w.revenue30d, w.currency)}</td><td className="text-right">{money(w.spend30d, w.currency)}</td>
              <td className="text-right"><button className="text-[12px] text-brand hover:underline" onClick={async () => { await api("/api/auth/workspace", { body: { workspaceId: w.id } }); location.href = "/dashboard"; }}>Open →</button></td></tr>
          ))}</tbody>
        </table>
      </Card>
      <div className="mt-4 grid gap-4 xl:grid-cols-[1fr_360px]">
        <Card title="White-label branding" subtitle="Clients see only your branding in the app, reports and emails" actions={<Button size="sm" variant="primary" loading={busy} onClick={() => run(async () => { await api("/agency", { method: "PATCH", body: { name: brand.name, branding: { logoUrl: brand.logoUrl ?? "", primaryColor: brand.primaryColor ?? "#2563EB", productName: brand.productName ?? "", loginDomain: brand.loginDomain ?? "", hidePlatformBranding: !!brand.hidePlatformBranding } } }); a.reload(); }, "Branding saved — reload to see it")}>Save</Button>}>
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="Agency name"><Input value={brand.name} onChange={(e) => setBrand({ ...brand, name: e.target.value })} /></Field>
            <Field label="Product name shown to clients"><Input value={brand.productName ?? ""} onChange={(e) => setBrand({ ...brand, productName: e.target.value })} placeholder="Tempest Pulse" /></Field>
            <Field label="Logo URL (PNG/JPG)"><Input value={brand.logoUrl ?? ""} onChange={(e) => setBrand({ ...brand, logoUrl: e.target.value })} /></Field>
            <Field label="Primary colour"><div className="flex gap-2"><input type="color" className="h-8 w-10 rounded" value={brand.primaryColor ?? "#2563EB"} onChange={(e) => setBrand({ ...brand, primaryColor: e.target.value })} /><Input value={brand.primaryColor ?? "#2563EB"} onChange={(e) => setBrand({ ...brand, primaryColor: e.target.value })} /></div></Field>
            <Field label="Custom login domain" hint="Add the domain to Vercel and point a CNAME at it" className="sm:col-span-2"><Input value={brand.loginDomain ?? ""} onChange={(e) => setBrand({ ...brand, loginDomain: e.target.value })} placeholder="app.youragency.com" /></Field>
          </div>
          <div className="mt-3"><Toggle checked={!!brand.hidePlatformBranding} onChange={(v) => setBrand({ ...brand, hidePlatformBranding: v })} label="Hide “by Brand Tempest” from reports and emails" /></div>
        </Card>
        <Card title="Preview">
          <div className="overflow-hidden rounded-[12px] border border-line">
            <div className="flex items-center gap-2 p-3" style={{ background: brand.primaryColor ?? "#2563EB" }}>{brand.logoUrl ? <img src={brand.logoUrl} alt="" className="h-7 rounded bg-white/90 p-0.5" /> : <span className="grid h-7 w-7 place-items-center rounded bg-white/25 font-bold text-white">{(brand.productName || brand.name)[0]}</span>}<span className="font-display font-bold text-white">{brand.productName || brand.name}</span></div>
            <div className="p-3 text-[12px] text-ink-3">Client report · Weekly performance</div>
          </div>
        </Card>
      </div>
      {newWs && <NewWorkspace onClose={() => setNewWs(false)} onDone={() => { setNewWs(false); a.reload(); push("ok", "Workspace created — you are its admin"); }} />}
    </>
  );
}

function NewWorkspace({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
  const [f, setF] = useState({ name: "", timezone: "Asia/Dhaka", currency: "BDT", locale: "en", plan: "growth", industry: "general" });
  const { busy, run } = useAction();
  return (
    <Sheet open onClose={onClose} width={460} title="New client workspace" footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(async () => { await api("/agency/workspaces", { body: f }); onDone(); })}>Create</Button></>}>
      <div className="space-y-3">
        <Field label="Client name"><Input autoFocus value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Field>
        <Field label="Industry" hint={industryExamples(f.industry) || "Sets the funnel, lead fields, AI questions and labels"}><IndustrySelect value={f.industry} onChange={(v) => setF({ ...f, industry: v })} /></Field>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Timezone"><Select value={f.timezone} onChange={(e) => setF({ ...f, timezone: e.target.value })}><option>Asia/Dhaka</option><option>Australia/Sydney</option><option>Australia/Melbourne</option><option>America/New_York</option><option>America/Los_Angeles</option></Select></Field>
          <Field label="Currency"><Select value={f.currency} onChange={(e) => setF({ ...f, currency: e.target.value })}><option>BDT</option><option>USD</option><option>AUD</option></Select></Field>
          <Field label="Language"><Select value={f.locale} onChange={(e) => setF({ ...f, locale: e.target.value })}><option value="en">English</option><option value="bn">বাংলা</option></Select></Field>
          <Field label="Plan"><Select value={f.plan} onChange={(e) => setF({ ...f, plan: e.target.value })}><option value="starter">Starter</option><option value="growth">Growth</option><option value="agency">Agency</option></Select></Field>
        </div>
      </div>
    </Sheet>
  );
}
