"use client";

import {
  Activity,
  BadgeIndianRupee,
  BellRing,
  Boxes,
  Building2,
  Check,
  ChevronRight,
  CircleUserRound,
  Download,
  FileSpreadsheet,
  FileText,
  LayoutDashboard,
  LoaderCircle,
  Megaphone,
  PackageSearch,
  Palette,
  Plus,
  RefreshCw,
  Search,
  Settings2,
  ShoppingBag,
  TrendingUp,
  UserCog,
  Users,
  WalletCards,
  X,
} from "lucide-react";
import { FormEvent, useCallback, useEffect, useMemo, useState } from "react";
import { useTenant } from "@/components/tenant-provider";
import { formatPrice } from "@/lib/catalog";
import TenantSettings from "./tenant-settings";

type ModuleId = "overview" | "branding" | "users" | "vendors" | "billing" | "tally" | "cms" | "erp" | "crm" | "notifications";
type FormResource = "user" | "vendor" | "invoice" | "page" | "inventory" | "crm" | "notification";

type UserRow = { id: number; name: string; email: string; phone: string; role: string; status: string; phoneVerified: boolean; createdAt: string };
type VendorRow = { id: number; companyName: string; contactName: string; email: string; phone: string; gstin: string | null; commissionRate: string; status: string; createdAt: string };
type ProductRow = { id: number; title: string; sku: string | null; seller: string; stock: number; price: string; approvalStatus: string; active: boolean };
type InvoiceRow = { id: number; invoiceNumber: string; customerName: string; subtotal: string; taxAmount: string; total: string; status: string; createdAt: string };
type CrmRow = { id: number; name: string; company: string | null; email: string | null; phone: string | null; stage: string; value: string; nextFollowUp: string | null; createdAt: string };
type PageRow = { id: number; title: string; slug: string; status: string; updatedAt: string };
type CampaignRow = { id: number; title: string; audience: string; channels: string[]; status: string; sentCount: number; failedCount: number; createdAt: string };
type InventoryRow = { id: number; productId: number; type: string; quantity: number; reference: string | null; createdAt: string };
type AuditRow = { id: number; action: string; entity: string; entityId: string | null; createdAt: string };
type EnterpriseData = {
  users: UserRow[]; vendors: VendorRow[]; products: ProductRow[]; invoices: InvoiceRow[]; crm: CrmRow[];
  pages: PageRow[]; campaigns: CampaignRow[]; inventory: InventoryRow[]; audits: AuditRow[];
  deliveries: Array<{ id: number; channel: string; status: string }>;
  orders: Array<{ id: number; status: string; total: string }>;
  stats: { revenue: number; users: number; operators: number; vendors: number; products: number; lowStock: number; receivables: number; pipeline: number; queuedNotifications: number };
};

const emptyData: EnterpriseData = {
  users: [], vendors: [], products: [], invoices: [], crm: [], pages: [], campaigns: [], inventory: [], audits: [], deliveries: [], orders: [],
  stats: { revenue: 0, users: 0, operators: 0, vendors: 0, products: 0, lowStock: 0, receivables: 0, pipeline: 0, queuedNotifications: 0 },
};

const modules: Array<{ id: ModuleId; label: string; icon: React.ElementType; description: string }> = [
  { id: "overview", label: "Command centre", icon: LayoutDashboard, description: "Business health and activity" },
  { id: "branding", label: "Brand & tenants", icon: Palette, description: "Resale stores, contacts, language and theme" },
  { id: "users", label: "Users & operators", icon: UserCog, description: "Roles, access and customers" },
  { id: "vendors", label: "Multivendor", icon: Building2, description: "Seller onboarding and status" },
  { id: "billing", label: "Billing", icon: WalletCards, description: "GST invoices and receivables" },
  { id: "tally", label: "Tally", icon: FileSpreadsheet, description: "Accounting data export" },
  { id: "cms", label: "CMS", icon: FileText, description: "Pages and publishing" },
  { id: "erp", label: "ERP & inventory", icon: Boxes, description: "Stock and product ledger" },
  { id: "crm", label: "CRM", icon: Users, description: "Leads and customer pipeline" },
  { id: "notifications", label: "Notification server", icon: BellRing, description: "Email and voice campaigns" },
];

const resourceByModule: Partial<Record<ModuleId, FormResource>> = {
  users: "user", vendors: "vendor", billing: "invoice", cms: "page", erp: "inventory", crm: "crm", notifications: "notification",
};

