"use client";

import * as React from "react";
import { ArrowLeftRightIcon } from "lucide-react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { BranchStockMatrix, branchQty, cellStatus, InventoryLog, QtyCell, type Movement, type StockBranch, type StockRow } from "@/components/medora/branch-stock";
import { DescriptionList } from "@/components/medora/description-list";
import { RecordDrawer } from "@/components/medora/drawer";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { branches, formatDate, products, TODAY } from "@/lib/mock-data";

const LOCS = ["Dispensary", "Store room", "Front shop"];
const BRANCHES: StockBranch[] = branches.map((b) => ({ id: b.id, name: b.name, locations: LOCS.slice(0, b.id === 4 ? 2 : 3).map((n) => ({ id: `${b.id}-${n}`, name: n })) }));

/** Deterministic spread of each product's stock over branches and locations, with a few gaps and one negative. */
const ROWS: StockRow[] = products
  .filter((p) => p.type === "Product")
  .slice(0, 14)
  .map((p, i) => {
    const qty: Record<string, number> = {};
    BRANCHES.forEach((b, bi) => {
      const share = [0.45, 0.25, 0.2, 0.1][bi];
      const branchTotal = (i + bi) % 7 === 3 ? 0 : Math.round(p.stock * share * (1 + ((i * 3 + bi) % 4) / 4));
      b.locations.forEach((l, li) => {
        const part = [0.5, 0.35, 0.15][li] ?? 0;
        qty[l.id] = Math.round(branchTotal * (b.locations.length === 2 ? [0.6, 0.4][li] : part));
      });
    });
    if (i === 4) qty["3-Front shop"] = -4; // sold at Nyali before the delivery was received
    return { productId: p.id, name: p.name, sub: `${p.strength} · ${p.form}`, category: p.category, subCategory: i % 3 === 0 ? "Generic" : "Branded", brand: ["GSK", "Cosmos", "Dawa Ltd", "Beiersdorf"][i % 4], unitCost: p.costPrice, unitPrice: p.price, reorderLevel: Math.round(p.minStock / 3), qty };
  });

const MOVES: Movement[] = [
  { id: "m1", at: `${TODAY}T14:32`, product: "Panadol 500 mg", action: "Sale", change: -20, newQty: 180, branch: "Westlands Main", location: "Front shop", user: "Kevin Mutua", reference: "SALE-005200" },
  { id: "m2", at: `${TODAY}T13:05`, product: "Panadol 500 mg", action: "Transfer in", change: 100, newQty: 200, branch: "Westlands Main", location: "Store room", user: "Grace Wanjiru", reference: "TRF-2026-0042" },
  { id: "m3", at: `${TODAY}T13:05`, product: "Panadol 500 mg", action: "Transfer out", change: -100, newQty: 320, branch: "Kilimani", location: "Store room", user: "Peter Kamau", reference: "TRF-2026-0042" },
  { id: "m4", at: `${TODAY}T11:40`, product: "Amoxil 500 mg", action: "Issue", change: -21, newQty: 99, branch: "Westlands Main", location: "Dispensary", user: "Grace Wanjiru", reference: "ISS-2026-0011" },
  { id: "m5", at: `${TODAY}T10:12`, product: "Augmentin 625 mg", action: "Waste", change: -12, newQty: 36, branch: "Westlands Main", location: "Store room", user: "Peter Kamau", reference: "WST-2026-0007" },
  { id: "m6", at: `${TODAY}T09:01`, product: "Panadol 500 mg", action: "Received", change: 300, newQty: 300, branch: "Westlands Main", location: "Store room", user: "Grace Wanjiru", reference: "GRN-2026-0187" },
  { id: "m7", at: "2026-10-19T18:20", product: "Brufen 400 mg", action: "Stocktake", change: -3, newQty: 117, branch: "Westlands Main", location: "Dispensary", user: "Faith Njeri", reference: "STK-2026-0004" },
  { id: "m8", at: "2026-10-19T16:02", product: "Brufen 400 mg", action: "Return", change: 1, newQty: 120, branch: "Westlands Main", location: "Front shop", user: "Kevin Mutua", reference: "CN-2026-0091" },
  { id: "m9", at: "2026-10-19T12:45", product: "Panadol 500 mg", action: "Conversion", change: 100, newQty: 400, branch: "Nyali", location: "Dispensary", user: "Ali Hassan", reference: "CNV-2026-0003" },
  { id: "m10", at: "2026-10-18T15:30", product: "Brufen 400 mg", action: "Adjustment", change: 6, newQty: 120, branch: "Kilimani", location: "Front shop", user: "Peter Kamau", reference: "ADJ-2026-0019" },
];

const formatAt = (iso: string) => `${formatDate(iso.slice(0, 10), { short: true })}, ${iso.slice(11, 16)}`;

