"use client";

import { useState } from "react";
import { ArchiveIcon, LayersIcon, MinusIcon, PlusIcon, SlidersHorizontalIcon } from "lucide-react";

import { Modal, ModalClose, type ModalSize } from "@/components/medora/modal";
import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "@/components/ui/toast";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { batches, formatDate, formatKES, products } from "@/lib/mock-data";
import { cn } from "@/lib/utils";

export type ModalProduct = { id: number; name: string; stock: number };

const REASONS = ["Count correction", "Damaged", "Expired", "Received outside a PO", "Returned by customer", "Other"];

// ---- adjust stock: a short form ------------------------------------------------------------------

export function AdjustStockModal({ product, open, onOpenChange }: { product: ModalProduct; open: boolean; onOpenChange: (o: boolean) => void }) {
  const [direction, setDirection] = useState<"add" | "remove">("add");
  const [qty, setQty] = useState("");
  const [reason, setReason] = useState("");
  const [note, setNote] = useState("");
  const [tried, setTried] = useState(false);

  const n = Number(qty);
  const qtyError = !qty || !Number.isInteger(n) || n <= 0 ? "Enter a whole number above 0" : direction === "remove" && n > product.stock ? `Only ${product.stock} in stock` : "";
  const reasonError = reason ? "" : "Choose a reason";
  const after = qtyError ? product.stock : direction === "add" ? product.stock + n : product.stock - n;
  const dirty = qty !== "" || reason !== "" || note !== "";

  const reset = () => {
    setDirection("add");
    setQty("");
    setReason("");
    setNote("");
    setTried(false);
  };
  const close = (o: boolean) => {
    onOpenChange(o);
    if (!o) reset();
  };
  const save = () => {
    setTried(true);
    if (qtyError || reasonError) return;
    toast.add({ type: "success", title: "Stock adjusted", description: `${product.name}: ${product.stock} → ${after} (${reason.toLowerCase()}).` });
    close(false);
  };

  return (
    <Modal
      open={open}
      onOpenChange={close}
      size="md"
      icon={SlidersHorizontalIcon}
      title="Adjust stock"
      description={`${product.name}. Every adjustment is logged with its reason and appears in stock movements.`}
      // Once something is typed, a stray backdrop click must not throw the entry away.
      dismissible={!dirty}
      footer={
        <>
          <ModalClose render={<Button variant="outline" />}>Cancel</ModalClose>
          <Button onClick={save}>Save adjustment</Button>
        </>
      }
    >
      <FieldGroup className="gap-4">
        <Field>
          <FieldLabel>Change</FieldLabel>
          <ToggleGroup variant="outline" spacing={0} value={[direction]} onValueChange={(v: string[]) => v[0] && setDirection(v[0] as "add" | "remove")} aria-label="Add or remove stock">
            <ToggleGroupItem value="add">
              <PlusIcon /> Add
            </ToggleGroupItem>
            <ToggleGroupItem value="remove">
              <MinusIcon /> Remove
            </ToggleGroupItem>
          </ToggleGroup>
        </Field>
        <div className="grid gap-4 sm:grid-cols-2">
          <Field data-invalid={tried && !!qtyError}>
            <FieldLabel htmlFor="adj-qty">Quantity</FieldLabel>
            <Input id="adj-qty" inputMode="numeric" className="tabular-nums" value={qty} onChange={(e) => setQty(e.target.value.replace(/[^\d]/g, ""))} aria-invalid={tried && !!qtyError} />
            {tried && qtyError ? <FieldError>{qtyError}</FieldError> : null}
          </Field>
          <Field data-invalid={tried && !!reasonError}>
            <FieldLabel>Reason</FieldLabel>
            <Select value={reason || null} onValueChange={(v) => setReason(String(v ?? ""))}>
              <SelectTrigger className="w-full" aria-invalid={tried && !!reasonError}>
                <SelectValue placeholder="Choose a reason" />
              </SelectTrigger>
              <SelectContent>
                {REASONS.map((r) => (
                  <SelectItem key={r} value={r}>
                    {r}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {tried && reasonError ? <FieldError>{reasonError}</FieldError> : null}
          </Field>
        </div>
        <Field>
          <FieldLabel htmlFor="adj-note">Note (optional)</FieldLabel>
          <Textarea id="adj-note" rows={2} value={note} onChange={(e) => setNote(e.target.value)} placeholder="e.g. Two packs crushed in delivery" />
        </Field>
        <div className="flex items-center justify-between rounded-lg bg-muted px-3 py-2.5 text-sm">
          <span className="text-muted-foreground">Stock after this change</span>
          <span className="tabular-nums">
            {product.stock.toLocaleString("en-US")} → <span className={cn("font-semibold", !qtyError && direction === "remove" && "text-status-warning-text")}>{after.toLocaleString("en-US")}</span>
          </span>
        </div>
        <FieldDescription>Backdrop clicks are ignored once you start typing, so an entry is never lost by accident.</FieldDescription>
      </FieldGroup>
    </Modal>
  );
}

// ---- archive: a destructive confirmation --------------------------------------------------------

export function ArchiveProductModal({ product, open, onOpenChange }: { product: ModalProduct; open: boolean; onOpenChange: (o: boolean) => void }) {
  return (
    <Modal
      open={open}
      onOpenChange={onOpenChange}
      size="sm"
      tone="destructive"
      icon={ArchiveIcon}
      title={`Archive ${product.name}?`}
      description={`It disappears from the till and from search. Its ${product.stock.toLocaleString("en-US")} units, past sales and reports are kept, and you can restore it from Archived products.`}
      footer={
        <>
          <ModalClose render={<Button variant="outline" />}>Keep product</ModalClose>
          <ModalClose
            render={<Button variant="destructive" />}
            onClick={() => toast.add({ title: `${product.name} archived`, description: "Restore it any time from Archived products." })}
          >
            Archive
          </ModalClose>
        </>
      }
    />
  );
}

// ---- batch details: long content that scrolls inside the modal ----------------------------------

const detailProduct = products[0];
const detailBatches = Array.from({ length: 14 }, (_, i) => {
  const b = batches[i % batches.length];
  return { ...b, id: i, batchNo: `${b.batchNo.slice(0, 2)}${24500 + i * 37}` };
});

function BatchDetailsModal() {
  const total = detailBatches.reduce((s, b) => s + b.stock, 0);
  const value = detailBatches.reduce((s, b) => s + b.stock * b.costPrice, 0);
  return (
    <Modal
      trigger={<Button variant="outline" />}
      triggerLabel={
        <>
          <LayersIcon data-icon="inline-start" />
          Batch details (long)
        </>
      }
      size="lg"
      icon={LayersIcon}
      title={`${detailProduct.name} ${detailProduct.strength}: batches`}
      description="14 batches. The body scrolls on its own; the title and the footer stay in place."
      footer={<ModalClose render={<Button />}>Done</ModalClose>}
    >
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Batch</TableHead>
            <TableHead>Expiry</TableHead>
            <TableHead className="text-right">Units</TableHead>
            <TableHead className="text-right">Cost</TableHead>
            <TableHead className="text-right">Value</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {detailBatches.map((b) => (
            <TableRow key={b.id}>
              <TableCell className="font-mono text-xs">{b.batchNo}</TableCell>
              <TableCell>{formatDate(b.expiryDate)}</TableCell>
              <TableCell className="text-right tabular-nums">{b.stock.toLocaleString("en-US")}</TableCell>
              <TableCell className="text-right tabular-nums">{formatKES(b.costPrice, { decimals: true })}</TableCell>
              <TableCell className="text-right tabular-nums">{formatKES(b.stock * b.costPrice, { decimals: true })}</TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TableCell colSpan={2}>Total</TableCell>
            <TableCell className="text-right tabular-nums">{total.toLocaleString("en-US")}</TableCell>
            <TableCell />
            <TableCell className="text-right tabular-nums">{formatKES(value, { decimals: true })}</TableCell>
          </TableRow>
        </TableFooter>
      </Table>
    </Modal>
  );
}

// ---- showcase ------------------------------------------------------------------------------------

const SIZES: { size: ModalSize; width: string; use: string }[] = [
  { size: "sm", width: "384 px", use: "Confirmations and single questions" },
  { size: "md", width: "512 px", use: "Short forms: adjust stock, record a payment" },
  { size: "lg", width: "672 px", use: "Longer forms and record details" },
  { size: "xl", width: "896 px", use: "Tables, comparisons, side-by-side content" },
];

export function ModalSizes() {
  return (
    <div className="flex flex-wrap gap-2">
      {SIZES.map((s) => (
        <Modal
          key={s.size}
          trigger={<Button variant="outline" />}
          triggerLabel={`${s.size.toUpperCase()} · ${s.width}`}
          size={s.size}
          title={`${s.size.toUpperCase()} modal, ${s.width}`}
          description={s.use}
          footer={
            <>
              <ModalClose render={<Button variant="outline" />}>Cancel</ModalClose>
              <ModalClose render={<Button />}>Continue</ModalClose>
            </>
          }
        >
          <p className="text-muted-foreground">
            Width is capped at the viewport minus 2 rem, so every size fits on a phone. Height is capped at 85% of the screen; longer content scrolls inside the body.
          </p>
        </Modal>
      ))}
    </div>
  );
}

const demo: ModalProduct = { id: products[1].id, name: `${products[1].name} ${products[1].strength}`, stock: products[1].stock };

export function ModalUseCases() {
  const [adjust, setAdjust] = useState(false);
  const [archive, setArchive] = useState(false);
  return (
    <div className="flex flex-wrap gap-2">
      <Button variant="outline" onClick={() => setAdjust(true)}>
        <SlidersHorizontalIcon data-icon="inline-start" />
        Adjust stock (form)
      </Button>
      <BatchDetailsModal />
      <Button variant="outline" onClick={() => setArchive(true)}>
        <ArchiveIcon data-icon="inline-start" />
        Archive product (destructive)
      </Button>
      <AdjustStockModal product={demo} open={adjust} onOpenChange={setAdjust} />
      <ArchiveProductModal product={demo} open={archive} onOpenChange={setArchive} />
    </div>
  );
}
