"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { PrintButton } from "@/components/medora/print";
import { ConversionReport, InvoiceReport, MergeReport, PaymentRecords, ProductHistory, QuotationsList, ReconciliationReport, ShelfAllocationImport, StockAsAt, SupplierCreditNotes, SupplierPurchases, WasteReport, type Quote } from "@/components/medora/record-lists";
import type { Promo } from "@/components/medora/settings-ops";
import { closeProblems, CloseShiftForm, ZReport, type CloseCount, type ShiftFigures } from "@/components/medora/shift-close";
import { TillBasket, type BasketItem } from "@/components/medora/till-basket";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
import { TODAY } from "@/lib/mock-data";

/* ------------------------------------ Till basket (PS-02, PS-04, PS-07) ------------------------------------ */

const BASKET: BasketItem[] = [
  { id: 1, name: "Augmentin 625 mg, 14s", unit: "box", qty: 1, unitPrice: 1260, batch: "AUG-2311", expiry: "Mar 2028", shelf: "B2", cost: 1020, category: "Antibiotics", taxCode: "A", rx: true },
  { id: 2, name: "Panadol 500 mg", unit: "strip", qty: 2, unitPrice: 58, discount: 3, batch: "PN-30217", expiry: "Sep 2027", shelf: "A1", cost: 32, category: "Analgesics", taxCode: "A" },
  { id: 3, name: "Nivea Soft cream 200 ml", unit: "tube", qty: 1, unitPrice: 610, batch: "NV24-0912", expiry: "Mar 2028", shelf: "D3", cost: 455, category: "Dermatology", taxCode: "B" },
  { id: 4, name: "Vitamin C 1000 mg, 20s", unit: "tube", qty: 2, unitPrice: 450, batch: "VC-7781", expiry: "Jan 2027", shelf: "E1", cost: 300, category: "Vitamins", taxCode: "B" },
];

const PROMOS: Promo[] = [
  { name: "Skin care week, 10% off", kind: "Percent", value: 10, scope: "Category", target: "Dermatology", minBasket: 0, start: "2026-10-18", end: "2026-10-25", branches: ["Westlands Main", "Kilimani"], active: true },
  { name: "Spend 3,000, save 100", kind: "Fixed", value: 100, scope: "Basket", minBasket: 3000, start: "2026-10-01", end: "2026-10-31", branches: ["Westlands Main"], active: true },
  { name: "Vitamin Saturday", kind: "Percent", value: 15, scope: "Category", target: "Vitamins", minBasket: 0, start: "2026-10-25", end: "2026-10-25", branches: ["Westlands Main"], active: true },
];

export function TillBasketSection() {
  const [manager, setManager] = React.useState(true);
  return (
    <Section
      id="till-basket"
      title="Till basket with batches, promotions and margin"
      description="PS-02, PS-04 and PS-07. Every line shows the batch and expiry being sold, the unit and the shelf. Running promotions apply by themselves and are named on the bill; a promotion just out of reach says how much more to spend. Cost, margin and markup appear only for roles allowed to see them, behind a switch."
    >
      <Example title="Basket, Westlands Main" description="Skin care week takes 10% off the Nivea; the basket is KES 120 short of the 3,000 promotion; Vitamin Saturday is scheduled, so it doesn't apply today">
        <div className="mb-3 flex gap-2">
          <Button size="sm" variant={manager ? "secondary" : "ghost"} onClick={() => setManager(true)}>
            As a pharmacist (can see cost)
          </Button>
          <Button size="sm" variant={!manager ? "secondary" : "ghost"} onClick={() => setManager(false)}>
            As a cashier
          </Button>
        </div>
        <div className="max-w-md">
          <TillBasket key={String(manager)} items={BASKET} promos={PROMOS} branch="Westlands Main" today={TODAY} canSeeCost={manager} onSaveQuote={(q) => toast.add({ title: "QUO-2026-00119 saved", description: `${q.lines} lines, KES ${q.total.toLocaleString("en-US", { minimumFractionDigits: 2 })}, valid 14 days. No payment taken and no stock moved.` })} />
        </div>
      </Example>
    </Section>
  );
}

/* ------------------------------------ Close shift and Z-report (PS-20) ------------------------------------ */