function CellDrawer({ open, onClose, row, branch }: { open: boolean; onClose: () => void; row?: StockRow; branch?: StockBranch }) {
  if (!row || !branch) return null;
  const here = branchQty(row, branch);
  const others = BRANCHES.filter((b) => b.id !== branch.id)
    .map((b) => ({ b, q: branchQty(row, b) }))
    .sort((a, z) => z.q - a.q);
  // Spare stock at another branch: what it holds above its own reorder level.
  const donor = others.find((o) => o.q - row.reorderLevel > 0);
  const spare = donor ? donor.q - row.reorderLevel : 0;
  const short = cellStatus(here, row.reorderLevel) !== "ok";
  return (
    <RecordDrawer open={open} onOpenChange={(o) => !o && onClose()} title={`${row.name} at ${branch.name}`} subtitle={`${row.sub} · reorder level ${row.reorderLevel} per branch`}>
      <div className="space-y-5">
        <section className="space-y-2">
          <h3 className="text-sm font-semibold">By location</h3>
          <DescriptionList
            variant="summary"
            density="compact"
            items={[...branch.locations.map((l) => ({ label: l.name, value: <QtyCell q={row.qty[l.id] ?? 0} status={(row.qty[l.id] ?? 0) < 0 ? "negative" : "ok"} /> })), { label: `${branch.name} total`, value: <QtyCell q={here} status={cellStatus(here, row.reorderLevel)} strong /> }]}
          />
        </section>
        <section className="space-y-2">
          <h3 className="text-sm font-semibold">Other branches</h3>
          <ul className="divide-y divide-[var(--color-border-subtle)] rounded-lg border border-[var(--color-border-panel)] text-sm">
            {others.map(({ b, q }) => (
              <li key={b.id} className="flex items-center justify-between px-3 py-2">
                {b.name}
                <QtyCell q={q} status={cellStatus(q, row.reorderLevel)} />
              </li>
            ))}
          </ul>
          {short && donor ? (
            <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-[var(--color-border-panel)] px-3 py-2 text-sm">
              <p>
                {donor.b.name} can spare up to <span className="font-semibold tabular-nums">{spare.toLocaleString("en-US")}</span> and stay above its reorder level.
              </p>
              <Button size="sm" variant="outline" onClick={() => toast.add({ title: "Transfer started", description: `${row.name} from ${donor.b.name} to ${branch.name}. (Branch transfer is the next component.)` })}>
                <ArrowLeftRightIcon data-icon="inline-start" />
                Request transfer
              </Button>
            </div>
          ) : short ? (
            <p className="text-sm text-muted-foreground">No other branch has stock to spare. Add it to a purchase order.</p>
          ) : null}
        </section>
        <section className="space-y-2">
          <h3 className="text-sm font-semibold">Value here</h3>
          <DescriptionList
            variant="inline"
            density="compact"
            items={[
              { label: "At cost (from batches)", value: `KES ${(Math.max(0, here) * row.unitCost).toLocaleString("en-US", { minimumFractionDigits: 2 })}`, money: true },
              { label: "At selling price", value: `KES ${(Math.max(0, here) * row.unitPrice).toLocaleString("en-US", { minimumFractionDigits: 2 })}`, money: true },
            ]}
          />
        </section>
      </div>
    </RecordDrawer>
  );
}

export function BranchStockSection() {
  const [scope, setScope] = React.useState<"all" | "branch">("all");
  const [cell, setCell] = React.useState<{ row: StockRow; branch: StockBranch } | null>(null);
  return (
    <Section
      id="branch-stock"
      title="Stock by branch and location"
      description="Stock lives at a location inside a branch. Products down, branches across; Show locations splits each branch into Dispensary, Store room and Front shop. Low, Out and Negative are words beside the number, judged against each branch's reorder level. The totals follow the filters and value stock at batch cost. A user without All branches sees only their branch, already split by location. Open a cell to see its locations and which branch could spare stock."
    >
      <Example title="Branch stock" description="Try Show locations, the Zero or negative filter, and opening a Low or Out cell" bare>
        <div className="flex flex-wrap items-center gap-3 border-b border-border px-4 py-3 text-sm">
          <span className="text-muted-foreground">Viewing as</span>
          <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Viewing as" value={[scope]} onValueChange={(v: string[]) => v[0] && setScope(v[0] as "all" | "branch")}>
            <ToggleGroupItem value="all">Admin, all branches</ToggleGroupItem>
            <ToggleGroupItem value="branch">Pharmacist, Westlands Main</ToggleGroupItem>
          </ToggleGroup>
        </div>
        <div className="p-4">
          <BranchStockMatrix key={scope} caption="Stock by branch" rows={ROWS} branches={BRANCHES} scopeBranchId={scope === "branch" ? 1 : undefined} onOpenCell={(row, branch) => setCell({ row, branch })} />
        </div>
        <CellDrawer open={!!cell} onClose={() => setCell(null)} row={cell?.row} branch={cell?.branch} />
      </Example>
      <Example title="Inventory log" description="Every movement, with the document behind it. A transfer shows twice: out of one branch and into the other" bare>
        <div className="p-4">
          <InventoryLog movements={MOVES} formatAt={formatAt} />
        </div>
      </Example>
    </Section>
  );
}
