"use client";

import { useState } from "react";
import { MinusIcon, PlusIcon, SearchIcon, Trash2Icon } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-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 { batches, customers, daysBetween, formatKES, products, TODAY } from "@/lib/mock-data";
import { PosBar, type PosShift } from "@/components/medora/pos-bar";
import { Frame } from "./frame";

const cats = ["All", "Analgesics", "Antibiotics", "Respiratory", "Vitamins", "Consumables"];

function nearestExpiry(id: number) {
  const bs = batches.filter((b) => b.productId === id && b.stock > 0).sort((a, b) => a.expiryDate.localeCompare(b.expiryDate));
  return bs[0] ? daysBetween(TODAY, bs[0].expiryDate) : null;
}

export function PosTillPattern() {
  const [cat, setCat] = useState("All");
  const [q, setQ] = useState("");
  const [cart, setCart] = useState<Record<number, number>>({ 1: 2, 5: 1, 21: 3 });
  const [pay, setPay] = useState("M-Pesa");
  const [shift] = useState<PosShift>(() => ({ status: "open", openedAt: new Date(Date.now() - 135 * 60_000), float: 5000 }));

  const list = products.filter((p) => (cat === "All" || p.category === cat) && p.name.toLowerCase().includes(q.toLowerCase())).slice(0, 12);
  const lines = Object.entries(cart).map(([id, qty]) => ({ p: products.find((x) => x.id === Number(id))!, qty }));
  const subtotal = lines.reduce((s, l) => s + l.p.price * l.qty, 0);
  const vat = Math.round(subtotal * 0.16 * 100) / 100;
  const total = subtotal + vat;
  const setQty = (id: number, d: number) =>
    setCart((c) => {
      const n = (c[id] ?? 0) + d;
      const { [id]: _drop, ...rest } = c;
      void _drop;
      return n > 0 ? { ...rest, [id]: n } : rest;
    });

  return (
    <Frame className="flex flex-col">
      <PosBar till="Till 1" branch="Westlands Main, Nairobi" cashier={{ name: "Kevin Mutua", role: "Cashier" }} shift={shift} held={2} />
      <div className="grid min-h-0 flex-1 grid-cols-[1fr_380px]">
      <div className="flex min-w-0 flex-col border-r border-border bg-muted/40">
        <div className="space-y-2 border-b border-border bg-background p-3">
          <InputGroup><InputGroupAddon><SearchIcon /></InputGroupAddon><InputGroupInput placeholder="Search name or scan barcode" value={q} onChange={(e) => setQ(e.target.value)} aria-label="Search products" /></InputGroup>
          <Tabs value={cat} onValueChange={(v) => setCat(String(v))}>
            <TabsList variant="line" className="w-full justify-start overflow-x-auto">
              {cats.map((c) => <TabsTrigger key={c} value={c} className="flex-none">{c}</TabsTrigger>)}
            </TabsList>
          </Tabs>
        </div>
        <div className="grid flex-1 grid-cols-2 content-start gap-2 overflow-auto p-3 sm:grid-cols-3">
          {list.map((p) => {
            const exp = nearestExpiry(p.id);
            const svc = p.type === "Service";
            return (
              <button key={p.id} type="button" onClick={() => setQty(p.id, 1)} className="flex cursor-pointer flex-col gap-1 rounded-lg border border-border bg-card p-3 text-left outline-none hover:border-primary focus-visible:ring-2 focus-visible:ring-ring">
                <span className="text-sm font-medium">{p.name}</span>
                <span className="text-xs text-muted-foreground">{p.strength}</span>
                <span className="mt-1 text-sm font-semibold tabular-nums">{formatKES(p.price, { decimals: true })}</span>
                <span className="flex flex-wrap gap-1">
                  {svc ? <Badge variant="secondary">SERVICE</Badge> : <Badge variant={p.stock === 0 ? "destructive" : "outline"}>{p.stock === 0 ? "Out" : `${p.stock} in stock`}</Badge>}
                  {exp !== null && exp <= 90 ? <Badge variant="destructive">{exp < 0 ? "Expired" : `Exp ${exp} d`}</Badge> : null}
                  {p.requiresRx ? <Badge variant="outline">Rx</Badge> : null}
                </span>
              </button>
            );
          })}
        </div>
      </div>
      <div className="flex min-h-0 flex-col bg-background">
        <div className="border-b border-border p-3">
          <Select defaultValue="walk-in">
            <SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="walk-in">Walk-in customer</SelectItem>
              {customers.slice(0, 5).map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.name}</SelectItem>)}
            </SelectContent>
          </Select>
        </div>
        <div className="flex-1 overflow-auto">
          <Table>
            <TableHeader>
              <TableRow><TableHead>Item</TableHead><TableHead className="text-center">Qty</TableHead><TableHead className="text-right">Total</TableHead><TableHead className="w-8" /></TableRow>
            </TableHeader>
            <TableBody>
              {lines.map(({ p, qty }) => (
                <TableRow key={p.id}>
                  <TableCell className="whitespace-normal"><div className="font-medium">{p.name}</div><div className="text-xs text-muted-foreground tabular-nums">{formatKES(p.price, { decimals: true })}</div></TableCell>
                  <TableCell>
                    <div className="mx-auto flex w-fit items-center gap-1">
                      <Button variant="outline" size="icon-xs" aria-label="Decrease" onClick={() => setQty(p.id, -1)}><MinusIcon /></Button>
                      <span className="w-6 text-center text-sm tabular-nums">{qty}</span>
                      <Button variant="outline" size="icon-xs" aria-label="Increase" onClick={() => setQty(p.id, 1)}><PlusIcon /></Button>
                    </div>
                  </TableCell>
                  <TableCell className="text-right tabular-nums">{formatKES(p.price * qty, { decimals: true })}</TableCell>
                  <TableCell><Button variant="ghost" size="icon-xs" aria-label="Remove" onClick={() => setQty(p.id, -qty)}><Trash2Icon /></Button></TableCell>
                </TableRow>
              ))}
              {lines.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">Cart is empty</TableCell></TableRow> : null}
            </TableBody>
          </Table>
        </div>
        <div className="space-y-3 border-t border-border p-3">
          <dl className="space-y-1 text-sm tabular-nums">
            <div className="flex justify-between"><dt className="text-muted-foreground">Subtotal</dt><dd>{formatKES(subtotal, { decimals: true })}</dd></div>
            <div className="flex justify-between"><dt className="text-muted-foreground">VAT 16% (eTIMS sales only)</dt><dd>{formatKES(vat, { decimals: true })}</dd></div>
            <div className="flex justify-between border-t border-border pt-2 text-lg font-semibold"><dt>Total</dt><dd>{formatKES(total, { decimals: true })}</dd></div>
          </dl>
          <RadioGroup value={pay} onValueChange={(v) => setPay(String(v))} className="grid-cols-4 gap-2">
            {["Cash", "M-Pesa", "Card", "Credit"].map((m) => (
              <Field key={m} orientation="horizontal" className="rounded-lg border border-border px-2 py-1.5">
                <RadioGroupItem value={m} id={`pay-${m}`} />
                <FieldLabel htmlFor={`pay-${m}`}>{m}</FieldLabel>
              </Field>
            ))}
          </RadioGroup>
          <button type="button" className="h-12 w-full cursor-pointer rounded-lg bg-action-accent-default text-base font-semibold text-fg-on-accent outline-none hover:bg-action-accent-hover active:bg-action-accent-active focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">
            Pay {formatKES(total, { decimals: true })}
          </button>
        </div>
      </div>
      </div>
    </Frame>
  );
}
