"use client";

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

type BillOption = {
  _id: string;
  billNumber: string;
  supplier?: { name?: string };
};

type BillDetail = {
  _id: string;
  billNumber: string;
  invoiceNumber?: string;
  subtotal?: number;
  billDate?: string;
  supplier?: { name?: string };
  lines?: {
    qty: number;
    unitCost?: number;
    product?: { title?: string } | string;
    warehouse?: { name?: string; code?: string } | string;
  }[];
};

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

export default function InventoryReceiveBillDialog({ open, onOpenChange, onDone }: Props) {
  const [loading, setLoading] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  const [busy, setBusy] = useState(false);
  const [bills, setBills] = useState<BillOption[]>([]);
  const [billId, setBillId] = useState("");
  const [selected, setSelected] = useState<BillDetail | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await DataService.get("/admin/supplier-bills?status=draft");
      const rows = (res.data?.data || []) as BillOption[];
      setBills(rows);
      setBillId(rows[0]?._id || "");
      if (!rows.length) setSelected(null);
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Failed to load draft bills"));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (open) load();
  }, [open, load]);

  useEffect(() => {
    if (!open || !billId) {
      setSelected(null);
      return;
    }
    let cancelled = false;
    (async () => {
      setDetailLoading(true);
      try {
        const res = await DataService.get(`/admin/supplier-bills/${billId}`);
        if (!cancelled) setSelected(res.data?.data || null);
      } catch (e: unknown) {
        if (!cancelled) {
          setSelected(null);
          toast.error(getApiErrorMessage(e, "Failed to load bill details"));
        }
      } finally {
        if (!cancelled) setDetailLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [open, billId]);

  const receive = async () => {
    if (!billId) {
      toast.error("Select a supplier bill");
      return;
    }
    if (!confirm("Add this bill’s line items into warehouse inventory?")) return;
    setBusy(true);
    try {
      await DataService.post(`/admin/supplier-bills/${billId}/receive`);
      toast.success("Inventory updated from supplier bill");
      onOpenChange(false);
      onDone?.();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not receive bill into inventory"));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Add inventory from supplier bill</DialogTitle>
        </DialogHeader>

        {loading ? (
          <p className="text-sm text-muted-foreground">Loading draft bills…</p>
        ) : bills.length === 0 ? (
          <p className="text-sm text-muted-foreground">
            No draft supplier bills. Create a bill under Suppliers &amp; bills first, then receive it
            here.
          </p>
        ) : (
          <div className="space-y-4">
            <div className="grid gap-2">
              <Label>Supplier bill</Label>
              <Select value={billId} onValueChange={setBillId}>
                <SelectTrigger>
                  <SelectValue placeholder="Select draft bill" />
                </SelectTrigger>
                <SelectContent>
                  {bills.map((b) => (
                    <SelectItem key={b._id} value={b._id}>
                      {b.billNumber}
                      {b.supplier?.name ? ` — ${b.supplier.name}` : ""}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {detailLoading ? (
              <p className="text-sm text-muted-foreground">Loading bill lines…</p>
            ) : selected ? (
              <div className="space-y-2 rounded-md border bg-muted/30 p-3 text-sm">
                <div className="flex flex-wrap justify-between gap-2">
                  <span>
                    <span className="text-muted-foreground">Supplier: </span>
                    {selected.supplier?.name || "—"}
                  </span>
                  <span>
                    <span className="text-muted-foreground">Subtotal: </span>
                    {selected.subtotal ?? 0}
                  </span>
                </div>
                <div className="text-muted-foreground">
                  Date:{" "}
                  {selected.billDate
                    ? new Date(selected.billDate).toLocaleDateString()
                    : "—"}
                  {selected.invoiceNumber ? ` · Invoice ${selected.invoiceNumber}` : ""}
                </div>
                <ul className="max-h-40 space-y-1 overflow-y-auto border-t pt-2">
                  {(selected.lines || []).map((l, i) => {
                    const title =
                      typeof l.product === "object" ? l.product?.title : "Product";
                    const wh =
                      typeof l.warehouse === "object"
                        ? l.warehouse?.name || l.warehouse?.code
                        : "";
                    return (
                      <li key={i} className="flex justify-between gap-2">
                        <span className="truncate">
                          {title || "Product"}
                          {wh ? ` → ${wh}` : ""}
                        </span>
                        <span className="shrink-0 font-mono">
                          ×{l.qty}
                          {l.unitCost != null ? ` @ ${l.unitCost}` : ""}
                        </span>
                      </li>
                    );
                  })}
                </ul>
              </div>
            ) : null}

            <div className="flex justify-end gap-2">
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
              <Button type="button" disabled={busy || !billId} onClick={receive}>
                {busy ? "Adding…" : "Add to inventory"}
              </Button>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