const SHIFT: ShiftFigures = {
  shiftNo: "SH-2026-1042",
  till: "Till 1",
  branch: "Westlands Main",
  cashier: "Kevin Mutua",
  opened: "20 Oct 2026, 08:00",
  closed: "20 Oct 2026, 16:10",
  openingCash: 5000,
  openingMpesa: 12400,
  sales: { cash: 17260, mpesa: 38410, card: 7350, credit: 2000 },
  cashRefunds: 450,
  drops: { cash: 10000, mpesa: 30000 },
  transactions: 103,
  voids: 1,
  returns: 2,
};

export function CloseShiftSection() {
  const [c, setC] = React.useState<CloseCount>({ cash: "11,760", leftInDrawer: "5000", mpesa: "20810", card: "7350", note: "" });
  const [tried, setTried] = React.useState(false);
  const [closed, setClosed] = React.useState(false);
  const z = React.useRef<HTMLDivElement>(null);
  const p = closeProblems(c, SHIFT, 5000);
  const n = (s: string) => Number(s.replace(/,/g, ""));
  return (
    <Section
      id="close-shift"
      title="Close shift and Z-report"
      description="PS-20: every tender is counted against what the system expects: cash, M-Pesa and the card batch total. Cash left in the drawer becomes the next float; the rest is banked. Anything that doesn't balance needs a note, which prints on the Z-report for the supervisor."
    >
      <div className="grid gap-4 xl:grid-cols-[1fr_auto]">
        <Example title="Close Kevin Mutua's shift" description="Cash is KES 50 short: try closing without a note">
          <CloseShiftForm figures={SHIFT} count={c} onChange={setC} problems={p} show={tried} />
          <div className="mt-4 flex justify-end">
            <Button
              onClick={() => {
                setTried(true);
                if (!Object.keys(p).length) {
                  setClosed(true);
                  toast.add({ title: "Shift closed", description: "Z-report ready to print." });
                }
              }}
            >
              Close shift
            </Button>
          </div>
        </Example>
        <Example title="Z-report" description={closed ? "As closed" : "Preview from the figures entered"} className="space-y-3 bg-muted/40">
          <div className="flex justify-end">
            <PrintButton target={z} paper="receipt-80" label="Print Z-report" />
          </div>
          <ZReport ref={z} figures={SHIFT} count={{ cash: n(c.cash) || 0, leftInDrawer: n(c.leftInDrawer) || 0, mpesa: n(c.mpesa) || 0, card: n(c.card) || 0, note: c.note }} printedAt="20 Oct 2026, 16:12" />
        </Example>
      </div>
    </Section>
  );
}

/* ------------------------------------ Catalog: merges and history (IN-07, IN-08) ------------------------------------ */

export function ProductRecordsSection() {
  return (
    <Section id="product-records" title="Merge report and product history" description="IN-07 and IN-08: every merge is listed with what moved, and each product keeps its change history as old → new values, with who, where and when.">
      <div className="grid gap-4 xl:grid-cols-2">
        <Example title="Merge report" description="2026">
          <MergeReport
            rows={[
              { ref: "MRG-0012", date: "2026-10-14", merged: "Panadol 500mg (old code PAN-500)", kept: "Panadol 500 mg", stockMoved: 1700, batchesMoved: 0, salesMoved: 412, by: "Grace Wanjiru" },
              { ref: "MRG-0011", date: "2026-09-02", merged: "Amoxyl 500 capsules", kept: "Amoxil 500 mg, 21s", stockMoved: 36, batchesMoved: 2, salesMoved: 88, by: "Peter Kamau" },
            ]}
          />
        </Example>
        <Example title="History: Augmentin 625 mg, 14s" description="Newest first">
          <ProductHistory
            product="Augmentin 625 mg, 14s"
            entries={[
              { at: "20 Oct 2026, 10:12", who: "Grace Wanjiru", where: "Westlands Main", action: "Price changed", changes: [{ field: "Selling price", before: "KES 1,190.00", after: "KES 1,260.00" }, { field: "Minimum margin", before: "15%", after: "20%" }] },
              { at: "18 Oct 2026, 15:40", who: "Peter Kamau", where: "Westlands Main", action: "Shelf moved", changes: [{ field: "Shelf", before: "B1 Antibiotics", after: "B2 Antibiotics" }] },
            ]}
          />
        </Example>
      </div>
    </Section>
  );
}

