"use client";

import { useState, useMemo } from "react";
import { Plus, Pencil, Trash2, Search } from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { Textarea } from "@/shared/components/ui/textarea";
import { Badge } from "@/shared/components/ui/badge";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/components/ui/dialog";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/shared/components/ui/tabs";
import type { CompanyId } from "@/core/auth/types";
import type {
  InventoryItem,
  InventoryItemType,
  InventoryItemStatus,
} from "../types";
import {
  DEFAULT_TYPE_LABELS,
  STATUS_LABELS,
  RACK_MOUNTABLE_TYPES,
} from "../types";
import { useInventory } from "../hooks/use-inventory";
import { ServerRack } from "./server-rack";
import { cn } from "@/shared/lib/utils";

type ViewMode = "list" | "add" | "edit";

/** Resolve type label from defaults or custom */
function getTypeLabel(type: string, customTypes: Map<string, string>): string {
  return (
    DEFAULT_TYPE_LABELS[type] ??
    customTypes.get(type) ??
    type.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase())
  );
}

export function ItInventoryModule() {
  const {
    items,
    allItems,
    loading,
    filters,
    updateFilter,
    addItem,
    updateItem,
    removeItem,
  } = useInventory();
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [editingItem, setEditingItem] = useState<InventoryItem | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  // Build dynamic type list from defaults + existing items
  const allTypes = useMemo(() => {
    const map = new Map<string, string>();
    for (const [key, label] of Object.entries(DEFAULT_TYPE_LABELS)) {
      map.set(key, label);
    }
    for (const item of allItems) {
      if (!map.has(item.type)) {
        map.set(
          item.type,
          item.type.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase()),
        );
      }
    }
    return map;
  }, [allItems]);

  // Custom types beyond defaults (for display)
  const customTypes = useMemo(() => {
    const map = new Map<string, string>();
    for (const item of allItems) {
      if (!DEFAULT_TYPE_LABELS[item.type]) {
        map.set(
          item.type,
          item.type.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase()),
        );
      }
    }
    return map;
  }, [allItems]);

  const handleSubmit = async (
    data: Omit<InventoryItem, "id" | "createdAt" | "updatedAt">,
  ) => {
    if (viewMode === "edit" && editingItem) {
      await updateItem(editingItem.id, data);
    } else {
      await addItem(data);
    }
    setViewMode("list");
    setEditingItem(null);
  };

  const handleDeleteConfirm = async () => {
    if (deletingId) {
      await removeItem(deletingId);
      setDeletingId(null);
    }
  };

  const rentedCount = allItems.filter((i) => i.status === "rented").length;

  return (
    <Tabs defaultValue="list">
      <TabsList>
        <TabsTrigger value="list">Inventar</TabsTrigger>
        <TabsTrigger value="rack">
          Rack 42U
          {allItems.filter((i) => i.rackPosition).length > 0 && (
            <Badge
              variant="secondary"
              className="ml-1.5 text-[10px] px-1.5 py-0"
            >
              {allItems.filter((i) => i.rackPosition).length}
            </Badge>
          )}
        </TabsTrigger>
      </TabsList>

      <TabsContent value="list">
        <div className="space-y-6">
          {/* Stats */}
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-5">
            <Card>
              <CardContent className="p-4">
                <p className="text-xs text-muted-foreground">Total</p>
                <p className="text-2xl font-bold">{allItems.length}</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4">
                <p className="text-xs text-muted-foreground">Active</p>
                <p className="text-2xl font-bold">
                  {allItems.filter((i) => i.status === "active").length}
                </p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4">
                <p className="text-xs text-muted-foreground">În reparație</p>
                <p className="text-2xl font-bold">
                  {allItems.filter((i) => i.status === "in-repair").length}
                </p>
              </CardContent>
            </Card>
            <Card
              className={cn(
                rentedCount > 0 && "ring-2 ring-purple-400/50 animate-pulse",
              )}
            >
              <CardContent className="p-4">
                <p className="text-xs text-muted-foreground">Închiriate</p>
                <p
                  className={cn(
                    "text-2xl font-bold",
                    rentedCount > 0 && "text-purple-600 dark:text-purple-400",
                  )}
                >
                  {rentedCount}
                </p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4">
                <p className="text-xs text-muted-foreground">Dezafectate</p>
                <p className="text-2xl font-bold">
                  {allItems.filter((i) => i.status === "decommissioned").length}
                </p>
              </CardContent>
            </Card>
          </div>

          {viewMode === "list" && (
            <>
              <div className="flex flex-wrap items-center gap-3">
                <div className="relative min-w-[200px] flex-1">
                  <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="Caută..."
                    value={filters.search}
                    onChange={(e) => updateFilter("search", e.target.value)}
                    className="pl-9"
                  />
                </div>
                <Select
                  value={filters.type}
                  onValueChange={(v) => updateFilter("type", v)}
                >
                  <SelectTrigger className="w-[160px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Toate tipurile</SelectItem>
                    {Array.from(allTypes.entries()).map(([key, label]) => (
                      <SelectItem key={key} value={key}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Select
                  value={filters.status}
                  onValueChange={(v) =>
                    updateFilter("status", v as InventoryItemStatus | "all")
                  }
                >
                  <SelectTrigger className="w-[140px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Toate</SelectItem>
                    {(Object.keys(STATUS_LABELS) as InventoryItemStatus[]).map(
                      (s) => (
                        <SelectItem key={s} value={s}>
                          {STATUS_LABELS[s]}
                        </SelectItem>
                      ),
                    )}
                  </SelectContent>
                </Select>
                <Button onClick={() => setViewMode("add")} className="shrink-0">
                  <Plus className="mr-1.5 h-4 w-4" /> Adaugă
                </Button>
              </div>

              {loading ? (
                <p className="py-8 text-center text-sm text-muted-foreground">
                  Se încarcă...
                </p>
              ) : items.length === 0 ? (
                <p className="py-8 text-center text-sm text-muted-foreground">
                  Niciun echipament găsit.
                </p>
              ) : (
                <div className="overflow-x-auto rounded-lg border">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b bg-muted/40">
                        <th className="px-3 py-2 text-left font-medium">
                          Nume
                        </th>
                        <th className="px-3 py-2 text-left font-medium">Tip</th>
                        <th className="px-3 py-2 text-left font-medium">
                          Vendor/Model
                        </th>
                        <th className="px-3 py-2 text-left font-medium">S/N</th>
                        <th className="px-3 py-2 text-left font-medium">IP</th>
                        <th className="px-3 py-2 text-left font-medium">
                          Locație
                        </th>
                        <th className="px-3 py-2 text-left font-medium">
                          Status
                        </th>
                        <th className="px-3 py-2 text-right font-medium">
                          Acțiuni
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {items.map((item) => {
                        const isRented = item.status === "rented";
                        return (
                          <tr
                            key={item.id}
                            className={cn(
                              "border-b hover:bg-muted/20 transition-colors",
                              isRented &&
                                "bg-purple-50/50 dark:bg-purple-950/10",
                            )}
                          >
                            <td className="px-3 py-2 font-medium">
                              {item.name}
                            </td>
                            <td className="px-3 py-2">
                              <Badge variant="outline">
                                {getTypeLabel(item.type, customTypes)}
                              </Badge>
                            </td>
                            <td className="px-3 py-2 text-xs">
                              {item.vendor && <span>{item.vendor}</span>}
                              {item.vendor && item.model && (
                                <span className="text-muted-foreground">
                                  {" "}
                                  /{" "}
                                </span>
                              )}
                              {item.model && (
                                <span className="text-muted-foreground">
                                  {item.model}
                                </span>
                              )}
                            </td>
                            <td className="px-3 py-2 font-mono text-xs">
                              {item.serialNumber}
                            </td>
                            <td className="px-3 py-2 font-mono text-xs">
                              {item.ipAddress}
                            </td>
                            <td className="px-3 py-2 text-xs">
                              {item.rackPosition ? (
                                <span>
                                  U{item.rackPosition}
                                  {item.rackSize && item.rackSize > 1
                                    ? `–U${item.rackPosition + item.rackSize - 1}`
                                    : ""}
                                  {item.rackLocation
                                    ? ` · ${item.rackLocation}`
                                    : ""}
                                </span>
                              ) : (
                                item.rackLocation || item.location || "—"
                              )}
                            </td>
                            <td className="px-3 py-2">
                              <Badge
                                variant="secondary"
                                className={cn(
                                  isRented &&
                                    "bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200 animate-pulse",
                                )}
                              >
                                {STATUS_LABELS[item.status] ?? item.status}
                              </Badge>
                            </td>
                            <td className="px-3 py-2 text-right">
                              <div className="flex justify-end gap-1">
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="h-7 w-7"
                                  onClick={() => {
                                    setEditingItem(item);
                                    setViewMode("edit");
                                  }}
                                >
                                  <Pencil className="h-3.5 w-3.5" />
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="h-7 w-7 text-destructive"
                                  onClick={() => setDeletingId(item.id)}
                                >
                                  <Trash2 className="h-3.5 w-3.5" />
                                </Button>
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}

              {!loading && (
                <p className="text-xs text-muted-foreground">
                  {items.length} din {allItems.length} echipamente afișate
                </p>
              )}
            </>
          )}

          {(viewMode === "add" || viewMode === "edit") && (
            <Card>
              <CardHeader>
                <CardTitle>
                  {viewMode === "edit"
                    ? "Editare echipament"
                    : "Echipament nou"}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <InventoryForm
                  initial={editingItem ?? undefined}
                  allTypes={allTypes}
                  onSubmit={handleSubmit}
                  onCancel={() => {
                    setViewMode("list");
                    setEditingItem(null);
                  }}
                />
              </CardContent>
            </Card>
          )}

          {/* Delete confirmation */}
          <Dialog
            open={deletingId !== null}
            onOpenChange={(open) => {
              if (!open) setDeletingId(null);
            }}
          >
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Confirmare ștergere</DialogTitle>
              </DialogHeader>
              <p className="text-sm">
                Ești sigur că vrei să ștergi acest echipament? Acțiunea este
                ireversibilă.
              </p>
              <DialogFooter>
                <Button variant="outline" onClick={() => setDeletingId(null)}>
                  Anulează
                </Button>
                <Button variant="destructive" onClick={handleDeleteConfirm}>
                  Șterge
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>
      </TabsContent>

      <TabsContent value="rack">
        <ServerRack items={allItems} />
      </TabsContent>
    </Tabs>
  );
}

// ── Inventory Form ──

function InventoryForm({
  initial,
  allTypes,
  onSubmit,
  onCancel,
}: {
  initial?: InventoryItem;
  allTypes: Map<string, string>;
  onSubmit: (
    data: Omit<InventoryItem, "id" | "createdAt" | "updatedAt">,
  ) => void;
  onCancel: () => void;
}) {
  const [name, setName] = useState(initial?.name ?? "");
  const [type, setType] = useState<InventoryItemType>(
    initial?.type ?? "laptop",
  );
  const [customType, setCustomType] = useState("");
  const [serialNumber, setSerialNumber] = useState(initial?.serialNumber ?? "");
  const [company, setCompany] = useState<CompanyId>(
    initial?.company ?? "beletage",
  );
  const [location, setLocation] = useState(initial?.location ?? "");
  const [status, setStatus] = useState<InventoryItemStatus>(
    initial?.status ?? "active",
  );
  const [ipAddress, setIpAddress] = useState(initial?.ipAddress ?? "");
  const [macAddress, setMacAddress] = useState(initial?.macAddress ?? "");
  const [rackPosition, setRackPosition] = useState<string>(
    initial?.rackPosition?.toString() ?? "",
  );
  const [rackSize, setRackSize] = useState<string>(
    initial?.rackSize?.toString() ?? "1",
  );
  const [rackLocation, setRackLocation] = useState(initial?.rackLocation ?? "");
  const [vendor, setVendor] = useState(initial?.vendor ?? "");
  const [model, setModel] = useState(initial?.model ?? "");
  const [notes, setNotes] = useState(initial?.notes ?? "");

  const showRackFields = RACK_MOUNTABLE_TYPES.has(type);

  const handleAddCustomType = () => {
    const label = customType.trim();
    if (!label) return;
    const key = label.toLowerCase().replace(/\s+/g, "-");
    setType(key);
    setCustomType("");
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        const rackPosNum = parseInt(rackPosition, 10);
        const rackSizeNum = parseInt(rackSize, 10);
        onSubmit({
          name,
          type,
          serialNumber,
          company,
          location,
          status,
          ipAddress,
          macAddress,
          rackPosition:
            showRackFields && rackPosNum >= 1 ? rackPosNum : undefined,
          rackSize:
            showRackFields && rackSizeNum >= 1 ? rackSizeNum : undefined,
          rackLocation,
          vendor,
          model,
          notes,
          tags: initial?.tags ?? [],
          visibility: initial?.visibility ?? "all",
        });
      }}
      className="space-y-4"
    >
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label>Nume echipament *</Label>
          <Input
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="mt-1"
            required
          />
        </div>
        <div>
          <Label>Tip</Label>
          <Select
            value={allTypes.has(type) ? type : "other"}
            onValueChange={(v) => setType(v as InventoryItemType)}
          >
            <SelectTrigger className="mt-1">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {Array.from(allTypes.entries()).map(([key, label]) => (
                <SelectItem key={key} value={key}>
                  {label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {/* Add custom type inline */}
          <div className="mt-1.5 flex gap-1">
            <Input
              value={customType}
              onChange={(e) => setCustomType(e.target.value)}
              placeholder="Tip nou..."
              className="text-xs h-7"
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault();
                  handleAddCustomType();
                }
              }}
            />
            <Button
              type="button"
              variant="outline"
              size="sm"
              className="h-7 px-2"
              onClick={handleAddCustomType}
              disabled={!customType.trim()}
            >
              <Plus className="h-3 w-3" />
            </Button>
          </div>
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-3">
        <div>
          <Label>Vendor</Label>
          <Input
            value={vendor}
            onChange={(e) => setVendor(e.target.value)}
            className="mt-1"
            placeholder="Dell, HP, Lenovo..."
          />
        </div>
        <div>
          <Label>Model</Label>
          <Input
            value={model}
            onChange={(e) => setModel(e.target.value)}
            className="mt-1"
          />
        </div>
        <div>
          <Label>Număr serie</Label>
          <Input
            value={serialNumber}
            onChange={(e) => setSerialNumber(e.target.value)}
            className="mt-1"
          />
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-3">
        <div>
          <Label>Adresă IP</Label>
          <Input
            value={ipAddress}
            onChange={(e) => setIpAddress(e.target.value)}
            className="mt-1"
            placeholder="192.168.1.x"
          />
        </div>
        <div>
          <Label>Adresă MAC</Label>
          <Input
            value={macAddress}
            onChange={(e) => setMacAddress(e.target.value)}
            className="mt-1"
            placeholder="AA:BB:CC:DD:EE:FF"
          />
        </div>
        <div>
          <Label>Companie</Label>
          <Select
            value={company}
            onValueChange={(v) => setCompany(v as CompanyId)}
          >
            <SelectTrigger className="mt-1">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="beletage">Beletage</SelectItem>
              <SelectItem value="urban-switch">Urban Switch</SelectItem>
              <SelectItem value="studii-de-teren">Studii de Teren</SelectItem>
              <SelectItem value="group">Grup</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-3">
        <div>
          <Label>Locație / Cameră</Label>
          <Input
            value={location}
            onChange={(e) => setLocation(e.target.value)}
            className="mt-1"
          />
        </div>
        <div>
          <Label>Rack / Poziție</Label>
          <Input
            value={rackLocation}
            onChange={(e) => setRackLocation(e.target.value)}
            className="mt-1"
            placeholder="Rack 1, Birou 2..."
          />
        </div>
        <div>
          <Label>Status</Label>
          <Select
            value={status}
            onValueChange={(v) => setStatus(v as InventoryItemStatus)}
          >
            <SelectTrigger className="mt-1">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {(Object.keys(STATUS_LABELS) as InventoryItemStatus[]).map(
                (s) => (
                  <SelectItem key={s} value={s}>
                    {STATUS_LABELS[s]}
                  </SelectItem>
                ),
              )}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Rack position fields — shown only for rack-mountable types */}
      {showRackFields && (
        <div className="grid gap-4 sm:grid-cols-2 p-3 rounded border border-dashed border-slate-400 dark:border-slate-600 bg-slate-50 dark:bg-slate-900/50">
          <div>
            <Label className="text-xs">
              Poziție Rack (U){" "}
              <span className="text-muted-foreground">(1–42)</span>
            </Label>
            <Input
              type="number"
              min={1}
              max={42}
              value={rackPosition}
              onChange={(e) => setRackPosition(e.target.value)}
              className="mt-1"
              placeholder="Ex: 12"
            />
          </div>
          <div>
            <Label className="text-xs">
              Dimensiune{" "}
              <span className="text-muted-foreground">(unități rack)</span>
            </Label>
            <Select value={rackSize} onValueChange={setRackSize}>
              <SelectTrigger className="mt-1">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="1">1U</SelectItem>
                <SelectItem value="2">2U</SelectItem>
                <SelectItem value="3">3U</SelectItem>
                <SelectItem value="4">4U</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      )}

      <div>
        <Label>Note</Label>
        <Textarea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={2}
          className="mt-1"
        />
      </div>

      <div className="flex justify-end gap-2 pt-2">
        <Button type="button" variant="outline" onClick={onCancel}>
          Anulează
        </Button>
        <Button type="submit">{initial ? "Actualizează" : "Adaugă"}</Button>
      </div>
    </form>
  );
}
