"use client";

import {
  AlertTriangle,
  Calendar,
  CheckCircle2,
  Clock,
  DollarSign,
  Edit,
  Hash,
  Package,
  ShieldCheck,
  Tag,
  Trash2,
  Truck,
  Wrench,
  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, formatDate } from "@/lib/utils";
import { Equipment, EquipmentStatus } from "@/types/equipment";

interface EquipmentDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  equipment: Equipment | null;
  onEdit: (equipment: Equipment) => void;
  onDelete: (id: string) => void;
  onToggleStatus: (id: string, newStatus: EquipmentStatus) => void;
}

export function EquipmentDetailModal({
  isOpen,
  onClose,
  equipment,
  onEdit,
  onDelete,
  onToggleStatus,
}: EquipmentDetailModalProps) {
  const [mounted, setMounted] = useState(false);

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

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

  const getStatusBadge = (status: EquipmentStatus) => {
    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">Em Manutenção</Badge>;
      case "RESERVED":
        return <Badge tone="blue">Reservado</Badge>;
      case "INACTIVE":
        return <Badge tone="red">Inativo</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-4xl 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="rounded-xl border bg-muted/60 p-3">
              <Package className="h-7 w-7 text-primary" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-2xl font-bold">
                  {equipment.brand} {equipment.model}
                </h2>
                {getStatusBadge(equipment.status)}
              </div>
              <p className="text-sm text-muted-foreground flex items-center gap-2 mt-0.5 font-mono">
                <span>Código: {equipment.code}</span>
                <span>•</span>
                <span>Patrimônio: {equipment.assetTag}</span>
                {equipment.category && (
                  <>
                    <span>•</span>
                    <span className="font-sans font-medium text-foreground">
                      {equipment.category.name}
                    </span>
                  </>
                )}
              </p>
            </div>
          </div>

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

            {/* Alternar Status Rápido */}
            <select
              value={equipment.status}
              onChange={(e) => onToggleStatus(equipment.id, e.target.value as EquipmentStatus)}
              className="h-9 rounded-md border border-input bg-background px-3 text-xs font-medium shadow-xs focus:outline-hidden focus:ring-1 focus:ring-ring"
            >
              <option value="AVAILABLE">Disponível</option>
              <option value="RENTED">Locado</option>
              <option value="MAINTENANCE">Manutenção</option>
              <option value="RESERVED">Reservado</option>
              <option value="INACTIVE">Inativo</option>
            </select>

            <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 ${equipment.code}?`)) {
                  onDelete(equipment.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>

        {/* Tarifador & Telemetria */}
        <div className="mt-5 grid gap-4 sm:grid-cols-4">
          <div className="rounded-xl border bg-muted/40 p-4">
            <p className="text-xs font-medium uppercase text-muted-foreground flex items-center gap-1.5">
              <DollarSign className="h-4 w-4 text-emerald-500" /> Diária
            </p>
            <p className="mt-2 text-xl font-bold text-foreground">
              {currency(equipment.dailyRate)}
            </p>
          </div>

          <div className="rounded-xl border bg-muted/40 p-4">
            <p className="text-xs font-medium uppercase text-muted-foreground flex items-center gap-1.5">
              <DollarSign className="h-4 w-4 text-blue-500" /> Semanal
            </p>
            <p className="mt-2 text-xl font-bold text-foreground">
              {currency(equipment.weeklyRate)}
            </p>
          </div>

          <div className="rounded-xl border bg-muted/40 p-4">
            <p className="text-xs font-medium uppercase text-muted-foreground flex items-center gap-1.5">
              <DollarSign className="h-4 w-4 text-purple-500" /> Mensal
            </p>
            <p className="mt-2 text-xl font-bold text-foreground">
              {currency(equipment.monthlyRate)}
            </p>
          </div>

          <div className="rounded-xl border bg-muted/40 p-4">
            <p className="text-xs font-medium uppercase text-muted-foreground flex items-center gap-1.5">
              <Clock className="h-4 w-4 text-amber-500" /> Horímetro
            </p>
            <p className="mt-2 text-xl font-bold text-foreground">
              {equipment.hourMeter ? `${equipment.hourMeter} hrs` : "Não registrado"}
            </p>
          </div>
        </div>

        {/* Ficha Técnica detalhada */}
        <div className="mt-6 rounded-xl border p-4">
          <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2 mb-4">
            <Tag className="h-4 w-4" /> Especificações do Ativo
          </h3>

          <div className="grid gap-4 sm:grid-cols-3 text-sm">
            <div>
              <span className="text-muted-foreground block text-xs">Marca / Fabricante</span>
              <strong className="text-foreground">{equipment.brand}</strong>
            </div>

            <div>
              <span className="text-muted-foreground block text-xs">Modelo</span>
              <strong className="text-foreground">{equipment.model}</strong>
            </div>

            <div>
              <span className="text-muted-foreground block text-xs">Ano de Fabricação</span>
              <strong className="text-foreground">{equipment.year || "Não informado"}</strong>
            </div>

            <div>
              <span className="text-muted-foreground block text-xs">Número de Série</span>
              <strong className="text-foreground font-mono">
                {equipment.serialNumber || "Não informado"}
              </strong>
            </div>

            <div>
              <span className="text-muted-foreground block text-xs">Valor de Aquisição</span>
              <strong className="text-foreground">
                {currency(equipment.acquisitionValue)}
              </strong>
            </div>

            <div>
              <span className="text-muted-foreground block text-xs">Data de Cadastro</span>
              <strong className="text-foreground">
                {new Date(equipment.createdAt).toLocaleDateString("pt-BR")}
              </strong>
            </div>
          </div>
        </div>

        {/* Observações Gerais */}
        {equipment.notes && (
          <div className="mt-6 rounded-xl border bg-blue-500/5 p-4 border-blue-500/20">
            <h3 className="text-xs font-semibold uppercase tracking-wider text-blue-600 dark:text-blue-400">
              Observações Técnicas e Operacionais
            </h3>
            <p className="mt-1 text-sm text-foreground/90">{equipment.notes}</p>
          </div>
        )}

        {/* Histórico de Locações Recentes */}
        <div className="mt-6">
          <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
            <Truck className="h-4 w-4" /> Locações & Contratos Vinculados
          </h3>
          {equipment.rentalItems && equipment.rentalItems.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">Contrato</th>
                    <th className="px-4 py-2.5">Cliente</th>
                    <th className="px-4 py-2.5">Período</th>
                    <th className="px-4 py-2.5">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {equipment.rentalItems.map((item) => (
                    <tr key={item.id} className="hover:bg-muted/30">
                      <td className="px-4 py-2.5 font-medium">{item.rental?.code}</td>
                      <td className="px-4 py-2.5 font-medium">{item.rental?.customer?.name}</td>
                      <td className="px-4 py-2.5 text-xs text-muted-foreground">
                        {formatDate(item.rental?.startDate)} até {formatDate(item.rental?.endDate)}
                      </td>
                      <td className="px-4 py-2.5">
                        <Badge tone="blue">{item.rental?.status}</Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground">
              Nenhuma locação ativa no momento. Este equipamento está disponível para novos contratos.
            </div>
          )}
        </div>

        {/* Histórico de Manutenções / Ordens de Serviço */}
        <div className="mt-6">
          <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
            <Wrench className="h-4 w-4" /> Ordens de Serviço & Manutenção
          </h3>
          {equipment.serviceOrders && equipment.serviceOrders.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">O.S.</th>
                    <th className="px-4 py-2.5">Título / Serviço</th>
                    <th className="px-4 py-2.5">Abertura</th>
                    <th className="px-4 py-2.5">Custo (R$)</th>
                    <th className="px-4 py-2.5">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {equipment.serviceOrders.map((so) => (
                    <tr key={so.id} className="hover:bg-muted/30">
                      <td className="px-4 py-2.5 font-medium">{so.code}</td>
                      <td className="px-4 py-2.5 font-medium">{so.title}</td>
                      <td className="px-4 py-2.5 text-xs text-muted-foreground">
                        {formatDate(so.openedAt)}
                      </td>
                      <td className="px-4 py-2.5 font-medium">{currency(so.cost)}</td>
                      <td className="px-4 py-2.5">
                        <Badge tone={so.status === "DONE" ? "green" : "red"}>{so.status}</Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground">
              Nenhuma ordem de serviço ou manutenção registrada para este ativo.
            </div>
          )}
        </div>

        <div className="mt-6 flex justify-end border-t pt-4">
          <Button variant="secondary" onClick={onClose}>
            Fechar Ficha Técnica
          </Button>
        </div>
      </Card>
    </div>,
    document.body
  );
}
