"use client";

import { Fragment, useState } from "react";
import { ArchiveIcon, ChevronRightIcon, ClipboardListIcon, PencilIcon, PlusIcon, SearchIcon, SlidersHorizontalIcon } from "lucide-react";

import { RowActions } from "@/components/medora/row-actions";
import { Badge } from "@/components/ui/badge";
import { toast } from "@/components/ui/toast";
import { Button } from "@/components/ui/button";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { batches, expiring, formatDate, formatKES, lowStock, products, stockStatus } from "@/lib/mock-data";
import { Frame } from "./frame";

const stocked = products.filter((p) => p.type === "Product");
const categories = ["All categories", ...Array.from(new Set(stocked.map((p) => p.category)))];
const preview = (what: string) => () => toast.add({ title: what, description: "Design-system preview: no record changes." });

function Row({ id }: { id: number }) {
  const p = products.find((x) => x.id === id)!;
  const bs = batches.filter((b) => b.productId === id);
  const st = stockStatus(p);
  const [open, setOpen] = useState(false);
  // Rows live inside a <tbody>, so the expander is plain state + a Fragment rather than a Collapsible (Base UI would inject data-* props into the Fragment).
  return (
    <Fragment>
      <TableRow>
        <TableCell>
          <button type="button" onClick={() => setOpen((o) => !o)} aria-expanded={open} className="flex cursor-pointer items-center gap-1 outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label={`Batches of ${p.name}`}>
            <ChevronRightIcon className="size-4 transition-transform" style={{ transform: open ? "rotate(90deg)" : undefined }} />
            <span className="font-medium">{p.name}</span>
          </button>
          <div className="pl-5 text-xs text-muted-foreground">{p.generic} {p.strength}</div>
        </TableCell>
        <TableCell>{p.category}</TableCell>
        <TableCell className="text-right tabular-nums">{p.stock}</TableCell>
        <TableCell className="text-right tabular-nums">{formatKES(p.price, { decimals: true })}</TableCell>
        <TableCell><Badge variant={st === "In stock" ? "outline" : st === "Low stock" ? "secondary" : "destructive"}>{st}</Badge></TableCell>
        <TableCell className="py-1 text-right">
          <RowActions
            label={`${p.name} ${p.strength}`}
            actions={[
              { label: "View product", icon: ClipboardListIcon, href: `#product-${p.id}` },
              { label: "Adjust stock", icon: SlidersHorizontalIcon, onSelect: preview(`Adjust stock: ${p.name}`) },
              { label: "Edit product", icon: PencilIcon, onSelect: preview(`Edit ${p.name}`) },
              { label: "Archive", icon: ArchiveIcon, destructive: true, onSelect: preview(`Archive ${p.name}`) },
            ]}
          />
        </TableCell>
      </TableRow>
      {open && (
      <tr>
        <td colSpan={6} className="bg-muted/50 px-4 py-2">
          <table className="w-full text-xs">
            <thead><tr className="text-left text-muted-foreground"><th className="py-1 font-medium">Batch</th><th className="font-medium">Expiry</th><th className="text-right font-medium">Stock</th><th className="text-right font-medium">Cost</th></tr></thead>
            <tbody>
              {bs.map((b) => (
                <tr key={b.id} className="border-t border-border"><td className="py-1 font-mono">{b.batchNo}</td><td>{formatDate(b.expiryDate)}</td><td className="text-right tabular-nums">{b.stock}</td><td className="text-right tabular-nums">{formatKES(b.costPrice, { decimals: true })}</td></tr>
              ))}
            </tbody>
          </table>
        </td>
      </tr>
      )}
    </Fragment>
  );
}

export function InventoryListPattern() {
  const [tab, setTab] = useState("products");
  const [q, setQ] = useState("");
  const [cat, setCat] = useState(categories[0]);
  const [status, setStatus] = useState<string[]>([]);

  const base = tab === "low" ? lowStock : tab === "expiring" ? stocked.filter((p) => expiring.some((e) => e.productId === p.id)) : stocked;
  const rows = base
    .filter((p) => p.name.toLowerCase().includes(q.toLowerCase()))
    .filter((p) => cat === categories[0] || p.category === cat)
    .filter((p) => status.length === 0 || status.includes(stockStatus(p)))
    .slice(0, 14);

  return (
    <Frame className="flex flex-col bg-background">
      <div className="flex items-center justify-between border-b border-border px-4 py-3">
        <div>
          <h3 className="text-base font-semibold">Inventory</h3>
          <p className="text-xs text-muted-foreground">{stocked.length} products across all batches</p>
        </div>
        <Button size="sm"><PlusIcon data-icon="inline-start" />Add product</Button>
      </div>
      <div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-2">
        <InputGroup className="w-56"><InputGroupAddon><SearchIcon /></InputGroupAddon><InputGroupInput placeholder="Search products" value={q} onChange={(e) => setQ(e.target.value)} aria-label="Search products" /></InputGroup>
        <Select value={cat} onValueChange={(v) => v && setCat(v)}>
          <SelectTrigger size="sm" className="w-44"><SelectValue /></SelectTrigger>
          <SelectContent>{categories.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
        </Select>
        <ToggleGroup variant="outline" size="sm" value={status} onValueChange={(v) => setStatus(v as string[])} multiple spacing={0}>
          {["In stock", "Low stock", "Out of stock"].map((s) => <ToggleGroupItem key={s} value={s}>{s}</ToggleGroupItem>)}
        </ToggleGroup>
      </div>
      <Tabs value={tab} onValueChange={(v) => setTab(String(v))} className="flex-1 gap-0 overflow-hidden">
        <TabsList variant="line" className="w-full justify-start border-b border-border px-4">
          <TabsTrigger value="products" className="flex-none">Products <Badge variant="secondary">{stocked.length}</Badge></TabsTrigger>
          <TabsTrigger value="low" className="flex-none">Low stock <Badge variant="secondary">{lowStock.length}</Badge></TabsTrigger>
          <TabsTrigger value="expiring" className="flex-none">Expiring <Badge variant="secondary">{expiring.length}</Badge></TabsTrigger>
        </TabsList>
        <div className="flex-1 overflow-auto">
          <Table>
            <TableHeader>
              <TableRow><TableHead>Product</TableHead><TableHead>Category</TableHead><TableHead className="text-right">Stock</TableHead><TableHead className="text-right">Price</TableHead><TableHead>Status</TableHead><TableHead className="w-10"><span className="sr-only">Actions</span></TableHead></TableRow>
            </TableHeader>
            <TableBody>
              {rows.map((p) => <Row key={`${tab}-${p.id}`} id={p.id} />)}
              {rows.length === 0 ? <TableRow><TableCell colSpan={6} className="py-10 text-center text-muted-foreground">No products match these filters</TableCell></TableRow> : null}
            </TableBody>
          </Table>
        </div>
      </Tabs>
    </Frame>
  );
}