export default function EnterpriseSuite() {
  const { tenant } = useTenant();
  const [active, setActive] = useState<ModuleId>("overview");
  const [data, setData] = useState<EnterpriseData>(emptyData);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState<FormResource | null>(null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [toast, setToast] = useState("");
  const [query, setQuery] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/enterprise");
      const result = (await response.json()) as EnterpriseData & { error?: string };
      if (!response.ok) throw new Error(result.error || "Could not load workspace");
      setData(result);
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Could not load workspace");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { void load(); }, [load]);
  useEffect(() => { if (!toast) return; const timer = window.setTimeout(() => setToast(""), 2500); return () => window.clearTimeout(timer); }, [toast]);

  async function submitRecord(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!modal) return;
    setSaving(true);
    setError("");
    const form = new FormData(event.currentTarget);
    const payload: Record<string, unknown> = { resource: modal, ...Object.fromEntries(form.entries()) };
    if (modal === "notification") {
      payload.channels = form.getAll("channels");
      payload.sendNow = form.get("sendNow") === "on";
    }
    try {
      const response = await fetch("/api/enterprise", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
      const result = (await response.json()) as { error?: string; queued?: number; sent?: number };
      if (!response.ok) throw new Error(result.error || "Could not save record");
      setModal(null);
      setToast(modal === "notification" ? `Campaign saved: ${result.sent ?? 0} sent, ${result.queued ?? 0} queued` : "Record saved successfully");
      await load();
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Could not save record");
    } finally {
      setSaving(false);
    }
  }

  async function updateStatus(resource: "user" | "vendor" | "page" | "invoice", id: number, status: string) {
    try {
      const response = await fetch("/api/enterprise", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ resource, operation: "status", id, status }) });
      if (!response.ok) throw new Error();
      setToast("Status updated");
      await load();
    } catch { setToast("Status update failed"); }
  }

  function selectModule(id: ModuleId) {
    setActive(id);
    setQuery("");
    setError("");
  }

  const currentModule = modules.find((module) => module.id === active)!;
  const formResource = resourceByModule[active];

  return (
    <main className="min-h-[calc(100vh-72px)] bg-[#edf2f7]">
      <div className="mx-auto flex max-w-[1540px]">
        <aside className="sticky top-0 hidden h-[calc(100vh-72px)] w-64 shrink-0 overflow-y-auto border-r border-slate-200 bg-white p-4 lg:block">
          <div className="rounded-2xl bg-[var(--navy)] p-4 text-white"><div className="flex items-center gap-3"><span className="grid h-10 w-10 place-items-center rounded-xl bg-[var(--brand)]"><Settings2 size={20} /></span><div><p className="text-sm font-black">{tenant.brandName} One</p><p className="text-[9px] text-blue-200">Enterprise OS</p></div></div><div className="mt-4 flex items-center gap-2 rounded-lg bg-white/10 px-3 py-2 text-[9px] font-bold text-green-300"><span className="h-2 w-2 rounded-full bg-green-400" /> All systems operational</div></div>
          <nav className="mt-5 space-y-1">{modules.map((module) => { const Icon = module.icon; return <button key={module.id} onClick={() => selectModule(module.id)} className={`flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left ${active === module.id ? "bg-blue-50 text-[#155ee9]" : "text-slate-600 hover:bg-slate-50"}`}><Icon size={17} /><span className="flex-1 text-xs font-black">{module.label}</span>{active === module.id && <ChevronRight size={14} />}</button>; })}</nav>
          <div className="mt-6 rounded-xl border border-orange-100 bg-orange-50 p-3"><p className="text-[10px] font-black text-orange-800">Provider setup</p><p className="mt-1 text-[9px] leading-4 text-orange-700">Configure Twilio and Resend environment keys for live voice calls and email delivery.</p></div>
        </aside>

        <div className="min-w-0 flex-1 px-4 py-6 sm:px-7 lg:px-9">
          <div className="scrollbar-none mb-5 flex gap-2 overflow-x-auto lg:hidden">{modules.map((module) => { const Icon = module.icon; return <button key={module.id} onClick={() => selectModule(module.id)} className={`flex shrink-0 items-center gap-2 rounded-xl px-3 py-2 text-[10px] font-black ${active === module.id ? "bg-[#155ee9] text-white" : "bg-white text-slate-600"}`}><Icon size={14} />{module.label}</button>; })}</div>
          <header className="flex flex-wrap items-center justify-between gap-4"><div><p className="text-[10px] font-black uppercase tracking-[0.16em] text-[var(--brand)]">{tenant.brandName} One / {currentModule.label}</p><h1 className="mt-1 text-2xl font-black tracking-[-0.035em] sm:text-3xl">{currentModule.label}</h1><p className="mt-1 text-xs text-slate-500">{currentModule.description}</p></div><div className="flex items-center gap-2"><button onClick={() => void load()} className="grid h-10 w-10 place-items-center rounded-xl border border-slate-200 bg-white text-slate-500"><RefreshCw size={16} className={loading ? "animate-spin" : ""} /></button>{formResource && <button onClick={() => { setModal(formResource); setError(""); }} className="flex items-center gap-2 rounded-xl bg-[#155ee9] px-4 py-3 text-xs font-black text-white shadow-lg"><Plus size={16} /> Add {currentModule.label.split(" ")[0]}</button>}<span className="hidden items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-black sm:flex"><CircleUserRound size={18} className="text-[#155ee9]" /> Administrator</span></div></header>

          {error && !modal && <div className="mt-5 rounded-xl border border-red-100 bg-red-50 p-4 text-xs font-bold text-red-600">{error}</div>}
          {loading && <div className="mt-10 flex items-center justify-center gap-2 rounded-2xl bg-white p-16 text-sm font-bold text-slate-400"><LoaderCircle size={19} className="animate-spin" /> Loading enterprise data…</div>}
          {!loading && <div className="mt-7">{active === "overview" && <Overview data={data} onSelect={selectModule} />}{active === "branding" && <TenantSettings />}{active === "users" && <UsersModule rows={data.users} query={query} setQuery={setQuery} onStatus={updateStatus} />}{active === "vendors" && <VendorsModule vendors={data.vendors} products={data.products} onStatus={updateStatus} />}{active === "billing" && <BillingModule invoices={data.invoices} onStatus={updateStatus} />}{active === "tally" && <TallyModule invoices={data.invoices} />}{active === "cms" && <CmsModule pages={data.pages} onStatus={updateStatus} />}{active === "erp" && <ErpModule products={data.products} inventory={data.inventory} />}{active === "crm" && <CrmModule contacts={data.crm} />}{active === "notifications" && <NotificationsModule campaigns={data.campaigns} deliveries={data.deliveries} />}</div>}
        </div>
      </div>

      {modal && <RecordModal resource={modal} products={data.products} saving={saving} error={error} onClose={() => { setModal(null); setError(""); }} onSubmit={submitRecord} />}
      {toast && <div className="fixed bottom-6 left-1/2 z-[80] flex -translate-x-1/2 items-center gap-2 rounded-xl bg-[#101d37] px-5 py-3 text-xs font-bold text-white shadow-2xl"><Check size={14} className="text-green-400" />{toast}</div>}
    </main>
  );
}

