"use client";

/**
 * Email preview modal — renders a sent report's HTML content in a
 * sandboxed iframe. Offers re-send and download actions.
 */

import { useState } from "react";
import { X, Send, Download, Loader2 } from "lucide-react";

export interface SentReportDto {
  id: string;
  subject: string;
  recipients: string[];
  status: string;
  error: string | null;
  sentAt: string;
  scheduleId: string;
  htmlContent?: string;
}

interface Props {
  report: SentReportDto | null;
  onClose: () => void;
}

export default function EmailPreviewModal({ report, onClose }: Props) {
  const [resending, setResending] = useState(false);
  const [toast, setToast] = useState<string | null>(null);

  if (!report) return null;

  async function resend() {
    setResending(true);
    try {
      const res = await fetch(`/api/email-reports/send-now/${report!.scheduleId}`, { method: "POST" });
      if (!res.ok) throw new Error("Re-send failed");
      setToast("Sent!"); setTimeout(() => setToast(null), 2000);
    } catch {
      setToast("Failed to re-send");
      setTimeout(() => setToast(null), 2000);
    } finally { setResending(false); }
  }

  function downloadHtml() {
    if (!report?.htmlContent) return;
    const blob = new Blob([report.htmlContent], { type: "text/html;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `${report.subject.replace(/[^a-zA-Z0-9]+/g, "-").toLowerCase()}.html`;
    document.body.appendChild(a); a.click(); a.remove();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div className="flex items-center justify-between border-b border-slate-200 px-5 py-4">
          <div className="min-w-0 flex-1">
            <h2 className="font-bold text-slate-900 truncate">{report.subject}</h2>
            <p className="text-[11px] text-slate-500 mt-0.5">
              Sent to {report.recipients.join(", ")} · {new Date(report.sentAt).toLocaleString("en-US", { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" })}
            </p>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-500 shrink-0 ml-3"><X className="w-4 h-4" /></button>
        </div>

        {/* Iframe preview */}
        <div className="flex-1 overflow-hidden bg-slate-100 p-3">
          {report.htmlContent ? (
            <iframe
              srcDoc={report.htmlContent}
              sandbox="allow-same-origin"
              className="w-full h-full rounded-lg border border-slate-200 bg-white"
              title="Email preview"
            />
          ) : (
            <div className="flex items-center justify-center h-full text-sm text-slate-400">No email content available.</div>
          )}
        </div>

        {/* Actions */}
        <div className="flex items-center gap-2 border-t border-slate-200 px-5 py-3 bg-slate-50">
          <button onClick={resend} disabled={resending} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-brand-600 text-white text-[11px] font-semibold hover:bg-brand-700 disabled:opacity-60">
            {resending ? <Loader2 className="w-3 h-3 animate-spin" /> : <Send className="w-3 h-3" />}
            Re-send
          </button>
          <button onClick={downloadHtml} disabled={!report.htmlContent} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 text-[11px] font-semibold text-slate-600 hover:bg-white disabled:opacity-50">
            <Download className="w-3 h-3" /> Download HTML
          </button>
          {toast && <span className="ml-auto text-[11px] font-semibold text-green-600">{toast}</span>}
        </div>
      </div>
    </div>
  );
}
