"use client";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import {
  CustomerHeader,
  DispenseChecklist,
  GoodsReceivedStepper,
  PoLinesEditor,
  PrescriptionCard,
  SupplierHeader,
  type PoLine,
} from "@/components/medora/records/parties";
import { CashCountForm, ShiftSummary, shiftExpectedCash, type ShiftSummaryData } from "@/components/medora/records/shift";
import { Button } from "@/components/ui/button";
import { batches, customers, prescriptions, products, suppliers, formatDate } from "@/lib/mock-data";

const customer = customers.find((c) => c.creditLimit > 0) ?? customers[1];
const supplier = suppliers[2];
const productName = (id: number) => products.find((p) => p.id === id)?.name ?? "Unknown product";
const rx = (i: number) => prescriptions[i];
const rxItems = (i: number) => rx(i).items.map((it) => ({ name: productName(it.productId), dose: it.dose, quantity: it.quantity }));

const poLines: PoLine[] = products
  .filter((p) => p.type === "Product" && p.supplierId === supplier.id)
  .slice(0, 3)
  .map((p, i) => ({ id: i + 1, product: p.name, quantity: 100 * (i + 1), unitCost: p.costPrice, received: i === 0 ? 100 : 0 }));

const dispenseItems = rx(2).items.map((it) => {
  const b = batches.filter((x) => x.productId === it.productId && x.stock > 0).sort((a, c) => a.expiryDate.localeCompare(c.expiryDate))[0];
  return { name: productName(it.productId), quantity: it.quantity, batch: b?.batchNo ?? "No batch", expiry: b ? formatDate(b.expiryDate, { short: true }) : "none" };
});

const closed: ShiftSummaryData = {
  cashier: "Kevin Mutua",
  branch: "Westlands Main",
  opened: "20 Oct 08:00",
  closed: "20 Oct 17:05",
  openingFloat: 5000,
  salesByTender: [
    { method: "Cash", amount: 38400 },
    { method: "M-Pesa", amount: 52150 },
    { method: "Card", amount: 14800 },
  ],
  cashRefunds: 450,
  countedCash: 42750,
};
const expectedClosed = shiftExpectedCash(closed);

export function RecordsSection() {
  return (
    <>
      <Section id="records" title="People and prescriptions" description="Headers that sit above a customer or supplier record, and the prescription workflow from receipt to sign-off.">
        <Example title="Customer header" description="On account, and walk-in with actions" className="space-y-3">
          <CustomerHeader
            name={customer.name}
            phone={customer.phone}
            email={customer.email}
            lastVisit={customer.lastVisit}
            visits={customer.visits}
            totalSpend={customer.totalSpend}
            onAccount
            actions={
              <>
                <Button variant="outline" size="sm">Statement</Button>
                <Button size="sm">Record payment</Button>
              </>
            }
          />
          <CustomerHeader name={customers[0].name} phone={customers[0].phone} email={customers[0].email} lastVisit={customers[0].lastVisit} visits={customers[0].visits} totalSpend={customers[0].totalSpend} />
        </Example>
        <Example title="Supplier header">
          <SupplierHeader
            name={supplier.name}
            contact={supplier.contact}
            phone={supplier.phone}
            town={supplier.town}
            leadDays={supplier.leadDays}
            actions={<Button size="sm">New purchase order</Button>}
          />
        </Example>
        <Example title="Prescription card" description="Pending, partially dispensed, dispensed, cancelled" className="grid gap-4 lg:grid-cols-2">
          <PrescriptionCard reference={rx(0).ref} patient={rx(0).patient} prescriber={rx(0).prescriber} facility={rx(0).facility} date={rx(0).date} items={rxItems(0)} status="Pending" actions={<Button size="sm">Verify</Button>} />
          <PrescriptionCard reference={rx(5).ref} patient={rx(5).patient} prescriber={rx(5).prescriber} facility={rx(5).facility} date={rx(5).date} items={rxItems(5)} status="Partially" />
          <PrescriptionCard reference={rx(2).ref} patient={rx(2).patient} prescriber={rx(2).prescriber} facility={rx(2).facility} date={rx(2).date} items={rxItems(2)} status="Dispensed" />
          <PrescriptionCard reference={rx(6).ref} patient={rx(6).patient} prescriber={rx(6).prescriber} facility={rx(6).facility} date={rx(6).date} items={rxItems(6)} status="Cancelled" />
        </Example>
        <Example title="Dispense checklist" description="Sign-off unlocks after items are verified and counselling is ticked; the second is disabled" className="grid gap-4 lg:grid-cols-2">
          <DispenseChecklist items={dispenseItems} />
          <DispenseChecklist items={dispenseItems} disabled />
        </Example>
      </Section>

    </>
  );
}

export function PurchasingSection() {
  return (
    <>
      <Section id="purchasing" title="Purchasing" description="Building a purchase order and booking the delivery against it.">
        <Example title="Purchase order lines editor" description="Draft (editable), receiving, read-only, empty" className="space-y-4">
          <PoLinesEditor initial={poLines} mode="draft" />
          <PoLinesEditor initial={poLines} mode="receiving" />
          <PoLinesEditor initial={poLines} mode="readonly" />
          <PoLinesEditor initial={[]} mode="draft" />
        </Example>
        <Example title="Goods received stepper" description="Draft, ordered, partly received, received, cancelled" className="grid gap-3 lg:grid-cols-2">
          <GoodsReceivedStepper stage="Draft" />
          <GoodsReceivedStepper stage="Ordered" />
          <GoodsReceivedStepper stage="Partly received" />
          <GoodsReceivedStepper stage="Received" />
          <GoodsReceivedStepper stage="Ordered" cancelled />
        </Example>
      </Section>

    </>
  );
}

export function ShiftsSection() {
  return (
    <>
      <Section id="shifts" title="Shifts and cash" description="The till reconciliation: what should be in the drawer, what was counted, and the difference.">
        <Example title="Shift summary / Z-report" description="Closed and balanced, short, open (not counted), loading" className="grid gap-4 lg:grid-cols-2">
          <ShiftSummary data={{ ...closed, countedCash: expectedClosed }} />
          <ShiftSummary data={closed} />
          <ShiftSummary data={{ ...closed, closed: undefined, countedCash: undefined }} />
          <ShiftSummary data={closed} loading />
        </Example>
        <Example title="Cash count form" description="Active, and disabled" className="grid gap-4 lg:grid-cols-2">
          <CashCountForm expected={expectedClosed} />
          <CashCountForm expected={expectedClosed} disabled />
        </Example>
      </Section>
    </>
  );
}
