"use client";

import { useCallback, useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import ProductThumb from "@/components/app/product-thumb";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { toast } from "sonner";

type Warehouse = { _id: string; name: string; code: string; active?: boolean };
type ProductRow = {
  _id: string;
  title: string;
  status: string;
  stock?: number;
  images?: string[];
  variants?: { name: string; values: { label: string; stock?: number | null }[] }[];
};

type LineItem = {
  productId: string;
  variantKey: string;
  quantity: string;
};

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onDone?: () => void;
  defaultWarehouseId?: string;
};

function emptyLine(): LineItem {
  return { productId: "", variantKey: "", quantity: "1" };
}

function buildSlotOptions(product: ProductRow | null) {
  if (!product) return [{ value: "", label: "Main stock" }];
  const opts = [{ value: "", label: `Main stock (total ${product.stock ?? 0})` }];
  for (const g of product.variants || []) {
    for (const v of g.values || []) {
      if (v.stock != null && Number(v.stock) >= 0) {
        opts.push({
          value: `opt:${g.name}:${v.label}`,
          label: `${g.name}: ${v.label} (${v.stock})`,
        });
      }
    }
  }
  return opts;
}

export default function InventoryAdjustDialog({
  open,
  onOpenChange,
  onDone,
  defaultWarehouseId,
}: Props) {
  const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
  const [products, setProducts] = useState<ProductRow[]>([]);
  const [busy, setBusy] = useState(false);
  const [warehouseId, setWarehouseId] = useState("");
  const [direction, setDirection] = useState<"in" | "out">("in");
  const [note, setNote] = useState("");
  const [productFilter, setProductFilter] = useState("");
  const [lines, setLines] = useState<LineItem[]>([emptyLine()]);

  const loadMeta = useCallback(async () => {
    try {
      const [whRes, pRes] = await Promise.all([
        DataService.get("/admin/warehouses"),
        DataService.get("/admin/inventory/products"),
      ]);
      const wh = (whRes.data?.data || []) as Warehouse[];
      setWarehouses(wh.filter((w) => w.active !== false));
      setProducts(pRes.data?.data || []);
      if (defaultWarehouseId) setWarehouseId(defaultWarehouseId);
      else if (wh.length) {
        const def = wh.find((w) => (w as Warehouse & { isDefault?: boolean }).isDefault) || wh[0];
        setWarehouseId(def._id);
      }
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Failed to load products/warehouses"));
    }
  }, [defaultWarehouseId]);

  useEffect(() => {
    if (open) {
      loadMeta();
      setLines([emptyLine()]);
      setNote("");
      setDirection("in");
      setProductFilter("");
    }
  }, [open, loadMeta]);

  const filteredProducts = products.filter((p) => {
    if (!productFilter.trim()) return true;
    const q = productFilter.trim().toLowerCase();
    return p.title.toLowerCase().includes(q) || p.status.toLowerCase().includes(q);
  });

  const updateLine = (idx: number, patch: Partial<LineItem>) => {
    setLines((prev) => prev.map((l, i) => (i === idx ? { ...l, ...patch } : l)));
  };

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!warehouseId) {
      toast.error("Select a warehouse");
      return;
    }
    const prepared = lines
      .map((l) => ({
        productId: l.productId,
        variantKey: l.variantKey,
        quantity: Math.floor(Number(l.quantity) || 0),
      }))
      .filter((l) => l.productId);

    if (!prepared.length) {
      toast.error("Add at least one product");
      return;
    }
    if (prepared.some((l) => l.quantity < 1)) {
      toast.error("Each item needs a quantity of at least 1");
      return;
    }

    setBusy(true);
    try {
      await DataService.post("/admin/inventory/adjust", {
        warehouseId,
        direction,
        note: note.trim(),
        items: prepared,
      });
      toast.success(
        direction === "in"
          ? `Stock added (${prepared.length} item${prepared.length === 1 ? "" : "s"})`
          : `Stock removed (${prepared.length} item${prepared.length === 1 ? "" : "s"})`
      );
      onOpenChange(false);
      onDone?.();
    } catch (err: unknown) {
      toast.error(getApiErrorMessage(err, "Could not adjust stock"));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>Adjust inventory</DialogTitle>
        </DialogHeader>
        <p className="text-sm text-gray-500">
          All products are listed (published and draft). Add multiple items in one adjustment.
        </p>
        <form onSubmit={submit} className="grid gap-3">
          <div className="grid gap-3 sm:grid-cols-2">
            <div className="grid gap-2">
              <Label>Warehouse</Label>
              <Select value={warehouseId} onValueChange={setWarehouseId}>
                <SelectTrigger>
                  <SelectValue placeholder="Select warehouse" />
                </SelectTrigger>
                <SelectContent>
                  {warehouses.map((w) => (
                    <SelectItem key={w._id} value={w._id}>
                      {w.name} ({w.code})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label>Direction</Label>
              <Select value={direction} onValueChange={(v) => setDirection(v as "in" | "out")}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="in">Inbound (add)</SelectItem>
                  <SelectItem value="out">Outbound (remove)</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid gap-2">
            <Label>Search products</Label>
            <Input
              value={productFilter}
              onChange={(e) => setProductFilter(e.target.value)}
              placeholder="Filter by title or status…"
            />
          </div>

          <div className="space-y-3 border-t pt-3">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <Label className="text-sm font-medium">Items</Label>
              <Button type="button" variant="outline" size="sm" onClick={() => setLines((prev) => [...prev, emptyLine()])}>
                Add item
              </Button>
            </div>

            {lines.map((line, idx) => {
              const selectedProduct = products.find((p) => p._id === line.productId) || null;
              const slotOptions = buildSlotOptions(selectedProduct);
              return (
                <div
                  key={idx}
                  className="grid gap-2 rounded-md border border-gray-100 p-3 sm:grid-cols-12"
                >
                  <div className="grid gap-1 sm:col-span-6">
                    <Label className="text-xs">Product</Label>
                    <Select
                      value={line.productId}
                      onValueChange={(v) => updateLine(idx, { productId: v, variantKey: "" })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select product" />
                      </SelectTrigger>
                      <SelectContent className="max-h-64">
                        {filteredProducts.map((p) => (
                          <SelectItem key={p._id} value={p._id}>
                            <span className="flex items-center gap-2">
                              <ProductThumb src={p.images?.[0]} alt={p.title} />
                              <span>
                                {p.title} [{p.status}]
                              </span>
                            </span>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    {selectedProduct ? (
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <ProductThumb src={selectedProduct.images?.[0]} alt={selectedProduct.title} />
                        <span className="truncate">{selectedProduct.title}</span>
                      </div>
                    ) : null}
                  </div>

                  {slotOptions.length > 1 ? (
                    <div className="grid gap-1 sm:col-span-3">
                      <Label className="text-xs">Stock slot</Label>
                      <Select
                        value={line.variantKey || "__main__"}
                        onValueChange={(v) =>
                          updateLine(idx, { variantKey: v === "__main__" ? "" : v })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {slotOptions.map((o) => (
                            <SelectItem key={o.value || "__main__"} value={o.value || "__main__"}>
                              {o.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  ) : (
                    <div className="hidden sm:col-span-3 sm:block" />
                  )}

                  <div className="grid gap-1 sm:col-span-2">
                    <Label className="text-xs">Qty</Label>
                    <Input
                      type="number"
                      min={1}
                      value={line.quantity}
                      onChange={(e) => updateLine(idx, { quantity: e.target.value })}
                      required
                    />
                  </div>

                  <div className="flex items-end sm:col-span-1">
                    {lines.length > 1 ? (
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        className="w-full"
                        onClick={() => setLines((prev) => prev.filter((_, i) => i !== idx))}
                      >
                        ×
                      </Button>
                    ) : null}
                  </div>
                </div>
              );
            })}
          </div>

          <div className="grid gap-2">
            <Label>
              Reason <span className="font-normal text-muted-foreground">(optional)</span>
            </Label>
            <Input
              value={note}
              onChange={(e) => setNote(e.target.value)}
              placeholder="e.g. Damaged, Found stock…"
            />
          </div>
          <Button type="submit" disabled={busy}>
            {busy ? "Saving…" : "Apply"}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}
