"use client";

import { useMemo } from "react";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/components/ui/tooltip";
import { Badge } from "@/shared/components/ui/badge";
import type { InventoryItem } from "../types";
import { STATUS_LABELS } from "../types";
import { cn } from "@/shared/lib/utils";

interface ServerRackProps {
  items: InventoryItem[];
}

const TOTAL_UNITS = 42;

const STATUS_COLORS: Record<string, string> = {
  active: "bg-green-500/80 dark:bg-green-600/80",
  "in-repair": "bg-amber-500/80 dark:bg-amber-600/80",
  storage: "bg-slate-400/80 dark:bg-slate-500/80",
  rented: "bg-purple-500/80 dark:bg-purple-600/80 animate-pulse",
  decommissioned: "bg-red-400/60 dark:bg-red-500/60",
};

interface RackSlot {
  unit: number;
  item?: InventoryItem;
  isStart: boolean;
  height: number;
}

export function ServerRack({ items }: ServerRackProps) {
  const slots = useMemo(() => {
    // Build the rack map
    const occupied = new Map<number, { item: InventoryItem; size: number }>();
    const rackItems = items.filter(
      (i) =>
        i.rackPosition && i.rackPosition >= 1 && i.rackPosition <= TOTAL_UNITS,
    );

    for (const item of rackItems) {
      const pos = item.rackPosition!;
      const size = item.rackSize ?? 1;
      occupied.set(pos, { item, size });
    }

    const result: RackSlot[] = [];
    let u = 1;
    while (u <= TOTAL_UNITS) {
      const entry = occupied.get(u);
      if (entry) {
        result.push({
          unit: u,
          item: entry.item,
          isStart: true,
          height: entry.size,
        });
        u += entry.size;
      } else {
        result.push({ unit: u, isStart: false, height: 1 });
        u++;
      }
    }
    return result;
  }, [items]);

  // Reverse so U1 is at the bottom (standard rack numbering)
  const displaySlots = useMemo(() => [...slots].reverse(), [slots]);

  const rackItems = items.filter((i) => i.rackPosition);

  if (rackItems.length === 0) {
    return (
      <div className="text-center py-8 text-sm text-muted-foreground">
        Niciun echipament cu poziție rack configurată.
        <br />
        <span className="text-xs">
          Editează un echipament de tip Server/Switch/UPS și completează
          &quot;Poziție Rack&quot;.
        </span>
      </div>
    );
  }

  return (
    <TooltipProvider>
      <div className="mx-auto max-w-md">
        {/* Rack frame */}
        <div className="rounded-lg border-2 border-slate-600 dark:border-slate-400 bg-slate-100 dark:bg-slate-900 overflow-hidden">
          {/* Top label */}
          <div className="bg-slate-700 dark:bg-slate-300 px-3 py-1.5 text-center">
            <span className="text-xs font-bold text-white dark:text-slate-900">
              SERVER RACK — 42U
            </span>
          </div>

          {/* Units */}
          <div className="p-1 space-y-px">
            {displaySlots.map((slot) => {
              if (!slot.isStart && slot.item) return null;

              const heightPx = slot.height * 24;

              if (slot.item) {
                const color =
                  STATUS_COLORS[slot.item.status] ?? STATUS_COLORS.active;
                return (
                  <Tooltip key={slot.unit}>
                    <TooltipTrigger asChild>
                      <div
                        className={cn(
                          "flex items-center gap-2 rounded px-2 text-white text-xs font-medium cursor-default transition-all hover:brightness-110",
                          color,
                        )}
                        style={{ height: `${heightPx}px` }}
                      >
                        <span className="text-[10px] opacity-70 shrink-0 w-5 text-right">
                          U{slot.unit}
                        </span>
                        <span className="truncate flex-1">
                          {slot.item.name}
                        </span>
                        <span className="text-[10px] opacity-70 shrink-0">
                          {slot.item.rackSize ?? 1}U
                        </span>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent side="right" className="max-w-xs">
                      <div className="space-y-1">
                        <p className="font-semibold">{slot.item.name}</p>
                        {slot.item.vendor && (
                          <p className="text-xs">
                            {slot.item.vendor}
                            {slot.item.model ? ` / ${slot.item.model}` : ""}
                          </p>
                        )}
                        {slot.item.ipAddress && (
                          <p className="text-xs font-mono">
                            IP: {slot.item.ipAddress}
                          </p>
                        )}
                        <Badge variant="secondary" className="text-[10px]">
                          {STATUS_LABELS[slot.item.status] ?? slot.item.status}
                        </Badge>
                      </div>
                    </TooltipContent>
                  </Tooltip>
                );
              }

              // Empty slot
              return (
                <div
                  key={slot.unit}
                  className="flex items-center px-2 rounded border border-dashed border-slate-300 dark:border-slate-700 text-[10px] text-muted-foreground"
                  style={{ height: "24px" }}
                >
                  <span className="w-5 text-right opacity-50">
                    U{slot.unit}
                  </span>
                </div>
              );
            })}
          </div>

          {/* Bottom label */}
          <div className="bg-slate-700 dark:bg-slate-300 px-3 py-1 text-center">
            <span className="text-[10px] text-white dark:text-slate-900">
              {rackItems.length} echipamente montate
            </span>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
}
