"use client";

import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { CheckCircle2, Circle, Download, Loader2, MousePointerClick, RotateCcw } from "lucide-react";

import { Card, CardContent } from "@/shared/components/ui/card";
import { Badge } from "@/shared/components/ui/badge";
import { formatRelativeTime } from "@/shared/utils/relative-time";
import { downloadCsv } from "@/shared/utils/download-csv";
import { resendCampaignToContactAction } from "@/modules/campaigns/actions/resend-campaign-to-contact-action";
import { getContactEmailHistoryAction } from "../actions/get-contact-email-history-action";
import { exportContactEmailHistoryAction } from "../actions/export-contact-email-history-action";

type StatusFilter = "all" | "opened" | "unopened";

interface EmailHistoryItem {
  logId: string;
  campaignId: string;
  subject: string;
  senderName: string;
  senderEmail: string;
  contactEmail: string;
  status: string;
  sentAt: string;
  preview: string;
  fullText: string;
  opened: boolean;
  openedAt: string | null;
  openCount: number;
  clickCount: number;
}

interface EmailHistoryResponse {
  items: EmailHistoryItem[];
  total: number;
  page: number;
  pageSize: number;
}

interface ContactEmailsTabProps {
  contactId: string;
  onTotalChange?: (total: number) => void;
}

const FILTER_OPTIONS: { value: StatusFilter; label: string }[] = [
  { value: "all", label: "Todos" },
  { value: "opened", label: "Abertos" },
  { value: "unopened", label: "Não abertos" },
];

const PAGE_SIZE = 20;

