import React, { useEffect, useMemo, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import {
  Loader2,
  Package,
  RefreshCw,
  Search,
  Warehouse,
  ArrowLeftRight,
} from "lucide-react";
import { API } from "@/apis/configs/axiosConfigs";
import { InventoryAPI } from "@/apis/InventoryAPI";
import { WarehouseAPI } from "@/apis/WarehouseAPI";
import ProductBlockControls from "@/components/inventory/ProductBlockControls";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

const PAGE_SIZE_OPTIONS = [25, 50, 100];
const STOCK_FILTER_OPTIONS = [
  { value: "all", label: "Todos" },
  { value: "with_stock", label: "Con stock" },
  { value: "blocked", label: "Bloqueados" },
  { value: "zero", label: "Sin stock o negativo" },
];

const TYPE_LABELS = {
  entrada: "Entrada",
  salida: "Salida",
  traspaso: "Traspaso",
};

const unwrap = (res) => res?.data?.data?.detail ?? res?.data?.data ?? res?.data;

function formatQty(value) {
  return Number(value || 0).toLocaleString("es-CL");
}

function formatDateTime(value) {
  if (!value) return "—";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return value;
  return d.toLocaleString("es-CL", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function SummaryCard({ label, value }) {
  return (
    <div className="rounded-lg border bg-muted/20 p-3">
      <p className="text-xs text-muted-foreground uppercase tracking-wide">{label}</p>
      <p className="text-xl font-semibold tabular-nums mt-0.5">{value}</p>
    </div>
  );
}

function PaginationBar({ page, pageSize, total, onPageChange, onPageSizeChange, noun = "registros" }) {
  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  const safePage = Math.min(page, totalPages);
  const pageStart = (safePage - 1) * pageSize;

  if (total === 0) return null;

  return (
    <div className="flex flex-wrap items-center justify-between gap-3 pt-3 border-t">
      <p className="text-sm text-muted-foreground">
        Mostrando {pageStart + 1}-{Math.min(pageStart + pageSize, total)} de {total} {noun}
      </p>
      <div className="flex flex-wrap items-center gap-2">
        <Select value={String(pageSize)} onValueChange={(value) => onPageSizeChange(Number(value))}>
          <SelectTrigger className="w-[80px]"><SelectValue /></SelectTrigger>
          <SelectContent>
            {PAGE_SIZE_OPTIONS.map((size) => (
              <SelectItem key={size} value={String(size)}>{size}</SelectItem>
            ))}
          </SelectContent>
        </Select>
        <span className="text-sm text-muted-foreground whitespace-nowrap">
          Página {safePage} de {totalPages}
        </span>
        <Button variant="outline" size="sm" onClick={() => onPageChange(Math.max(1, safePage - 1))} disabled={safePage <= 1}>
          Anterior
        </Button>
        <Button variant="outline" size="sm" onClick={() => onPageChange(Math.min(totalPages, safePage + 1))} disabled={safePage >= totalPages}>
          Siguiente
        </Button>
      </div>
    </div>
  );
}

export default function InventoryWarehouseView() {
  const [companyId, setCompanyId] = useState(null);
  const [warehouses, setWarehouses] = useState([]);
  const [warehouseId, setWarehouseId] = useState("");
  const [rows, setRows] = useState([]);
  const [search, setSearch] = useState("");
  const [stockFilter, setStockFilter] = useState("all");
  const [loading, setLoading] = useState(false);
  const [blockRow, setBlockRow] = useState(null);
  const [movements, setMovements] = useState([]);
  const [movementSearch, setMovementSearch] = useState("");
  const [stockPage, setStockPage] = useState(1);
  const [stockPageSize, setStockPageSize] = useState(25);
  const [movementPage, setMovementPage] = useState(1);
  const [movementPageSize, setMovementPageSize] = useState(25);
  const [activeTab, setActiveTab] = useState("stock");

  useEffect(() => {
    (async () => {
      const company = await InventoryAPI.getPrimaryCompanyForCurrentUser();
      if (!company?.id) return;
      setCompanyId(company.id);
      const list = await WarehouseAPI.getByCompanyId(String(company.id));
      setWarehouses(Array.isArray(list) ? list : []);
    })().catch((e) => toast.error(e.message || "No se pudieron cargar bodegas"));
  }, []);

  const load = async (id) => {
    if (!companyId || !id) return;
    try {
      setLoading(true);
      const [stockRes, historyRes] = await Promise.all([
        API.get(`/inventory-stocks/by-warehouse/${id}`, { params: { idcompany: companyId } }),
        API.get(`/inventory-stocks/by-warehouse/${id}/movements`, { params: { idcompany: companyId } }),
      ]);
      setRows(unwrap(stockRes) || []);
      setMovements(unwrap(historyRes) || []);
      setStockPage(1);
      setMovementPage(1);
      setSearch("");
      setMovementSearch("");
    } catch (e) {
      toast.error(e?.response?.data?.data?.message || "No se pudo cargar el inventario");
    } finally {
      setLoading(false);
    }
  };

  const selectedWarehouse = warehouses.find((wh) => String(wh.id) === String(warehouseId));

  const filteredStock = useMemo(() => {
    const term = search.trim().toLowerCase();
    return rows.filter((row) => {
      const qty = Number(row.quantity || 0);
      if (stockFilter === "with_stock" && qty <= 0) return false;
      if (stockFilter === "blocked" && !row.is_blocked) return false;
      if (stockFilter === "zero" && qty > 0) return false;
      if (!term) return true;
      return `${row.sku || ""} ${row.name || ""}`.toLowerCase().includes(term);
    });
  }, [rows, search, stockFilter]);

  const filteredMovements = useMemo(() => {
    const term = movementSearch.trim().toLowerCase();
    if (!term) return movements;
    return movements.filter((move) =>
      [move.sku, move.product, move.type, move.user_name, move.folio, move.reference]
        .join(" ")
        .toLowerCase()
        .includes(term),
    );
  }, [movements, movementSearch]);

  const stockStats = useMemo(() => {
    const blocked = rows.filter((r) => r.is_blocked).length;
    const withStock = rows.filter((r) => Number(r.quantity || 0) > 0).length;
    const totalUnits = rows.reduce((sum, r) => sum + Number(r.quantity || 0), 0);
    return { total: rows.length, blocked, withStock, totalUnits };
  }, [rows]);

  const stockTotalPages = Math.max(1, Math.ceil(filteredStock.length / stockPageSize));
  const safeStockPage = Math.min(stockPage, stockTotalPages);
  const stockSlice = filteredStock.slice(
    (safeStockPage - 1) * stockPageSize,
    safeStockPage * stockPageSize,
  );

  const movementTotalPages = Math.max(1, Math.ceil(filteredMovements.length / movementPageSize));
  const safeMovementPage = Math.min(movementPage, movementTotalPages);
  const movementSlice = filteredMovements.slice(
    (safeMovementPage - 1) * movementPageSize,
    safeMovementPage * movementPageSize,
  );

  useEffect(() => {
    if (stockPage > stockTotalPages) setStockPage(stockTotalPages);
  }, [stockPage, stockTotalPages]);

  useEffect(() => {
    if (movementPage > movementTotalPages) setMovementPage(movementTotalPages);
  }, [movementPage, movementTotalPages]);

  return (
    <div className="p-4 lg:p-6 space-y-4 max-w-[1400px]">
      <div>
        <h1 className="text-2xl font-semibold flex items-center gap-2">
          <Warehouse className="h-6 w-6 text-blue-600" />
          Inventario por bodega
        </h1>
        <p className="text-sm text-muted-foreground mt-1">
          Stock actual, bloqueo de productos y movimientos con usuario y folio.
        </p>
      </div>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Selección de bodega</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-wrap gap-3 items-end">
            <div className="space-y-1">
              <Label>Bodega</Label>
              <Select
                value={warehouseId}
                onValueChange={(value) => {
                  setWarehouseId(value);
                  load(value);
                }}
              >
                <SelectTrigger className="w-[280px]">
                  <SelectValue placeholder="Seleccione bodega" />
                </SelectTrigger>
                <SelectContent>
                  {warehouses.map((wh) => (
                    <SelectItem key={String(wh.id)} value={String(wh.id)}>
                      {wh.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <Button variant="outline" onClick={() => load(warehouseId)} disabled={!warehouseId || loading}>
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
              <span className="ml-2">Actualizar</span>
            </Button>
          </div>

          {selectedWarehouse && !loading && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              <SummaryCard label="SKUs en bodega" value={stockStats.total} />
              <SummaryCard label="Con stock" value={stockStats.withStock} />
              <SummaryCard label="Bloqueados" value={stockStats.blocked} />
              <SummaryCard label="Unidades totales" value={formatQty(stockStats.totalUnits)} />
            </div>
          )}
        </CardContent>
      </Card>

      {!warehouseId ? (
        <Card>
          <CardContent className="py-16 text-center text-muted-foreground">
            <Warehouse className="h-12 w-12 mx-auto mb-3 opacity-40" />
            <p>Selecciona una bodega para ver stock y movimientos.</p>
          </CardContent>
        </Card>
      ) : loading ? (
        <div className="flex items-center justify-center gap-2 py-20 text-muted-foreground">
          <Loader2 className="h-5 w-5 animate-spin" />
          Cargando inventario…
        </div>
      ) : (
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
          <TabsList>
            <TabsTrigger value="stock" className="gap-2">
              <Package className="h-4 w-4" />
              Stock
              <Badge variant="secondary" className="ml-1 px-1.5 py-0 text-xs">{filteredStock.length}</Badge>
            </TabsTrigger>
            <TabsTrigger value="movements" className="gap-2">
              <ArrowLeftRight className="h-4 w-4" />
              Movimientos
              <Badge variant="secondary" className="ml-1 px-1.5 py-0 text-xs">{filteredMovements.length}</Badge>
            </TabsTrigger>
          </TabsList>

          <TabsContent value="stock">
            <Card>
              <CardHeader className="pb-3">
                <div className="flex flex-wrap items-end justify-between gap-3">
                  <CardTitle className="text-base">Productos en {selectedWarehouse?.name}</CardTitle>
                  <div className="flex flex-wrap gap-2">
                    <div className="relative">
                      <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                      <Input
                        className="pl-8 w-[220px]"
                        placeholder="Buscar SKU o nombre…"
                        value={search}
                        onChange={(e) => {
                          setSearch(e.target.value);
                          setStockPage(1);
                        }}
                      />
                    </div>
                    <Select
                      value={stockFilter}
                      onValueChange={(value) => {
                        setStockFilter(value);
                        setStockPage(1);
                      }}
                    >
                      <SelectTrigger className="w-[180px]"><SelectValue /></SelectTrigger>
                      <SelectContent>
                        {STOCK_FILTER_OPTIONS.map((opt) => (
                          <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                {filteredStock.length === 0 ? (
                  <p className="text-sm text-muted-foreground py-8 text-center">
                    {search || stockFilter !== "all"
                      ? "Sin productos con el filtro aplicado."
                      : "Esta bodega no tiene productos registrados."}
                  </p>
                ) : (
                  <>
                    <div className="overflow-x-auto rounded-md border">
                      <table className="w-full text-sm">
                        <thead>
                          <tr className="text-left border-b bg-muted/40">
                            <th className="p-3">SKU</th>
                            <th className="p-3">Producto</th>
                            <th className="p-3 text-right">Cantidad</th>
                            <th className="p-3">Estado</th>
                            <th className="p-3">Acción</th>
                          </tr>
                        </thead>
                        <tbody>
                          {stockSlice.map((row) => {
                            const qty = Number(row.quantity || 0);
                            return (
                              <tr key={row.idproduct} className="border-b last:border-b-0">
                                <td className="p-3 font-mono text-xs">{row.sku}</td>
                                <td className="p-3">{row.name}</td>
                                <td className={`p-3 text-right tabular-nums font-medium ${qty < 0 ? "text-red-600" : qty === 0 ? "text-amber-700" : ""}`}>
                                  {formatQty(qty)}
                                </td>
                                <td className="p-3">
                                  {row.is_blocked ? (
                                    <Badge variant="outline" className="bg-red-50 text-red-800 border-red-200">
                                      Bloqueado
                                    </Badge>
                                  ) : (
                                    <Badge variant="outline">Disponible</Badge>
                                  )}
                                </td>
                                <td className="p-3">
                                  <Button size="sm" variant="outline" onClick={() => setBlockRow(row)}>
                                    {row.is_blocked ? "Gestionar" : "Bloquear"}
                                  </Button>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                    <PaginationBar
                      page={safeStockPage}
                      pageSize={stockPageSize}
                      total={filteredStock.length}
                      noun="productos"
                      onPageChange={setStockPage}
                      onPageSizeChange={(size) => {
                        setStockPageSize(size);
                        setStockPage(1);
                      }}
                    />
                  </>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="movements">
            <Card>
              <CardHeader className="pb-3">
                <div className="flex flex-wrap items-end justify-between gap-3">
                  <div>
                    <CardTitle className="text-base">Movimientos recientes</CardTitle>
                    <p className="text-xs text-muted-foreground mt-1">
                      Usuario y folio por movimiento (trazabilidad R17).
                    </p>
                  </div>
                  <div className="relative">
                    <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                      className="pl-8 w-[240px]"
                      placeholder="Filtrar SKU, folio, usuario…"
                      value={movementSearch}
                      onChange={(e) => {
                        setMovementSearch(e.target.value);
                        setMovementPage(1);
                      }}
                    />
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                {filteredMovements.length === 0 ? (
                  <p className="text-sm text-muted-foreground py-8 text-center">
                    {movementSearch
                      ? "Sin movimientos que coincidan con el filtro."
                      : "Esta bodega aún no tiene movimientos registrados con folio."}
                  </p>
                ) : (
                  <>
                    <div className="overflow-x-auto rounded-md border">
                      <table className="w-full text-sm">
                        <thead>
                          <tr className="text-left border-b bg-muted/40">
                            <th className="p-3">Fecha</th>
                            <th className="p-3">SKU</th>
                            <th className="p-3">Tipo</th>
                            <th className="p-3 text-right">Cantidad</th>
                            <th className="p-3">Usuario</th>
                            <th className="p-3">Folio</th>
                          </tr>
                        </thead>
                        <tbody>
                          {movementSlice.map((move, index) => (
                            <tr key={`${move.folio}-${move.date}-${index}`} className="border-b last:border-b-0">
                              <td className="p-3 text-muted-foreground whitespace-nowrap">
                                {formatDateTime(move.date)}
                              </td>
                              <td className="p-3 font-mono text-xs">{move.sku || "—"}</td>
                              <td className="p-3">
                                <Badge variant="outline">
                                  {TYPE_LABELS[move.type] || move.type || "—"}
                                </Badge>
                              </td>
                              <td className="p-3 text-right tabular-nums">{formatQty(move.quantity)}</td>
                              <td className="p-3">{move.user_name || "—"}</td>
                              <td className="p-3 font-mono text-xs">{move.folio || "—"}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                    <PaginationBar
                      page={safeMovementPage}
                      pageSize={movementPageSize}
                      total={filteredMovements.length}
                      noun="movimientos"
                      onPageChange={setMovementPage}
                      onPageSizeChange={(size) => {
                        setMovementPageSize(size);
                        setMovementPage(1);
                      }}
                    />
                  </>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      )}

      <Dialog open={!!blockRow} onOpenChange={(open) => !open && setBlockRow(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Bloqueo de {blockRow?.sku}</DialogTitle>
            <DialogDescription>{blockRow?.name}</DialogDescription>
          </DialogHeader>
          {blockRow ? (
            <ProductBlockControls
              compact
              product={blockRow}
              onUpdated={(updated) => {
                const merged = {
                  ...blockRow,
                  ...updated,
                  idproduct: blockRow.idproduct,
                };
                setBlockRow(merged);
                setRows((prev) =>
                  prev.map((row) => (row.idproduct === merged.idproduct ? { ...row, ...merged } : row)),
                );
              }}
            />
          ) : null}
        </DialogContent>
      </Dialog>
    </div>
  );
}
