"use client";

import { useCallback, useEffect, useState } from "react";
import MainTitle from "@/components/layout/dashboard/main-title";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import ProductThumb from "@/components/app/product-thumb";
import DataService from "@/config/axios";
import { useRequireSuperAdmin } from "@/hooks/use-require-super-admin";
import { getApiErrorMessage } from "@/lib/api-error";
import { toast } from "sonner";
import InventoryAdjustDialog from "./inventory-adjust-dialog";

type Warehouse = { _id: string; name: string; code: string };
type Movement = {
  _id: string;
  type: string;
  direction: string;
  quantity: number;
  variantKey?: string;
  note?: string;
  createdAt?: string;
  product?: { title?: string; status?: string; images?: string[] };
  warehouse?: { name?: string; code?: string };
};

export default function InventoryHistoryAdmin() {
  const ready = useRequireSuperAdmin();
  const [loading, setLoading] = useState(true);
  const [rows, setRows] = useState<Movement[]>([]);
  const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
  const [direction, setDirection] = useState("all");
  const [warehouseId, setWarehouseId] = useState("all");
  const [adjustOpen, setAdjustOpen] = useState(false);

  const load = useCallback(async () => {
    try {
      const qs = new URLSearchParams();
      if (direction === "in" || direction === "out") qs.set("direction", direction);
      if (warehouseId !== "all") qs.set("warehouse", warehouseId);
      qs.set("limit", "150");
      const [mRes, wRes] = await Promise.all([
        DataService.get(`/admin/inventory/movements?${qs.toString()}`),
        DataService.get("/admin/warehouses"),
      ]);
      setRows(mRes.data?.data || []);
      setWarehouses(wRes.data?.data || []);
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Failed to load history"));
    } finally {
      setLoading(false);
    }
  }, [direction, warehouseId]);

  useEffect(() => {
    if (ready) {
      setLoading(true);
      load();
    }
  }, [ready, load]);

  if (!ready || loading) {
    return <div className="rounded-md border bg-white p-8 text-center text-gray-500">Loading…</div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <MainTitle title="Inventory history" />
          <p className="text-sm text-gray-500">Inbound and outbound stock movements.</p>
        </div>
        <Button type="button" onClick={() => setAdjustOpen(true)}>
          Adjust stock
        </Button>
      </div>

      <div className="flex flex-wrap gap-3">
        <Select value={direction} onValueChange={setDirection}>
          <SelectTrigger className="w-40">
            <SelectValue placeholder="Direction" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All directions</SelectItem>
            <SelectItem value="in">Inbound</SelectItem>
            <SelectItem value="out">Outbound</SelectItem>
          </SelectContent>
        </Select>
        <Select value={warehouseId} onValueChange={setWarehouseId}>
          <SelectTrigger className="w-52">
            <SelectValue placeholder="Warehouse" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All warehouses</SelectItem>
            {warehouses.map((w) => (
              <SelectItem key={w._id} value={w._id}>
                {w.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="rounded-md border bg-white">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>When</TableHead>
              <TableHead>Product</TableHead>
              <TableHead>Warehouse</TableHead>
              <TableHead>Direction</TableHead>
              <TableHead>Type</TableHead>
              <TableHead>Qty</TableHead>
              <TableHead>Note</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center text-gray-400">
                  No movements found.
                </TableCell>
              </TableRow>
            ) : (
              rows.map((m) => (
                <TableRow key={m._id}>
                  <TableCell className="whitespace-nowrap text-sm">
                    {m.createdAt ? new Date(m.createdAt).toLocaleString() : "—"}
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <ProductThumb src={m.product?.images?.[0]} alt={m.product?.title} />
                      <div>
                        {m.product?.title || "—"}
                        {m.product?.status === "draft" ? (
                          <span className="ml-1 text-xs text-amber-600">draft</span>
                        ) : null}
                        {m.variantKey ? (
                          <div className="font-mono text-xs text-gray-400">{m.variantKey}</div>
                        ) : null}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{m.warehouse?.name || m.warehouse?.code || "—"}</TableCell>
                  <TableCell className="capitalize">{m.direction}</TableCell>
                  <TableCell>{m.type}</TableCell>
                  <TableCell>{m.quantity}</TableCell>
                  <TableCell className="max-w-[200px] truncate text-sm text-gray-600">
                    {m.note || "—"}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <InventoryAdjustDialog open={adjustOpen} onOpenChange={setAdjustOpen} onDone={load} />
    </div>
  );
}
