"use client";

import {
  AlertTriangle,
  Building2,
  Calendar,
  CheckCircle2,
  Clock,
  CreditCard,
  Edit,
  FileText,
  Mail,
  MapPin,
  Phone,
  Receipt,
  Trash2,
  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 { Customer } from "@/types/customer";

interface CustomerDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  customer: Customer | null;
  onEdit: (customer: Customer) => void;
  onDelete: (id: string) => void;
  onToggleStatus: (id: string, currentStatus: Customer["status"]) => void;
  isLoading?: boolean;
}

export function CustomerDetailModal({
  isOpen,
  onClose,
  customer,
  onEdit,
  onDelete,
  onToggleStatus,
}: CustomerDetailModalProps) {
  const [mounted, setMounted] = useState(false);

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

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

  const getStatusBadge = (status: Customer["status"]) => {
    switch (status) {
      case "ACTIVE":
        return <Badge tone="green">Ativo</Badge>;
      case "DELINQUENT":
        return <Badge tone="red">Inadimplente</Badge>;
      case "INACTIVE":
        return <Badge tone="blue">Inativo</Badge>;
      default:
        return <Badge tone="blue">{status}</Badge>;
    }
  };

  const formattedAddress = [
    customer.street ? `${customer.street}, ${customer.number || "S/N"}` : null,
    customer.complement,
    customer.district,
    customer.city && customer.state ? `${customer.city} - ${customer.state}` : customer.city,
    customer.zipCode ? `CEP: ${customer.zipCode}` : null,
  ]
    .filter(Boolean)
    .join(" • ");

  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">
              {customer.type === "COMPANY" ? (
                <Building2 className="h-7 w-7 text-primary" />
              ) : (
                <User className="h-7 w-7 text-primary" />
              )}
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-2xl font-bold">{customer.name}</h2>
                {getStatusBadge(customer.status)}
              </div>
              <p className="text-sm text-muted-foreground flex items-center gap-2 mt-0.5">
                <span>{customer.type === "COMPANY" ? "Pessoa Jurídica" : "Pessoa Física"}</span>
                <span>•</span>
                <span>{customer.document}</span>
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Button variant="secondary" size="sm" onClick={() => onEdit(customer)}>
              <Edit className="mr-1.5 h-4 w-4" /> Editar
            </Button>
            <Button
              variant="secondary"
              size="sm"
              onClick={() => onToggleStatus(customer.id, customer.status)}
            >
              {customer.status === "ACTIVE" ? (
                <>
                  <AlertTriangle className="mr-1.5 h-4 w-4 text-rose-500" /> Inativar
                </>
              ) : (
                <>
                  <CheckCircle2 className="mr-1.5 h-4 w-4 text-emerald-500" /> Ativar
                </>
              )}
            </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 ${customer.name}?`)) {
                  onDelete(customer.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>

        {/* Resumo Rápido em Cards */}
        <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">
              <CreditCard className="h-4 w-4 text-purple-500" /> Limite de Crédito
            </p>
            <p className="mt-2 text-xl font-bold text-foreground">
              {currency(customer.creditLimit)}
            </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-blue-500" /> Histórico de Locações
            </p>
            <p className="mt-2 text-xl font-bold text-foreground">
              {customer._count?.rentals ?? customer.rentals?.length ?? 0} contratos
            </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">
              <Receipt className="h-4 w-4 text-emerald-500" /> Títulos Financeiros
            </p>
            <p className="mt-2 text-xl font-bold text-foreground">
              {customer._count?.receivables ?? customer.receivables?.length ?? 0} títulos
            </p>
          </div>
        </div>

        {/* Informações de Contato e Endereço */}
        <div className="mt-6 grid gap-6 md:grid-cols-2">
          {/* Contatos */}
          <div className="space-y-3 rounded-xl border p-4">
            <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
              <Phone className="h-4 w-4" /> Contatos & Responsável
            </h3>

            <div className="space-y-2 text-sm">
              <div className="flex items-center gap-2 text-muted-foreground">
                <Mail className="h-4 w-4 text-primary" />
                <span className="font-medium text-foreground">
                  {customer.email || "Não informado"}
                </span>
              </div>
              <div className="flex items-center gap-2 text-muted-foreground">
                <Phone className="h-4 w-4 text-primary" />
                <span className="font-medium text-foreground">
                  {customer.phone || customer.mobile || "Não informado"}
                </span>
                {customer.mobile && customer.phone && (
                  <span className="text-xs">({customer.mobile})</span>
                )}
              </div>
              {customer.contactName && (
                <div className="flex items-center gap-2 text-muted-foreground">
                  <User className="h-4 w-4 text-primary" />
                  <span>Contato Principal: </span>
                  <strong className="text-foreground">{customer.contactName}</strong>
                </div>
              )}
              <div className="flex items-center gap-2 text-muted-foreground text-xs pt-1">
                <Calendar className="h-3.5 w-3.5" />
                <span>
                  Cadastrado em: {new Date(customer.createdAt).toLocaleDateString("pt-BR")}
                </span>
              </div>
            </div>
          </div>

          {/* Endereço */}
          <div className="space-y-3 rounded-xl border p-4">
            <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
              <MapPin className="h-4 w-4" /> Endereço Cadastrado
            </h3>
            <p className="text-sm leading-relaxed text-foreground">
              {formattedAddress || "Nenhum endereço informado."}
            </p>
          </div>
        </div>

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

        {/* Histórico Recente de Locações */}
        <div className="mt-6">
          <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
            <Clock className="h-4 w-4" /> Locações Recentes
          </h3>
          {customer.rentals && customer.rentals.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">Período</th>
                    <th className="px-4 py-2.5">Valor Total</th>
                    <th className="px-4 py-2.5">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {customer.rentals.map((rental) => (
                    <tr key={rental.id} className="hover:bg-muted/30">
                      <td className="px-4 py-2.5 font-medium">{rental.code}</td>
                      <td className="px-4 py-2.5 text-xs text-muted-foreground">
                        {formatDate(rental.startDate)} até {formatDate(rental.endDate)}
                      </td>
                      <td className="px-4 py-2.5 font-medium">{currency(rental.total)}</td>
                      <td className="px-4 py-2.5">
                        <Badge tone="blue">{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 registrada para este cliente até o momento.
            </div>
          )}
        </div>

        {/* Títulos e Contas a Receber */}
        <div className="mt-6">
          <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
            <Receipt className="h-4 w-4" /> Contas a Receber / Títulos
          </h3>
          {customer.receivables && customer.receivables.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">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">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {customer.receivables.map((item) => (
                    <tr key={item.id} className="hover:bg-muted/30">
                      <td className="px-4 py-2.5 font-medium">{item.description}</td>
                      <td className="px-4 py-2.5 text-xs text-muted-foreground">
                        {formatDate(item.dueDate)}
                      </td>
                      <td className="px-4 py-2.5 font-medium">{currency(item.amount)}</td>
                      <td className="px-4 py-2.5">
                        <Badge tone={item.status === "OPEN" ? "blue" : item.status === "OVERDUE" ? "red" : "green"}>
                          {item.status}
                        </Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground">
              Nenhum título financeiro em aberto ou pendente.
            </div>
          )}
        </div>

        {/* Documentos Anexados */}
        {customer.documents && customer.documents.length > 0 && (
          <div className="mt-6">
            <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
              <FileText className="h-4 w-4" /> Documentos Anexados
            </h3>
            <div className="grid gap-2 sm:grid-cols-2">
              {customer.documents.map((doc) => (
                <div
                  key={doc.id}
                  className="flex items-center justify-between rounded-lg border p-3 text-sm hover:bg-muted/40"
                >
                  <div className="flex items-center gap-2 truncate">
                    <FileText className="h-4 w-4 text-primary shrink-0" />
                    <span className="truncate font-medium">{doc.name}</span>
                  </div>
                  <a
                    href={doc.fileUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex h-8 items-center justify-center rounded-md px-3 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground transition"
                  >
                    Visualizar
                  </a>
                </div>
              ))}
            </div>
          </div>
        )}

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