export function ContactEmailsTab({ contactId, onTotalChange }: ContactEmailsTabProps) {
  const [items, setItems] = useState<EmailHistoryItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState<StatusFilter>("all");
  const [isLoading, setIsLoading] = useState(true);
  const [expandedLogId, setExpandedLogId] = useState<string | null>(null);
  const [resendingLogId, setResendingLogId] = useState<string | null>(null);
  const [isExporting, setIsExporting] = useState(false);

  const load = useCallback(() => {
    setIsLoading(true);
    const statusFilter = status !== "all" ? status : undefined;

    getContactEmailHistoryAction(contactId, page, PAGE_SIZE, statusFilter)
      .then((data: EmailHistoryResponse) => {
        setItems(data.items ?? []);
        setTotal(data.total ?? 0);
        onTotalChange?.(data.total ?? 0);
      })
      .catch(() => {})
      .finally(() => setIsLoading(false));
  }, [contactId, page, status, onTotalChange]);

  useEffect(() => {
    load();
  }, [load]);

  function handleFilterChange(next: StatusFilter) {
    setStatus(next);
    setPage(1);
  }

  async function handleResend(logId: string) {
    setResendingLogId(logId);
    try {
      await resendCampaignToContactAction(logId, contactId);
      toast.success("E-mail reenviado com sucesso.");
      load();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Não foi possível reenviar o e-mail");
    } finally {
      setResendingLogId(null);
    }
  }

  async function handleExport() {
    setIsExporting(true);
    try {
      const { csvContent, fileName } = await exportContactEmailHistoryAction(
        contactId,
        status !== "all" ? status : undefined
      );
      downloadCsv(csvContent, fileName);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Não foi possível exportar o histórico");
    } finally {
      setIsExporting(false);
    }
  }

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  return (
    <div className="space-y-4">
      {/* Barra de Filtros e Exportação */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div className="inline-flex rounded-lg bg-muted/40 p-1 gap-1 w-fit">
          {FILTER_OPTIONS.map((option) => (
            <button
              key={option.value}
              type="button"
              onClick={() => handleFilterChange(option.value)}
              className={`text-xs font-semibold h-7 px-3.5 rounded-md transition-all cursor-pointer ${
                status === option.value
                  ? "bg-[#635BFF] text-white shadow-xs"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              {option.label}
            </button>
          ))}
        </div>

        <button
          type="button"
          onClick={handleExport}
          disabled={isExporting}
          className="inline-flex items-center gap-1.5 text-xs font-semibold h-8 px-3 rounded-lg border border-border/80 text-foreground hover:bg-muted/50 transition-colors w-fit disabled:opacity-50"
        >
          <Download className="w-3.5 h-3.5" />
          Exportar CSV
        </button>
      </div>

      {isLoading ? (
        <div className="p-8 text-center text-xs text-muted-foreground">Carregando e-mails...</div>
      ) : items.length === 0 ? (
        <Card className="bg-card border border-border rounded-xl shadow-xs">
          <CardContent className="p-8 text-center space-y-2">
            <p className="text-xs sm:text-sm text-muted-foreground">Nenhum e-mail encontrado para esse filtro.</p>
          </CardContent>
        </Card>
      ) : (
        /* Lista de E-mails em formato de Cards conforme Print 1 de referência */
        <div className="space-y-4">
          {items.map((item) => {
            const isExpanded = expandedLogId === item.logId;
            const sentDate = new Date(item.sentAt);
            const dateStr = sentDate.toLocaleDateString("pt-BR", { day: "2-digit", month: "2-digit", year: "numeric" });
            const timeStr = sentDate.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" });

            return (
              <Card key={item.logId} className="bg-card border border-border rounded-xl shadow-xs overflow-hidden">
                <CardContent className="p-4 sm:p-5 space-y-3">
                  {/* Linha superior: De ... para ... + Botão Reenviar */}
                  <div className="flex items-start justify-between gap-3">
                    <div className="space-y-0.5">
                      <p className="text-xs text-muted-foreground font-medium">
                        De <span className="font-semibold text-foreground">{item.senderEmail}</span> para{" "}
                        <a href={`mailto:${item.contactEmail}`} className="text-[#635BFF] font-semibold hover:underline">
                          {item.contactEmail}
                        </a>
                      </p>
                      <p className="text-[11px] text-muted-foreground">
                        {dateStr} {timeStr} ({formatRelativeTime(item.sentAt)})
                      </p>
                    </div>

                    <button
                      type="button"
                      onClick={() => handleResend(item.logId)}
                      disabled={resendingLogId === item.logId}
                      title="Reenviar e-mail"
                      className="p-1.5 rounded-lg border border-border text-muted-foreground hover:text-[#635BFF] hover:bg-muted/50 disabled:opacity-50 transition-colors shrink-0 cursor-pointer"
                    >
                      {resendingLogId === item.logId ? (
                        <Loader2 className="w-4 h-4 animate-spin text-[#635BFF]" />
                      ) : (
                        <RotateCcw className="w-4 h-4" />
                      )}
                    </button>
                  </div>

                  {/* Assunto do E-mail */}
                  <div className="flex items-center gap-2 pt-0.5">
                    <span className="w-2.5 h-2.5 rounded-xs bg-[#635BFF] shrink-0" />
                    <h4 className="text-sm font-bold text-foreground leading-snug">{item.subject}</h4>
                  </div>

                  {/* Preview / Corpo do E-mail em caixa compacta */}
                  {(() => {
                    const shortPreview = item.preview.length > 160 ? item.preview.slice(0, 160) + "..." : item.preview;
                    const canExpand = item.fullText.length > 160 || item.preview.length > 160;

                    return (
                      <>
                        <div
                          className={`bg-muted/30 border border-border/50 rounded-lg p-3.5 text-xs text-foreground/90 leading-relaxed font-sans whitespace-pre-line ${
                            isExpanded ? "max-h-80 overflow-y-auto shadow-inner" : "max-h-24 overflow-hidden"
                          }`}
                        >
                          {isExpanded ? item.fullText : shortPreview}
                        </div>

                        {canExpand && (
                          <button
                            type="button"
                            onClick={() => setExpandedLogId(isExpanded ? null : item.logId)}
                            className="text-xs font-bold text-[#635BFF] hover:underline cursor-pointer inline-block pt-0.5"
                          >
                            {isExpanded ? "...Ler menos" : "...Ler mais"}
                          </button>
                        )}
                      </>
                    );
                  })()}

                  {/* Status no rodapé do card */}
                  <div className="flex items-center justify-between gap-2 pt-2 border-t border-border/40 text-xs">
                    <div className="flex items-center gap-2 flex-wrap">
                      {item.opened ? (
                        <Badge
                          variant="outline"
                          className="border-emerald-200 text-emerald-700 bg-emerald-50 gap-1 text-[11px] font-medium"
                          title={`${item.openCount} abertura${item.openCount === 1 ? "" : "s"}${
                            item.openedAt ? ` — primeira em ${new Date(item.openedAt).toLocaleString("pt-BR")}` : ""
                          }`}
                        >
                          <CheckCircle2 className="w-3 h-3 text-emerald-600" />
                          {item.openCount > 1 ? `Aberto ${item.openCount}x` : "Aberto"}
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="border-border text-muted-foreground bg-muted/30 gap-1 text-[11px] font-medium">
                          <Circle className="w-3 h-3 text-muted-foreground" />
                          Não aberto
                        </Badge>
                      )}
                      {item.clickCount > 0 && (
                        <Badge variant="outline" className="border-primary/30 text-primary bg-primary/5 gap-1 text-[11px] font-medium">
                          <MousePointerClick className="w-3 h-3" />
                          {item.clickCount} clique{item.clickCount === 1 ? "" : "s"}
                        </Badge>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* Paginação */}
      {!isLoading && items.length > 0 && (
        <div className="flex items-center justify-between pt-2">
          <button
            type="button"
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="text-xs font-semibold h-8 px-3 rounded-lg border border-border text-foreground hover:bg-muted/50 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          >
            Anterior
          </button>
          <span className="text-xs text-muted-foreground">
            Página {page} de {totalPages}
          </span>
          <button
            type="button"
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            disabled={page >= totalPages}
            className="text-xs font-semibold h-8 px-3 rounded-lg border border-border text-foreground hover:bg-muted/50 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          >
            Próxima
          </button>
        </div>
      )}
    </div>
  );
}