function Overview({ data, onSelect }: { data: EnterpriseData; onSelect: (id: ModuleId) => void }) {
  return <><section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">{[[BadgeIndianRupee, "Gross commerce", formatPrice(data.stats.revenue), "Revenue", "bg-blue-50 text-blue-600"], [Users, "Active identities", String(data.stats.users), `${data.stats.operators} operators`, "bg-violet-50 text-violet-600"], [Building2, "Marketplace vendors", String(data.stats.vendors), `${data.stats.products} products`, "bg-orange-50 text-orange-600"], [TrendingUp, "CRM pipeline", formatPrice(data.stats.pipeline), `${data.stats.queuedNotifications} alerts queued`, "bg-green-50 text-green-600"]].map(([Icon, label, value, detail, style]) => { const MetricIcon = Icon as React.ElementType; return <article key={String(label)} className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"><div className="flex items-start justify-between"><span className={`grid h-10 w-10 place-items-center rounded-xl ${String(style)}`}><MetricIcon size={19} /></span><Activity size={15} className="text-slate-300" /></div><p className="mt-4 text-2xl font-black">{String(value)}</p><p className="mt-1 text-xs font-black text-slate-600">{String(label)}</p><p className="mt-1 text-[9px] text-slate-400">{String(detail)}</p></article>; })}</section><section className="mt-5 rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"><div className="flex items-center justify-between"><div><h2 className="font-black">Business modules</h2><p className="mt-1 text-[10px] text-slate-400">One connected source of truth</p></div><span className="rounded-full bg-green-50 px-2 py-1 text-[9px] font-black text-green-700">10 modules live</span></div><div className="mt-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">{modules.slice(1).map((module) => { const Icon = module.icon; return <button key={module.id} onClick={() => onSelect(module.id)} className="flex items-center gap-3 rounded-xl border border-slate-100 p-4 text-left hover:border-blue-200 hover:bg-blue-50"><span className="grid h-9 w-9 place-items-center rounded-lg bg-slate-100 text-[#155ee9]"><Icon size={17} /></span><div className="min-w-0"><p className="text-xs font-black">{module.label}</p><p className="mt-0.5 truncate text-[9px] text-slate-400">{module.description}</p></div></button>; })}</div></section><section className="mt-5 grid gap-5 lg:grid-cols-2"><div className="rounded-2xl border border-slate-200 bg-white p-5"><h2 className="font-black">Latest audit activity</h2><div className="mt-4 space-y-3">{data.audits.length === 0 ? <Empty text="Actions will appear here." /> : data.audits.slice(0, 6).map((audit) => <div key={audit.id} className="flex items-center gap-3 border-b border-slate-100 pb-3 last:border-0"><span className="h-2 w-2 rounded-full bg-[#155ee9]" /><div className="flex-1"><p className="text-xs font-black">{audit.action.replaceAll(".", " ")}</p><p className="mt-0.5 text-[9px] text-slate-400">{audit.entity} #{audit.entityId || "system"}</p></div><p className="text-[9px] text-slate-400">{new Date(audit.createdAt).toLocaleDateString("en-IN")}</p></div>)}</div></div><div className="rounded-2xl bg-[#0b2756] p-6 text-white"><p className="text-[10px] font-black uppercase tracking-wider text-[#ffd54a]">Enterprise health</p><h2 className="mt-2 text-2xl font-black">Operations in one place.</h2><p className="mt-3 text-xs leading-6 text-blue-100">Customer verification, marketplace inventory, finance, content, relationships and notifications now share one PostgreSQL-backed operating system.</p><div className="mt-6 grid grid-cols-3 gap-2">{[[data.stats.lowStock, "Low stock"], [data.stats.receivables, "Receivable ₹"], [data.orders.length, "Orders"]].map(([value, label]) => <div key={label} className="rounded-xl bg-white/10 p-3"><p className="text-lg font-black">{String(value)}</p><p className="mt-1 text-[8px] text-blue-200">{label}</p></div>)}</div></div></section></>;
}

function UsersModule({ rows, query, setQuery, onStatus }: { rows: UserRow[]; query: string; setQuery: (value: string) => void; onStatus: (resource: "user", id: number, status: string) => void }) {
  const visible = useMemo(() => { const term = query.toLowerCase(); return rows.filter((row) => !term || row.name.toLowerCase().includes(term) || row.email.toLowerCase().includes(term) || row.role.includes(term)); }, [rows, query]);
  return <Panel title="Identity & access" subtitle="Customers, administrators, operators, sellers and delivery staff" action={<SearchBox value={query} onChange={setQuery} placeholder="Search users" />}><DataTable headers={["User", "Mobile", "Role", "Verification", "Status", "Joined"]}>{visible.map((user) => <tr key={user.id}><Cell><p className="font-black">{user.name}</p><p className="subcell">{user.email}</p></Cell><Cell>{user.phone}</Cell><Cell><Badge text={user.role} color={user.role === "admin" ? "violet" : user.role === "operator" ? "blue" : "slate"} /></Cell><Cell>{user.phoneVerified ? <span className="text-[10px] font-black text-green-600">✓ Voice verified</span> : <span className="text-[10px] font-bold text-orange-600">Pending</span>}</Cell><Cell><select value={user.status} onChange={(event) => onStatus("user", user.id, event.target.value)} className="mini-select"><option>active</option><option>suspended</option><option>disabled</option></select></Cell><Cell>{new Date(user.createdAt).toLocaleDateString("en-IN")}</Cell></tr>)}</DataTable>{visible.length === 0 && <Empty text="No users found. Add an operator or customer." />}</Panel>;
}

function VendorsModule({ vendors, products, onStatus }: { vendors: VendorRow[]; products: ProductRow[]; onStatus: (resource: "vendor", id: number, status: string) => void }) {
  return <div className="grid gap-5 xl:grid-cols-[1fr_0.36fr]"><Panel title="Marketplace vendors" subtitle="Company identity, GST and catalogue ownership"><DataTable headers={["Company", "Contact", "GSTIN", "Products", "Commission", "Status"]}>{vendors.map((vendor) => <tr key={vendor.id}><Cell><p className="font-black">{vendor.companyName}</p><p className="subcell">{vendor.email}</p></Cell><Cell><p>{vendor.contactName}</p><p className="subcell">{vendor.phone}</p></Cell><Cell>{vendor.gstin || "—"}</Cell><Cell>{products.filter((product) => product.seller === vendor.companyName).length}</Cell><Cell>{vendor.commissionRate}%</Cell><Cell><select value={vendor.status} onChange={(event) => onStatus("vendor", vendor.id, event.target.value)} className="mini-select"><option>active</option><option>pending</option><option>suspended</option></select></Cell></tr>)}</DataTable>{vendors.length === 0 && <Empty text="No vendors registered yet." />}</Panel><div className="space-y-4"><MetricBox label="Active vendors" value={vendors.filter((v) => v.status === "active").length} icon={Building2} /><MetricBox label="Vendor products" value={products.length} icon={ShoppingBag} /><MetricBox label="Awaiting approval" value={vendors.filter((v) => v.status === "pending").length} icon={PackageSearch} /></div></div>;
}

function BillingModule({ invoices, onStatus }: { invoices: InvoiceRow[]; onStatus: (resource: "invoice", id: number, status: string) => void }) {
  const collected = invoices.filter((i) => i.status === "paid").reduce((sum, i) => sum + Number(i.total), 0);
  return <><div className="mb-5 grid gap-4 sm:grid-cols-3"><MetricBox label="Total invoiced" value={formatPrice(invoices.reduce((sum, i) => sum + Number(i.total), 0))} icon={BadgeIndianRupee} /><MetricBox label="Collected" value={formatPrice(collected)} icon={Check} /><MetricBox label="Receivables" value={formatPrice(invoices.reduce((sum, i) => sum + (i.status === "paid" ? 0 : Number(i.total)), 0))} icon={WalletCards} /></div><Panel title="GST invoices" subtitle="Order-generated and manual billing records"><DataTable headers={["Invoice", "Customer", "Taxable", "GST", "Total", "Status", "Issued"]}>{invoices.map((invoice) => <tr key={invoice.id}><Cell><p className="font-black text-[#155ee9]">{invoice.invoiceNumber}</p></Cell><Cell>{invoice.customerName}</Cell><Cell>{formatPrice(Number(invoice.subtotal))}</Cell><Cell>{formatPrice(Number(invoice.taxAmount))}</Cell><Cell><p className="font-black">{formatPrice(Number(invoice.total))}</p></Cell><Cell><select value={invoice.status} onChange={(event) => onStatus("invoice", invoice.id, event.target.value)} className="mini-select"><option>issued</option><option>paid</option><option>overdue</option><option>cancelled</option></select></Cell><Cell>{new Date(invoice.createdAt).toLocaleDateString("en-IN")}</Cell></tr>)}</DataTable>{invoices.length === 0 && <Empty text="Invoices are generated automatically with verified orders." />}</Panel></>;
}

function TallyModule({ invoices }: { invoices: InvoiceRow[] }) {
  return <div className="grid gap-5 lg:grid-cols-[0.8fr_1.2fr]"><section className="rounded-3xl bg-[#0b2756] p-7 text-white"><span className="grid h-12 w-12 place-items-center rounded-2xl bg-[#ffd54a] text-[#0b2756]"><FileSpreadsheet size={23} /></span><p className="mt-6 text-xs font-black uppercase tracking-wider text-[#ffd54a]">Tally connector</p><h2 className="mt-2 text-3xl font-black tracking-tight">Accounting-ready exports.</h2><p className="mt-4 text-sm leading-6 text-blue-100">Move GST sales vouchers from Parsoni billing into Tally with clean XML or review them first in CSV.</p><div className="mt-7 space-y-3"><a href="/api/enterprise/tally?format=xml" className="flex items-center justify-center gap-2 rounded-xl bg-[#ffd54a] px-5 py-3.5 text-xs font-black text-[#0b2756]"><Download size={16} /> Download Tally XML</a><a href="/api/enterprise/tally?format=csv" className="flex items-center justify-center gap-2 rounded-xl border border-white/20 px-5 py-3.5 text-xs font-black"><Download size={16} /> Download invoice CSV</a></div></section><section className="rounded-3xl border border-slate-200 bg-white p-7"><div className="flex items-center justify-between"><div><h2 className="font-black">Export readiness</h2><p className="mt-1 text-[10px] text-slate-400">Current billing ledger summary</p></div><span className="rounded-full bg-green-50 px-2 py-1 text-[9px] font-black text-green-700">Ready</span></div><div className="mt-7 grid gap-3 sm:grid-cols-3">{[[invoices.length, "Vouchers"], [formatPrice(invoices.reduce((sum, i) => sum + Number(i.taxAmount), 0)), "Output GST"], [formatPrice(invoices.reduce((sum, i) => sum + Number(i.total), 0)), "Invoice value"]].map(([value, label]) => <div key={label} className="rounded-xl bg-slate-50 p-4"><p className="text-xl font-black">{String(value)}</p><p className="mt-1 text-[9px] font-bold text-slate-400">{label}</p></div>)}</div><div className="mt-7 rounded-xl border border-blue-100 bg-blue-50 p-4"><p className="text-xs font-black text-blue-900">Before importing into Tally</p><ol className="mt-3 list-inside list-decimal space-y-2 text-[10px] leading-5 text-blue-800"><li>Create ledgers named “Sales GST” and “Output GST”.</li><li>Back up the target Tally company.</li><li>Import the downloaded XML under Vouchers.</li><li>Review GST allocation and round-off settings.</li></ol></div></section></div>;
}

function CmsModule({ pages, onStatus }: { pages: PageRow[]; onStatus: (resource: "page", id: number, status: string) => void }) {
  return <Panel title="Content management" subtitle="Landing pages, policies and campaign content"><DataTable headers={["Page", "URL slug", "Status", "Last updated", "Publishing"]}>{pages.map((page) => <tr key={page.id}><Cell><p className="font-black">{page.title}</p></Cell><Cell><code className="rounded bg-slate-100 px-2 py-1 text-[9px]">/{page.slug}</code></Cell><Cell><Badge text={page.status} color={page.status === "published" ? "green" : "orange"} /></Cell><Cell>{new Date(page.updatedAt).toLocaleString("en-IN", { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" })}</Cell><Cell><select value={page.status} onChange={(event) => onStatus("page", page.id, event.target.value)} className="mini-select"><option>draft</option><option>published</option><option>archived</option></select></Cell></tr>)}</DataTable>{pages.length === 0 && <Empty text="Create the first CMS page or campaign landing page." />}</Panel>;
}

function ErpModule({ products, inventory }: { products: ProductRow[]; inventory: InventoryRow[] }) {
  return <div className="grid gap-5 xl:grid-cols-[1.15fr_0.85fr]"><Panel title="Inventory master" subtitle="Live stock by vendor product"><DataTable headers={["Product", "Seller", "Price", "Stock", "Approval"]}>{products.map((product) => <tr key={product.id}><Cell><p className="max-w-[240px] truncate font-black">{product.title}</p><p className="subcell">{product.sku || `PRS-${product.id}`}</p></Cell><Cell>{product.seller}</Cell><Cell>{formatPrice(Number(product.price))}</Cell><Cell><span className={`font-black ${product.stock < 10 ? "text-orange-600" : "text-slate-700"}`}>{product.stock}</span></Cell><Cell><Badge text={product.approvalStatus} color="green" /></Cell></tr>)}</DataTable>{products.length === 0 && <Empty text="Vendor products will appear here." />}</Panel><Panel title="Stock ledger" subtitle="Latest inventory movements"><div className="space-y-3">{inventory.length === 0 ? <Empty text="Stock movements will appear here." /> : inventory.slice(0, 12).map((movement) => { const product = products.find((item) => item.id === movement.productId); return <div key={movement.id} className="flex items-center gap-3 border-b border-slate-100 pb-3"><span className={`grid h-9 w-9 place-items-center rounded-xl ${movement.quantity > 0 ? "bg-green-50 text-green-600" : "bg-red-50 text-red-600"}`}><Boxes size={16} /></span><div className="min-w-0 flex-1"><p className="truncate text-xs font-black">{product?.title || `Product #${movement.productId}`}</p><p className="subcell">{movement.type.replaceAll("_", " ")} • {movement.reference || "manual"}</p></div><p className={`text-xs font-black ${movement.quantity > 0 ? "text-green-600" : "text-red-600"}`}>{movement.quantity > 0 ? "+" : ""}{movement.quantity}</p></div>; })}</div></Panel></div>;
}

function CrmModule({ contacts }: { contacts: CrmRow[] }) {
  const stages = ["lead", "qualified", "proposal", "customer"];
  return <div className="grid gap-4 xl:grid-cols-4">{stages.map((stage) => <section key={stage} className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm"><div className="flex items-center justify-between"><h2 className="text-xs font-black capitalize">{stage}</h2><span className="grid h-6 min-w-6 place-items-center rounded-full bg-slate-100 px-1 text-[9px] font-black">{contacts.filter((c) => c.stage === stage).length}</span></div><div className="mt-4 space-y-3">{contacts.filter((contact) => contact.stage === stage).map((contact) => <article key={contact.id} className="rounded-xl border border-slate-100 p-3 shadow-sm"><p className="text-xs font-black">{contact.name}</p><p className="mt-1 truncate text-[9px] text-slate-400">{contact.company || contact.email || contact.phone}</p><div className="mt-3 flex items-center justify-between"><span className="text-[9px] font-black text-green-600">{formatPrice(Number(contact.value))}</span><span className="text-[8px] text-slate-400">{new Date(contact.createdAt).toLocaleDateString("en-IN")}</span></div></article>)}{contacts.filter((c) => c.stage === stage).length === 0 && <p className="rounded-xl bg-slate-50 p-5 text-center text-[9px] text-slate-400">No contacts</p>}</div></section>)}</div>;
}

function NotificationsModule({ campaigns, deliveries }: { campaigns: CampaignRow[]; deliveries: Array<{ id: number; channel: string; status: string }> }) {
  return <><div className="mb-5 grid gap-4 sm:grid-cols-3"><MetricBox label="Campaigns" value={campaigns.length} icon={Megaphone} /><MetricBox label="Email deliveries" value={deliveries.filter((d) => d.channel === "email").length} icon={FileText} /><MetricBox label="Voice deliveries" value={deliveries.filter((d) => d.channel === "voice").length} icon={BellRing} /></div><Panel title="Notification campaigns" subtitle="Broadcast to all users or a role through email and phone voice"><DataTable headers={["Campaign", "Audience", "Channels", "Status", "Sent", "Failed", "Created"]}>{campaigns.map((campaign) => <tr key={campaign.id}><Cell><p className="font-black">{campaign.title}</p></Cell><Cell><Badge text={campaign.audience} color="slate" /></Cell><Cell><div className="flex gap-1">{campaign.channels.map((channel) => <Badge key={channel} text={channel} color={channel === "voice" ? "violet" : "blue"} />)}</div></Cell><Cell><Badge text={campaign.status} color={campaign.status === "sent" ? "green" : "orange"} /></Cell><Cell>{campaign.sentCount}</Cell><Cell>{campaign.failedCount}</Cell><Cell>{new Date(campaign.createdAt).toLocaleDateString("en-IN")}</Cell></tr>)}</DataTable>{campaigns.length === 0 && <Empty text="Create a campaign to notify users by email or voice call." />}</Panel><div className="mt-4 rounded-xl border border-blue-100 bg-blue-50 p-4 text-[10px] leading-5 text-blue-800"><strong>Channel status:</strong> Voice is available through Twilio credentials. Text SMS is intentionally disabled and can be added later. Email uses Resend; messages remain queued when provider credentials are not configured.</div></>;
}

function RecordModal({ resource, products, saving, error, onClose, onSubmit }: { resource: FormResource; products: ProductRow[]; saving: boolean; error: string; onClose: () => void; onSubmit: (event: FormEvent<HTMLFormElement>) => void }) {
  const titles: Record<FormResource, string> = { user: "Add user or operator", vendor: "Register vendor", invoice: "Create manual invoice", page: "Create CMS page", inventory: "Adjust inventory", crm: "Add CRM contact", notification: "New notification campaign" };
  return <div className="fixed inset-0 z-[70] grid place-items-center overflow-y-auto bg-[#071a3b]/60 p-4 backdrop-blur-sm"><button className="absolute inset-0" onClick={onClose} aria-label="Close" /><div className="relative my-6 w-full max-w-xl rounded-3xl bg-white shadow-2xl"><div className="flex items-center justify-between border-b border-slate-100 p-5"><div><p className="text-[9px] font-black uppercase tracking-wider text-[#155ee9]">Parsoni One</p><h2 className="mt-1 text-lg font-black">{titles[resource]}</h2></div><button onClick={onClose} className="grid h-9 w-9 place-items-center rounded-full bg-slate-100"><X size={17} /></button></div><form onSubmit={onSubmit} className="p-5"><div className="grid gap-4 sm:grid-cols-2">{resource === "user" && <><Field name="name" label="Full name *" required /><Field name="email" label="Email *" type="email" required /><Field name="phone" label="Mobile *" placeholder="+91 98765 43210" required /><SelectField name="role" label="Access role *" options={["operator", "admin", "customer", "seller", "delivery"]} /><Field name="password" label="Temporary password" type="password" placeholder="Optional" /></>}{resource === "vendor" && <><Field name="companyName" label="Company name *" required /><Field name="contactName" label="Contact person *" required /><Field name="email" label="Business email *" type="email" required /><Field name="phone" label="Mobile *" required /><Field name="gstin" label="GSTIN" /><Field name="commissionRate" label="Commission %" type="number" defaultValue="12" /></>}{resource === "invoice" && <><Field name="customerName" label="Customer / company *" required /><Field name="customerGstin" label="Customer GSTIN" /><Field name="total" label="Invoice total ₹ *" type="number" required /><Field name="taxRate" label="GST rate %" type="number" defaultValue="18" /><Field name="dueDate" label="Due date" type="date" /><SelectField name="status" label="Status" options={["issued", "paid", "overdue"]} /></>}{resource === "page" && <><Field name="title" label="Page title *" required /><Field name="slug" label="URL slug" placeholder="auto-generated-from-title" /><Field name="excerpt" label="Short excerpt" wide /><SelectField name="status" label="Publishing status" options={["draft", "published"]} /><label className="input-label sm:col-span-2">Page content *<textarea required name="body" rows={7} className="checkout-input resize-none" placeholder="Write page or campaign content…" /></label></>}{resource === "inventory" && <><label className="input-label sm:col-span-2">Product *<select required name="productId" className="checkout-input"><option value="">Select product</option>{products.map((product) => <option key={product.id} value={product.id}>{product.title} — stock {product.stock}</option>)}</select></label><Field name="quantity" label="Adjustment quantity *" type="number" placeholder="Use -5 or 20" required /><Field name="reference" label="Reference" placeholder="PO-2026-001" /><Field name="note" label="Adjustment note" wide /></>}{resource === "crm" && <><Field name="name" label="Contact name *" required /><Field name="company" label="Company" /><Field name="email" label="Email" type="email" /><Field name="phone" label="Phone" /><SelectField name="stage" label="Pipeline stage" options={["lead", "qualified", "proposal", "customer"]} /><Field name="value" label="Opportunity value ₹" type="number" defaultValue="0" /><Field name="nextFollowUp" label="Next follow-up" type="date" /><Field name="notes" label="Notes" wide /></>}{resource === "notification" && <><Field name="title" label="Campaign title *" required wide /><label className="input-label sm:col-span-2">Message *<textarea required name="message" rows={5} className="checkout-input resize-none" placeholder="Write the email and voice-call message…" /></label><SelectField name="audience" label="Audience" options={["all", "customer", "operator", "admin", "seller", "delivery"]} /><div className="input-label"><span>Channels *</span><div className="flex h-11 items-center gap-4 rounded-xl border border-slate-200 px-3"><label className="flex items-center gap-2 text-xs"><input type="checkbox" name="channels" value="email" defaultChecked className="accent-[#155ee9]" /> Email</label><label className="flex items-center gap-2 text-xs"><input type="checkbox" name="channels" value="voice" defaultChecked className="accent-[#155ee9]" /> Voice call</label></div></div><label className="sm:col-span-2 flex items-start gap-2 rounded-xl bg-blue-50 p-3 text-[10px] leading-4 text-blue-800"><input type="checkbox" name="sendNow" defaultChecked className="mt-0.5 accent-[#155ee9]" />Send immediately when providers are configured; otherwise keep all deliveries queued for operators.</label></>}</div>{error && <p className="mt-4 rounded-xl bg-red-50 p-3 text-xs font-bold text-red-600">{error}</p>}<div className="mt-6 flex justify-end gap-2"><button type="button" onClick={onClose} className="rounded-xl border border-slate-200 px-5 py-3 text-xs font-black">Cancel</button><button disabled={saving} className="flex items-center gap-2 rounded-xl bg-[#155ee9] px-5 py-3 text-xs font-black text-white disabled:opacity-60">{saving ? <LoaderCircle size={15} className="animate-spin" /> : <Check size={15} />} Save record</button></div></form></div></div>;
}

function Panel({ title, subtitle, action, children }: { title: string; subtitle: string; action?: React.ReactNode; children: React.ReactNode }) { return <section className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm"><div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-100 p-5"><div><h2 className="font-black">{title}</h2><p className="mt-1 text-[10px] text-slate-400">{subtitle}</p></div>{action}</div>{children}</section>; }
function DataTable({ headers, children }: { headers: string[]; children: React.ReactNode }) { return <div className="overflow-x-auto"><table className="w-full min-w-[720px] text-left"><thead><tr className="bg-slate-50 text-[9px] font-black uppercase tracking-wider text-slate-400">{headers.map((header) => <th key={header} className="px-5 py-3">{header}</th>)}</tr></thead><tbody className="divide-y divide-slate-100 text-xs">{children}</tbody></table></div>; }
function Cell({ children }: { children: React.ReactNode }) { return <td className="px-5 py-4">{children}</td>; }
function Badge({ text, color }: { text: string; color: "blue" | "violet" | "green" | "orange" | "slate" }) { const styles = { blue: "bg-blue-50 text-blue-700", violet: "bg-violet-50 text-violet-700", green: "bg-green-50 text-green-700", orange: "bg-orange-50 text-orange-700", slate: "bg-slate-100 text-slate-600" }; return <span className={`rounded-full px-2 py-1 text-[8px] font-black uppercase ${styles[color]}`}>{text}</span>; }
function Empty({ text }: { text: string }) { return <div className="p-10 text-center"><PackageSearch className="mx-auto text-slate-300" size={30} /><p className="mt-3 text-xs font-bold text-slate-400">{text}</p></div>; }
function SearchBox({ value, onChange, placeholder }: { value: string; onChange: (value: string) => void; placeholder: string }) { return <div className="relative"><Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" /><input value={value} onChange={(event) => onChange(event.target.value)} placeholder={placeholder} className="h-9 w-56 rounded-lg border border-slate-200 pl-9 pr-3 text-xs outline-none focus:border-blue-500" /></div>; }
function MetricBox({ label, value, icon: Icon }: { label: string; value: string | number; icon: React.ElementType }) { return <article className="flex items-center gap-3 rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"><span className="grid h-10 w-10 place-items-center rounded-xl bg-blue-50 text-[#155ee9]"><Icon size={18} /></span><div><p className="text-xl font-black">{value}</p><p className="mt-1 text-[9px] font-bold text-slate-400">{label}</p></div></article>; }
function Field({ name, label, type = "text", placeholder, required, wide, defaultValue }: { name: string; label: string; type?: string; placeholder?: string; required?: boolean; wide?: boolean; defaultValue?: string }) { return <label className={`input-label ${wide ? "sm:col-span-2" : ""}`}>{label}<input required={required} name={name} type={type} placeholder={placeholder} defaultValue={defaultValue} className="checkout-input" /></label>; }
function SelectField({ name, label, options }: { name: string; label: string; options: string[] }) { return <label className="input-label">{label}<select name={name} className="checkout-input">{options.map((option) => <option key={option} value={option}>{option.replaceAll("_", " ")}</option>)}</select></label>; }