/* ------------------------------------ Inventory lists (IN-05, IN-20, IN-21, RP-02) ------------------------------------ */

export function InventoryListsSection() {
  return (
    <Section id="inventory-lists" title="Shelf import, waste, conversions and stock as at a date" description="IN-05, IN-20, IN-21 and RP-02. Shelves are assigned in bulk from a CSV checked row by row before anything changes. The waste and conversion reports list what the forms recorded. The stock report rewinds today's stock to any date and values it at batch cost.">
      <Example title="Assign shelves from a CSV" description="Try the sample file: one shelf doesn't exist and one code is repeated">
        <ShelfAllocationImport
          products={[{ code: "ANT-0042", name: "Augmentin 625 mg, 14s" }, { code: "ANL-0007", name: "Panadol 500 mg" }, { code: "DER-0019", name: "Nivea Soft cream 200 ml" }, { code: "VIT-0003", name: "Vitamin C 1000 mg" }]}
          shelves={["A1", "B2", "D3", "E1"]}
          sample={"Item code,Shelf\nANT-0042,B2\nANL-0007,A1\nDER-0019,D4\nVIT-0003,E1\nANL-0007,A1\n"}
        />
      </Example>
      <Example title="Waste report" description="1–20 Oct 2026. Open a row for its items">
        <WasteReport
          rows={[
            { no: "WST-0042", date: "2026-10-16", branch: "Nyali", staff: "Ali Hassan", reason: "Expired", status: "Approved", approver: "Grace Wanjiru", items: [{ name: "Amoxil 500 mg, 21s", qty: 15, cost: 210 }] },
            { no: "WST-0044", date: "2026-10-19", branch: "Westlands Main", staff: "Peter Kamau", reason: "Damaged in store", status: "Approved", approver: "Grace Wanjiru", items: [{ name: "Calamine lotion 100 ml", qty: 3, cost: 160 }] },
            { no: "WST-0045", date: "2026-10-20", branch: "Westlands Main", staff: "Kevin Mutua", reason: "Expired", status: "Awaiting approval", items: [{ name: "Vitamin C 1000 mg, 20s", qty: 4, cost: 300 }] },
            { no: "WST-0043", date: "2026-10-17", branch: "Kilimani", staff: "Faith Njeri", reason: "Recalled by supplier", status: "Rejected", approver: "Grace Wanjiru", items: [{ name: "Metformin 500 mg, 100s", qty: 2, cost: 330 }] },
          ]}
        />
      </Example>
      <div className="grid gap-4 xl:grid-cols-2">
        <Example title="Conversion report" description="October 2026, grouped by the product broken down">
          <ConversionReport
            rows={[
              { no: "CNV-0081", date: "2026-10-19", parent: "Panadol 500 mg, box of 10 strips", child: "strips", parentQty: 4, childQty: 40, location: "Westlands Main, Dispensary", staff: "Kevin Mutua" },
              { no: "CNV-0077", date: "2026-10-08", parent: "Panadol 500 mg, box of 10 strips", child: "strips", parentQty: 6, childQty: 60, location: "Kilimani, Dispensary", staff: "Faith Njeri" },
              { no: "CNV-0079", date: "2026-10-12", parent: "Amoxil 500 mg, 100 capsules", child: "capsules", parentQty: 1, childQty: 100, location: "Westlands Main, Dispensary", staff: "Grace Wanjiru" },
            ]}
          />
        </Example>
        <Example title="Stock as at a date" description="Westlands Main. Pick 1 Oct to see it rewound; 1 Sep is before movement records began">
          <StockAsAt
            today={TODAY}
            recordsSince="2026-09-15"
            rows={[
              { product: "Panadol 500 mg", unit: "strips", current: 420, reorder: 80, cost: 32, price: 58, nextExpiry: "2027-09-30", movements: [{ date: "2026-10-18", qty: 120 }, { date: "2026-10-05", qty: -260 }, { date: "2026-10-12", qty: -180 }] },
              { product: "Nivea Soft cream 200 ml", unit: "tubes", current: 18, reorder: 6, cost: 455, price: 610, nextExpiry: "2028-03-31", movements: [{ date: "2026-10-18", qty: 18 }] },
              { product: "Calamine lotion 100 ml", unit: "bottles", current: 22, reorder: 6, cost: 160, price: 240, nextExpiry: "2026-12-31", movements: [{ date: "2026-10-18", qty: 12 }, { date: "2026-10-19", qty: -3 }] },
              { product: "Augmentin 625 mg, 14s", unit: "boxes", current: 37, reorder: 10, cost: 1020, price: 1260, nextExpiry: "2028-03-31", movements: [{ date: "2026-10-03", qty: -12 }, { date: "2026-10-20", qty: -3 }] },
            ]}
          />
        </Example>
      </div>
    </Section>
  );
}

