"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { MedoraPageHeader } from "@/components/medora/page-header";
import { AssetForm, assetProblems, CustomersList, EmployeesList, QuotationForm, quoteProblems, SchemesManager, SuppliersList, type AssetDraft, type CustomerListRow, type EmployeeListRow, type QuoteDraft, type Scheme } from "@/components/medora/registers";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
import { TODAY } from "@/lib/mock-data";

/* ------------------------------------ CU-02, SU-02, CU-09 (Catalog and customers) ------------------------------------ */

export function PartyRegistersSection() {
  // Import opens from the page header's More (page header spec); the list holds only the Export menu
  const [importing, setImporting] = React.useState<"customers" | "suppliers" | null>(null);
  const [customers, setCustomers] = React.useState<CustomerListRow[]>([
    { id: 7, name: "Aga Khan Hospital", kind: "Company", group: "Corporate", phone: "0720 100 200", balance: 36777.2, creditLimit: 100000, lastVisit: "19 Oct" },
    { id: 12, name: "Nairobi West Clinic", kind: "Company", group: "Corporate", phone: "0733 400 500", balance: 1400, creditLimit: 20000, lastVisit: "18 Oct" },
    { id: 2, name: "Mary Wambui", kind: "Individual", group: "Loyalty", phone: "0712 345 678", balance: 0, creditLimit: 0, lastVisit: "20 Oct" },
    { id: 5, name: "John Otieno", kind: "Individual", phone: "0722 111 222", balance: 1500, creditLimit: 5000, lastVisit: "18 Oct" },
    { id: 9, name: "Ali Hassan", kind: "Individual", group: "Senior", phone: "0733 000 111", balance: 0, creditLimit: 0, lastVisit: "17 Oct" },
  ]);
  const [schemes, setSchemes] = React.useState<Scheme[]>([
    { id: "aar", name: "AAR Insurance, Outpatient Gold", kind: "Insurance", copayPct: "10", defaultLimit: "60000", claimWithinDays: "30", active: true, members: 214 },
    { id: "jub", name: "Jubilee Health, Family Silver", kind: "Insurance", copayPct: "20", defaultLimit: "20000", claimWithinDays: "30", active: true, members: 96 },
    { id: "nhif", name: "SHA Outpatient", kind: "Medical scheme", copayPct: "0", defaultLimit: "", claimWithinDays: "14", active: true, members: 488 },
    { id: "akh", name: "Aga Khan staff scheme", kind: "Corporate", copayPct: "120", defaultLimit: "30000", claimWithinDays: "45", active: true, members: 0 },
  ]);
  return (
    <Section id="registers" title="Customers, suppliers and schemes" description="CU-02, SU-02 and CU-09. Lists show key columns only and open the full record; both import from a CSV checked row by row, and export what the filters show. Schemes set the co-pay, default cover and claim deadline used at the till and in claims.">
      <Example title="Customers" description="Filter by group; a balance over its limit is flagged. Import checks phone numbers against existing customers">
        <MedoraPageHeader title="Customers" more={[{ label: "Import from CSV", onSelect: () => setImporting("customers") }]} />
        <CustomersList
          rows={customers}
          importOpen={importing === "customers"}
          onImportOpenChange={(o) => setImporting(o ? "customers" : null)}
          groups={["Corporate", "Loyalty", "Senior", "Staff"]}
          onOpen={(id) => toast.add({ title: "Opens the customer's page", description: `Profile, purchase history and statement (customer ${id}).` })}
          onImport={(rows) => {
            setCustomers((xs) => [...xs, ...rows.map((r, i) => ({ id: 100 + xs.length + i, name: r.name, kind: "Individual" as const, group: r.group || undefined, phone: r.phone, balance: 0, creditLimit: 0, lastVisit: "–" }))]);
            toast.add({ title: `${rows.length} customers added` });
          }}
        />
      </Example>
      <Example title="Suppliers" description="We owe figures match the supplier bills; Statement opens it in Accounts">
        <MedoraPageHeader title="Suppliers" more={[{ label: "Import from CSV", onSelect: () => setImporting("suppliers") }]} />
        <SuppliersList
          importOpen={importing === "suppliers"}
          onImportOpenChange={(o) => setImporting(o ? "suppliers" : null)}
          rows={[
            { id: 1, name: "Harleys Ltd", kraPin: "P051234567K", contact: "Wanjiku Mwangi", phone: "020 444 5000", owed: 18734.4, termsDays: 30, overdue: 0 },
            { id: 2, name: "Dawa Ltd", kraPin: "P051987654Z", contact: "Samuel Kiprono", phone: "0722 909 100", owed: 6800, termsDays: 30, overdue: 0 },
            { id: 3, name: "Cosmos Ltd", kraPin: "P052223334Q", contact: "Asha Noor", phone: "0711 222 333", owed: 3960, termsDays: 14, overdue: 3960 },
            { id: 4, name: "Surgipharm", kraPin: "P053334445R", contact: "Daniel Ouma", phone: "0700 444 555", owed: 0, termsDays: 45, overdue: 0 },
          ]}
          onOpen={(id) => toast.add({ title: "Opens the supplier's record", description: `Supplier ${id}` })}
          onStatement={(id) => toast.add({ title: "Opens the statement in Accounts", description: `Supplier ${id}` })}
          onImport={(rows) => toast.add({ title: `${rows.length} suppliers added` })}
        />
      </Example>
      <Example title="Insurance and medical schemes" description="The Aga Khan staff scheme's co-pay is over 100%: fix it. Schemes with members can only be deactivated">
        <SchemesManager schemes={schemes} onChange={setSchemes} />
      </Example>
    </Section>
  );
}

