"use client";

import {
  Calendar,
  CheckCircle2,
  Clock,
  DollarSign,
  Edit,
  FileText,
  Mail,
  Package,
  Phone,
  Printer,
  Receipt,
  Trash2,
  Truck,
  User,
  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 { Rental, RentalStatus } from "@/types/rental";

interface RentalDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  rental: Rental | null;
  onEdit: (rental: Rental) => void;
  onDelete: (id: string) => void;
  onUpdateStatus: (id: string, newStatus: RentalStatus) => void;
}

export function RentalDetailModal({
  isOpen,
  onClose,
  rental,
  onEdit,
  onDelete,
  onUpdateStatus,
}: RentalDetailModalProps) {
  const [mounted, setMounted] = useState(false);

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

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

  const renderStatusBadge = (status: RentalStatus) => {
    switch (status) {
      case "IN_PROGRESS":
        return <Badge tone="blue">Em Andamento</Badge>;
      case "QUOTE":
        return <Badge tone="blue">Orçamento</Badge>;
      case "RESERVED":
        return <Badge tone="blue">Reservado</Badge>;
      case "FINISHED":
        return <Badge tone="green">Concluído</Badge>;
      case "CANCELED":
        return <Badge tone="red">Cancelado</Badge>;
      default:
        return <Badge tone="blue">{status}</Badge>;
    }
  };

  const handlePrintContract = () => {
    window.print();
  };

  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 do Contrato */}
        <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">
              <FileText className="h-7 w-7 text-primary" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-2xl font-bold font-mono">{rental.code}</h2>
                {renderStatusBadge(rental.status)}
              </div>
              <p className="text-sm text-muted-foreground flex items-center gap-2 mt-0.5">
                <span>Cliente: <strong className="text-foreground">{rental.customer?.name}</strong></span>
                <span>•</span>
                <span>{rental.customer?.document}</span>
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Button variant="secondary" size="sm" onClick={handlePrintContract} title="Imprimir Contrato">
              <Printer className="mr-1.5 h-4 w-4" /> PDF / Imprimir
            </Button>
            <Button variant="secondary" size="sm" onClick={() => onEdit(rental)}>
              <Edit className="mr-1.5 h-4 w-4" /> Editar
            </Button>

            {/* Alternar Status Rápido */}
            <select
              value={rental.status}
              onChange={(e) => onUpdateStatus(rental.id, e.target.value as RentalStatus)}
              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="QUOTE">Orçamento</option>
              <option value="RESERVED">Reservado</option>
              <option value="IN_PROGRESS">Em Andamento</option>
              <option value="FINISHED">Concluído</option>
              <option value="CANCELED">Cancelado</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 o contrato ${rental.code}?`)) {
                  onDelete(rental.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>

        {/* Vigência e Operador */}
        <div className="mt-5 grid gap-4 sm:grid-cols-3">
          <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">
              <Calendar className="h-4 w-4 text-blue-500" /> Período do Contrato
            </p>
            <p className="mt-2 text-sm font-bold text-foreground">
              {formatDate(rental.startDate)} até {formatDate(rental.endDate)}
            </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">
              <User className="h-4 w-4 text-purple-500" /> Operador Responsável
            </p>
            <p className="mt-2 text-sm font-bold text-foreground">
              {rental.operator || "Não informado"}
            </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-emerald-500" /> Valor Total do Contrato
            </p>
            <p className="mt-2 text-xl font-bold text-emerald-600 dark:text-emerald-400">
              {currency(rental.total)}
            </p>
          </div>
        </div>

        {/* Equipamentos Locados */}
        <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 Inclusos no Contrato
          </h3>

          {rental.items && rental.items.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</th>
                    <th className="px-4 py-2.5">Equipamento / Modelo</th>
                    <th className="px-4 py-2.5">Qtd</th>
                    <th className="px-4 py-2.5">Diária</th>
                    <th className="px-4 py-2.5 text-right">Subtotal</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {rental.items.map((item) => (
                    <tr key={item.id} className="hover:bg-muted/30">
                      <td className="px-4 py-2.5 font-mono font-medium">
                        {item.equipment?.code || "EQ-100"}
                      </td>
                      <td className="px-4 py-2.5 font-medium">
                        {item.equipment
                          ? `${item.equipment.brand} ${item.equipment.model}`
                          : "Equipamento Industrial"}
                      </td>
                      <td className="px-4 py-2.5 font-medium">{item.quantity} un</td>
                      <td className="px-4 py-2.5 font-medium">{currency(item.dailyRate)}/dia</td>
                      <td className="px-4 py-2.5 font-bold text-right">{currency(item.total)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground">
              Nenhum equipamento registrado neste contrato.
            </div>
          )}
        </div>

        {/* Detalhamento Financeiro */}
        <div className="mt-6 rounded-xl border bg-card p-4 space-y-2 text-sm">
          <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-3">
            Composição de Valores
          </h3>

          <div className="flex justify-between text-muted-foreground">
            <span>Subtotal de Locação:</span>
            <span>{currency(rental.subtotal)}</span>
          </div>
          {Number(rental.freight) > 0 && (
            <div className="flex justify-between text-muted-foreground">
              <span>Frete / Mobilização (+):</span>
              <span>{currency(rental.freight)}</span>
            </div>
          )}
          {Number(rental.discount) > 0 && (
            <div className="flex justify-between text-muted-foreground">
              <span>Desconto Comercial (-):</span>
              <span className="text-emerald-600">-{currency(rental.discount)}</span>
            </div>
          )}
          <div className="flex justify-between border-t pt-2 font-bold text-base text-foreground">
            <span>Valor Total da Locação:</span>
            <span className="text-primary">{currency(rental.total)}</span>
          </div>

          {Number(rental.depositAmount || 0) > 0 && (
            <>
              <div className="flex justify-between text-emerald-600 font-medium pt-2 border-t border-dashed">
                <span>
                  {rental.status === "QUOTE"
                    ? "Sinal / Entrada (Previsto):"
                    : "Sinal / Entrada (Acordado):"}
                </span>
                <span>-{currency(rental.depositAmount)}</span>
              </div>
              <div className="flex justify-between text-foreground font-semibold">
                <span>Saldo Restante a Pagar:</span>
                <span>{currency(Math.max(Number(rental.total) - Number(rental.depositAmount || 0), 0))}</span>
              </div>
            </>
          )}
        </div>

        {/* Detalhamento de Parcelas & Condições de Pagamento */}
        {rental.receivables && rental.receivables.length > 0 && (
          <div className="mt-6 space-y-3">
            <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              Condições de Pagamento & Lançamentos Financeiros
            </h3>
            <div className="overflow-hidden rounded-xl border bg-card text-xs shadow-xs">
              <table className="w-full text-left">
                <thead className="border-b bg-muted/50 font-semibold text-muted-foreground">
                  <tr>
                    <th className="px-4 py-2.5">Descrição</th>
                    <th className="px-4 py-2.5">Vencimento</th>
                    <th className="px-4 py-2.5">Valor</th>
                    <th className="px-4 py-2.5 text-right">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {rental.receivables.map((rec) => (
                    <tr key={rec.id} className="hover:bg-muted/30">
                      <td className="px-4 py-2.5 font-medium">{rec.description}</td>
                      <td className="px-4 py-2.5 text-muted-foreground">{formatDate(rec.dueDate)}</td>
                      <td className="px-4 py-2.5 font-bold">{currency(rec.amount)}</td>
                      <td className="px-4 py-2.5 text-right">
                        {rental.status === "QUOTE" ? (
                          <Badge tone="amber">Pendente (Proposta)</Badge>
                        ) : rec.status === "PAID" ? (
                          <Badge tone="green">Pago</Badge>
                        ) : rec.status === "OVERDUE" ? (
                          <Badge tone="red">Em Atraso</Badge>
                        ) : (
                          <Badge tone="blue">A Vencer (Aberto)</Badge>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Observações */}
        {rental.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 do Contrato
            </h3>
            <p className="mt-1 text-sm text-foreground/90">{rental.notes}</p>
          </div>
        )}

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