/* ------------------------------------ Receivables and payables (AC-09, AC-11, AC-12, AC-15) ------------------------------------ */

export function AccountsListsSection() {
  const [quotes, setQuotes] = React.useState<Quote[]>([
    { no: "QUO-2026-00118", date: "2026-10-19", customer: "Nairobi West Clinic", total: 18420, validDays: 14, status: "Open" },
    { no: "QUO-2026-00112", date: "2026-10-02", customer: "Aga Khan Hospital", total: 31480, validDays: 14, status: "Converted", convertedTo: "INV-2026-00790" },
    { no: "QUO-2026-00109", date: "2026-09-28", customer: "Mary Wambui", total: 2140, validDays: 7, status: "Open" },
    { no: "QUO-2026-00104", date: "2026-09-20", customer: "John Otieno", total: 960, validDays: 7, status: "Cancelled", cancelReason: "Customer bought elsewhere" },
  ]);
  return (
    <Section
      id="accounts-lists"
      title="Invoices, payments, credit notes, reconciliations and quotations"
      description="AC-09, AC-11, AC-12 and AC-15. Receivable and payable reports as lists, with totals that follow the filters. Supplier payments show the running total paid to each supplier. Quotations expire by themselves after their validity."
    >
      <Example title="Invoice report" description="1 Sep to 20 Oct 2026. Switch between summary, by customer and itemised">
        <InvoiceReport
          today={TODAY}
          rows={[
            { no: "INV-2026-00783", date: "2026-10-01", dueDate: "2026-11-19", customer: "Aga Khan Hospital", paid: 2000, lines: [{ item: "Augmentin 625 mg, 14s", qty: 3, price: 1260, vat: 0 }, { item: "Gloves, box of 100", qty: 1, price: 1307.93, vat: 16 }] },
            { no: "INV-2026-00790", date: "2026-10-12", dueDate: "2026-11-11", customer: "Aga Khan Hospital", paid: 0, lines: [{ item: "Augmentin 625 mg, 14s", qty: 20, price: 1260, vat: 0 }, { item: "Glucometer strips, 50s", qty: 4, price: 1570, vat: 0 }] },
            { no: "INV-2026-00771", date: "2026-09-10", dueDate: "2026-10-10", customer: "Nairobi West Clinic", paid: 4000, lines: [{ item: "Metformin 500 mg, 100s", qty: 12, price: 450, vat: 0 }] },
          ]}
        />
      </Example>
      <div className="grid gap-4 xl:grid-cols-2">
        <Example title="Customer payments" description="October 2026">
          <PaymentRecords
            partyLabel="Customer"
            rows={[
              { ref: "CP-0061", date: "2026-10-18", party: "Aga Khan Hospital", method: "Bank transfer", reference: "EQ-77812", amount: 2000, appliedTo: "INV-2026-00783" },
              { ref: "CP-0058", date: "2026-10-09", party: "Nairobi West Clinic", method: "M-Pesa", reference: "SJ81K2M4QX", amount: 4000, appliedTo: "INV-2026-00771" },
              { ref: "CP-0055", date: "2026-10-03", party: "John Otieno", method: "Cash", amount: 1500, appliedTo: "Account balance" },
            ]}
          />
        </Example>
        <Example title="Supplier payments" description="September and October 2026, with what's been paid to each supplier so far">
          <PaymentRecords
            partyLabel="Supplier"
            cumulative
            rows={[
              { ref: "SP-0121", date: "2026-09-30", party: "Harleys Ltd", method: "Bank transfer", reference: "EQ-74410", amount: 80100, appliedTo: "Bills to 31 Aug" },
              { ref: "SP-0124", date: "2026-10-12", party: "Harleys Ltd", method: "Bank transfer", reference: "EQ-76022", amount: 4398.72, appliedTo: "BILL-2026-0184" },
              { ref: "SP-0127", date: "2026-10-19", party: "Harleys Ltd", method: "Bank transfer", reference: "EQ-77790", amount: 84500, appliedTo: "Bills to 30 Sep" },
              { ref: "SP-0125", date: "2026-10-15", party: "Dawa Ltd", method: "M-Pesa", reference: "SJ82P9W1RT", amount: 10000, appliedTo: "BILL-2026-0196" },
            ]}
          />
        </Example>
      </div>
      <div className="grid gap-4 xl:grid-cols-2">
        <Example title="Supplier credit notes" description="October 2026">
          <SupplierCreditNotes
            rows={[
              { no: "SCN-0031", supplierCn: "HL-CN-2207", date: "2026-10-20", supplier: "Harleys Ltd", bill: "BILL-2026-0201", returnRef: "SRN-0044", amount: 3166.8, reason: "6 Nivea tubes refused as damaged" },
              { no: "SCN-0029", supplierCn: "DCN-7781", date: "2026-10-13", supplier: "Dawa Ltd", bill: "BILL-2026-0196", returnRef: "SRN-0041", amount: 4200, reason: "Short-expiry Amoxil returned" },
            ]}
          />
        </Example>
        <Example title="Reconciliations" description="2026, all accounts">
          <ReconciliationReport
            rows={[
              { ref: "REC-0019", account: "1040 Equity Bank", endDate: "2026-09-30", statement: 512400, book: 512400, matched: 214, unmatched: 0, by: "Grace Wanjiru", closedOn: "2026-10-04" },
              { ref: "REC-0020", account: "1021 M-Pesa till 512330", endDate: "2026-09-30", statement: 86050, book: 86050, matched: 1840, unmatched: 0, by: "Grace Wanjiru" },
              { ref: "REC-0021", account: "1040 Equity Bank", endDate: "2026-10-15", statement: 497600, book: 498050, matched: 98, unmatched: 3, by: "Grace Wanjiru" },
            ]}
          />
        </Example>
      </div>
      <Example title="Quotations" description="As at 20 Oct 2026. QUO-2026-00109 has passed its 7 days, so it shows as expired">
        <QuotationsList
          rows={quotes}
          today={TODAY}
          onConvert={(no) => toast.add({ title: `Converting ${no}`, description: "Opens it as an invoice or a till sale, with prices checked against today's." })}
          onCancel={(no, reason) => {
            setQuotes((qs) => qs.map((q) => (q.no === no ? { ...q, status: "Cancelled", cancelReason: reason } : q)));
            toast.add({ title: `${no} cancelled` });
          }}
        />
      </Example>
    </Section>
  );
}