/* ------------------------------------ HR-01 ------------------------------------ */

export function EmployeesListSection() {
  const [importing, setImporting] = React.useState(false);
  const [rows, setRows] = React.useState<EmployeeListRow[]>([
    { id: "e1", number: "EMP-001", name: "Grace Wanjiru", role: "Pharmacist", type: "Permanent", branch: "Westlands Main", pay: "Monthly, Equity Bank", active: true },
    { id: "e3", number: "EMP-002", name: "Peter Kamau", role: "Branch admin", type: "Permanent", branch: "Westlands Main", pay: "Monthly, KCB", active: true },
    { id: "e2", number: "EMP-004", name: "Kevin Mutua", role: "Cashier", type: "Contract", branch: "Westlands Main", pay: "Monthly, M-Pesa", active: true },
    { id: "e4", number: "EMP-007", name: "Faith Njeri", role: "Pharm tech", type: "Permanent", branch: "Kilimani", pay: "Monthly, Equity Bank", active: true },
    { id: "e5", number: "EMP-009", name: "Musa Kariuki", role: "Rider", type: "Casual", branch: "Kilimani", pay: "Daily rate, M-Pesa", active: true },
    { id: "e6", number: "EMP-003", name: "John Kamau", role: "Cashier", type: "Contract", branch: "Nyali", pay: "Monthly, M-Pesa", active: false },
  ]);
  return (
    <Section id="employees" title="Employees" description="HR-01: search, filter by branch, type and status, import from CSV and export. Employees are deactivated, never deleted, so past payslips and P9s keep their name.">
      <Example title="Employees" description="John Kamau is deactivated; filter to Active, or reactivate him">
        <MedoraPageHeader title="Employees" more={[{ label: "Import from CSV", onSelect: () => setImporting(true) }]} />
        <EmployeesList
          rows={rows}
          importOpen={importing}
          onImportOpenChange={setImporting}
          onOpen={(id) => toast.add({ title: "Opens the employee record", description: `Personal, employment and pay tabs (${id}).` })}
          onToggleActive={(id) => {
            const r = rows.find((x) => x.id === id);
            setRows((xs) => xs.map((x) => (x.id === id ? { ...x, active: !x.active } : x)));
            toast.add({ title: r?.active ? `${r.name} deactivated` : `${r?.name} reactivated`, description: r?.active ? "Left out of future payroll runs; history kept." : "Included in the next payroll run." });
          }}
          onImport={(xs) => toast.add({ title: `${xs.length} employees added` })}
        />
      </Example>
    </Section>
  );
}

/* ------------------------------------ AC-15, AC-18 ------------------------------------ */

export function QuoteAssetSection() {
  const [q, setQ] = React.useState<QuoteDraft>({
    customer: "Nairobi West Clinic",
    date: TODAY,
    validDays: "14",
    note: "",
    lines: [
      { id: 1, product: "Gloves, box of 100", qty: "10", price: "1307.93", vat: 16 },
      { id: 2, product: "Metformin 500 mg, 100s", qty: "12", price: "450", vat: 0 },
      { id: 3, product: "", qty: "1", price: "", vat: 0 },
    ],
  });
  const [qTried, setQTried] = React.useState(false);
  const qp = quoteProblems(q);
  const [a, setA] = React.useState<AssetDraft>({ code: "AST-0042", name: "Pharmacy fridge, 2-door", category: "Equipment", location: "Westlands Main, Dispensary", qty: "1", model: "Haier HYC-610", serial: "HY61-220931", bought: "2026-10-02", price: "185000", purchaseType: "Bought outright", ratePct: "12.5" });
  const [aTried, setATried] = React.useState(false);
  const ap = assetProblems(a, ["AST-0041", "AST-0042"], TODAY);
  return (
    <Section id="quote-asset" title="New quotation and new asset" description="AC-15 and AC-18. A quotation raised in Accounts (the till can also save one) takes no payment and reserves no stock. The asset form records everything the register needs, and shows what depreciation will post each month.">
      <Example title="New quotation" description="Known items fill in their price and VAT; the third line is empty: try Save">
        <QuotationForm d={q} onChange={setQ} customers={["Aga Khan Hospital", "Nairobi West Clinic", "Mary Wambui"]} prices={{ "Gloves, box of 100": { price: 1307.93, vat: 16 }, "Metformin 500 mg, 100s": { price: 450, vat: 0 }, "Augmentin 625 mg, 14s": { price: 1260, vat: 0 } }} />
        {qTried && qp.length ? (
          <ul role="alert" className="mt-3 list-disc pl-5 text-sm text-status-error-text">
            {qp.map((x) => (
              <li key={x}>{x}</li>
            ))}
          </ul>
        ) : null}
        <div className="mt-3 flex justify-end">
          <Button onClick={() => (setQTried(true), !qp.length && toast.add({ title: "QUO-2026-00120 saved", description: `Valid ${q.validDays} days. Send it, or convert it when the customer accepts.` }))}>Save quotation</Button>
        </div>
      </Example>
      <Example title="New asset" description="AST-0042 is already taken: try Save, then change the code">
        <AssetForm a={a} onChange={setA} categories={[{ name: "Equipment", rate: 12.5 }, { name: "Computers", rate: 30 }, { name: "Furniture", rate: 10 }, { name: "Vehicles", rate: 25 }]} locations={["Westlands Main, Dispensary", "Westlands Main, Store room", "Kilimani, Dispensary"]} problems={ap} show={aTried} />
        <div className="mt-3 flex justify-end">
          <Button onClick={() => (setATried(true), !Object.keys(ap).length && toast.add({ title: `${a.code} added to the asset register` }))}>Save asset</Button>
        </div>
      </Example>
    </Section>
  );
}
