"use client";

import {
  Calendar,
  Edit,
  Layers,
  Package,
  Trash2,
  X,
} from "lucide-react";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { currency } from "@/lib/utils";
import { Category } from "@/types/category";

interface CategoryDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  category: Category | null;
  onEdit: (category: Category) => void;
  onDelete: (id: string) => void;
}

export function CategoryDetailModal({
  isOpen,
  onClose,
  category,
  onEdit,
  onDelete,
}: CategoryDetailModalProps) {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!isOpen || !category || !mounted) return null;

  const renderStatusBadge = (status: string) => {
    switch (status) {
      case "AVAILABLE":
        return <Badge tone="green">Disponível</Badge>;
      case "RENTED":
        return <Badge tone="blue">Locado</Badge>;
      case "MAINTENANCE":
        return <Badge tone="red">Manutenção</Badge>;
      default:
        return <Badge tone="blue">{status}</Badge>;
    }
  };

  return createPortal(
    <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 p-4 backdrop-blur-xs transition-all">
      <Card className="w-full max-w-3xl max-h-[90vh] overflow-y-auto p-6 shadow-2xl">
        {/* Header com Ações */}
        <div className="flex flex-wrap items-start justify-between gap-4 border-b pb-4">
          <div className="flex items-center gap-3">
            <div
              className="flex h-12 w-12 items-center justify-center rounded-xl text-white font-bold shadow-sm shrink-0"
              style={{ backgroundColor: category.color || "#2563eb" }}
            >
              <Layers className="h-6 w-6" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-2xl font-bold">{category.name}</h2>
                <span
                  className="inline-flex items-center gap-1.5 rounded-full border bg-muted px-3 py-0.5 text-xs font-medium"
                >
                  <span
                    className="h-2 w-2 rounded-full"
                    style={{ backgroundColor: category.color }}
                  />
                  {category._count?.equipment || category.equipment?.length || 0} ativos
                </span>
              </div>
              <p className="text-sm text-muted-foreground mt-0.5">
                {category.description || "Nenhuma descrição detalhada informada."}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Button variant="secondary" size="sm" onClick={() => onEdit(category)}>
              <Edit className="mr-1.5 h-4 w-4" /> Editar
            </Button>

            <Button
              variant="ghost"
              size="icon"
              className="text-rose-500 hover:bg-rose-500/10 hover:text-rose-600"
              onClick={() => {
                if (
                  confirm(
                    `Tem certeza que deseja excluir a categoria ${category.name}?`
                  )
                ) {
                  onDelete(category.id);
                  onClose();
                }
              }}
            >
              <Trash2 className="h-4 w-4" />
            </Button>

            <Button variant="ghost" size="icon" onClick={onClose}>
              <X className="h-5 w-5" />
            </Button>
          </div>
        </div>

        {/* Lista de Equipamentos Pertencentes à Categoria */}
        <div className="mt-6">
          <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
            <Package className="h-4 w-4" /> Equipamentos Pertencentes a esta Categoria
          </h3>

          {category.equipment && category.equipment.length > 0 ? (
            <div className="overflow-x-auto rounded-xl border">
              <table className="w-full text-left text-sm">
                <thead className="bg-muted/60 text-xs uppercase text-muted-foreground">
                  <tr>
                    <th className="px-4 py-2.5">Código / Patrimônio</th>
                    <th className="px-4 py-2.5">Marca / Modelo</th>
                    <th className="px-4 py-2.5">Diária (R$)</th>
                    <th className="px-4 py-2.5">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {category.equipment.map((equip) => (
                    <tr key={equip.id} className="hover:bg-muted/30">
                      <td className="px-4 py-2.5 font-mono font-medium">
                        {equip.code} <span className="text-xs text-muted-foreground">({equip.assetTag})</span>
                      </td>
                      <td className="px-4 py-2.5 font-medium">
                        {equip.brand} {equip.model}
                      </td>
                      <td className="px-4 py-2.5 font-medium">{currency(equip.dailyRate)}</td>
                      <td className="px-4 py-2.5">{renderStatusBadge(equip.status)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="rounded-xl border border-dashed p-8 text-center text-sm text-muted-foreground">
              Nenhum equipamento vinculado a esta categoria até o momento.
            </div>
          )}
        </div>

        <div className="mt-6 flex items-center justify-between border-t pt-4 text-xs text-muted-foreground">
          {category.createdAt && (
            <span className="flex items-center gap-1">
              <Calendar className="h-3.5 w-3.5" />
              Criada em: {new Date(category.createdAt).toLocaleDateString("pt-BR")}
            </span>
          )}
          <Button variant="secondary" onClick={onClose}>
            Fechar Detalhes
          </Button>
        </div>
      </Card>
    </div>,
    document.body
  );
}