/* ------------------------------------ RP-10 Supplier purchases ------------------------------------ */

export function SupplierPurchasesSection() {
  return (
    <Section id="supplier-purchases" title="Purchases by supplier and by product" description="RP-10: what was bought, from whom, at what weighted average cost (value ÷ units, not an average of prices), with links to the GRNs behind each figure.">
      <Example title="Supplier purchases" description="1 Sep to 20 Oct 2026, goods received, before VAT">
        <SupplierPurchases
          onGrn={(g) => toast.add({ title: `Opens ${g}` })}
          rows={[
            { supplier: "Harleys Ltd", product: "Nivea Soft cream 200 ml", grn: "GRN-2026-0318", qty: 18, value: 8190 },
            { supplier: "Harleys Ltd", product: "Calamine lotion 100 ml", grn: "GRN-2026-0318", qty: 12, value: 1920 },
            { supplier: "Harleys Ltd", product: "Panadol 500 mg, strip", grn: "GRN-2026-0318", qty: 120, value: 3840 },
            { supplier: "Harleys Ltd", product: "Calamine lotion 100 ml", grn: "GRN-2026-0299", qty: 24, value: 3792 },
            { supplier: "Dawa Ltd", product: "Amoxil 500 mg, 21s", grn: "GRN-2026-0311", qty: 80, value: 16800 },
            { supplier: "Cosmos Ltd", product: "Metformin 500 mg, 100s", grn: "GRN-2026-0305", qty: 12, value: 3960 },
          ]}
        />
      </Example>
    </Section>
  );
}
