import React, { useState } from "react";
import { SaaSEmailNotification } from "../../types";
import { 
  Mail, 
  X, 
  Search, 
  CheckCircle2, 
  Clock, 
  Send, 
  Building2, 
  Eye, 
  Copy, 
  Check, 
  Tag, 
  Inbox,
  Filter,
  ExternalLink,
  ShieldCheck,
  RefreshCw
} from "lucide-react";

interface SaasEmailOutboxModalProps {
  isOpen: boolean;
  onClose: () => void;
  emails: SaaSEmailNotification[];
  onResendEmail?: (email: SaaSEmailNotification) => void;
  preselectedEmailId?: string;
}

export const SaasEmailOutboxModal: React.FC<SaasEmailOutboxModalProps> = ({
  isOpen,
  onClose,
  emails,
  onResendEmail,
  preselectedEmailId
}) => {
  const [searchQuery, setSearchQuery] = useState("");
  const [filterCategory, setFilterCategory] = useState<string>("ALL");
  const [selectedEmail, setSelectedEmail] = useState<SaaSEmailNotification | null>(() => {
    if (preselectedEmailId) {
      return emails.find(e => e.id === preselectedEmailId) || emails[0] || null;
    }
    return emails[0] || null;
  });
  const [copiedHtml, setCopiedHtml] = useState(false);
  const [resendSuccess, setResendSuccess] = useState(false);

  if (!isOpen) return null;

  const filteredEmails = emails.filter(email => {
    const matchSearch = 
      email.subject.toLowerCase().includes(searchQuery.toLowerCase()) ||
      email.recipientEmail.toLowerCase().includes(searchQuery.toLowerCase()) ||
      email.recipientName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      email.tenantName.toLowerCase().includes(searchQuery.toLowerCase());

    const matchCategory = filterCategory === "ALL" || email.category === filterCategory;
    return matchSearch && matchCategory;
  });

  const handleCopyHtml = () => {
    if (!selectedEmail) return;
    navigator.clipboard.writeText(selectedEmail.bodyHtml);
    setCopiedHtml(true);
    setTimeout(() => setCopiedHtml(false), 2000);
  };

  const handleResend = () => {
    if (!selectedEmail) return;
    if (onResendEmail) {
      onResendEmail(selectedEmail);
    }
    setResendSuccess(true);
    setTimeout(() => setResendSuccess(false), 2500);
  };

  const getCategoryBadge = (cat: SaaSEmailNotification['category']) => {
    switch (cat) {
      case 'OPERATIONAL_TICKET':
        return <span className="px-2 py-0.5 bg-sky-500/20 text-sky-300 border border-sky-500/40 rounded text-[10px] font-bold">Tiket Operasional</span>;
      case 'MEMBERSHIP_TRIAL':
        return <span className="px-2 py-0.5 bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 rounded text-[10px] font-bold">Trial 7 Hari</span>;
      case 'MEMBERSHIP_ACTIVE':
        return <span className="px-2 py-0.5 bg-blue-500/20 text-blue-300 border border-blue-500/40 rounded text-[10px] font-bold">Pelanggan Aktif</span>;
      case 'MEMBERSHIP_INACTIVE':
        return <span className="px-2 py-0.5 bg-amber-500/20 text-amber-300 border border-amber-500/40 rounded text-[10px] font-bold">Inaktif (1 Bulan)</span>;
      case 'IT_DOMAIN_PROVISIONING':
        return <span className="px-2 py-0.5 bg-indigo-500/20 text-indigo-300 border border-indigo-500/40 rounded text-[10px] font-bold">IT Provisioning</span>;
      case 'IT_DOMAIN_ACTIVE':
        return <span className="px-2 py-0.5 bg-teal-500/20 text-teal-300 border border-teal-500/40 rounded text-[10px] font-bold">IT Domain Live</span>;
      default:
        return <span className="px-2 py-0.5 bg-slate-700 text-slate-300 rounded text-[10px]">Email Notifikasi</span>;
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/85 backdrop-blur-md animate-in fade-in duration-200">
      <div className="bg-slate-900 border border-slate-700/80 rounded-2xl w-full max-w-6xl max-h-[90vh] flex flex-col shadow-2xl overflow-hidden text-slate-100">
        
        {/* Header */}
        <div className="px-6 py-4 bg-slate-800/80 border-b border-slate-700/70 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-sky-500 to-indigo-600 flex items-center justify-center text-white shadow-lg shadow-sky-500/20">
              <Mail className="w-5 h-5" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-base font-black tracking-tight text-white font-mono">
                  LOG & PUSAT NOTIFIKASI EMAIL KLIEN
                </h2>
                <span className="px-2 py-0.5 bg-sky-500/10 text-sky-400 border border-sky-500/30 text-[10px] font-mono font-bold rounded-full">
                  {emails.length} Email Terkirim
                </span>
              </div>
              <p className="text-xs text-slate-400">
                Riwayat otomatisasi surat elektronik untuk Tiket Operasional, Aktivasi Membership, dan Provisioning Domain IT.
              </p>
            </div>
          </div>

          <button
            onClick={onClose}
            className="p-2 hover:bg-slate-700 rounded-lg text-slate-400 hover:text-white transition-colors cursor-pointer"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content Layout: 2 Columns */}
        <div className="flex-1 flex flex-col md:flex-row overflow-hidden">
          
          {/* Left Column: Email List */}
          <div className="w-full md:w-5/12 border-r border-slate-800 flex flex-col bg-slate-950/50">
            {/* Search & Filters */}
            <div className="p-3 border-b border-slate-800 space-y-2">
              <div className="relative">
                <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <input
                  type="text"
                  placeholder="Cari subjek, email, tenant..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-8 pr-3 py-1.5 bg-slate-900 border border-slate-700/80 rounded-lg text-xs text-slate-100 placeholder-slate-500 focus:outline-none focus:border-sky-500 font-mono"
                />
              </div>

              <div className="flex items-center gap-1 overflow-x-auto pb-1 text-[11px] font-mono">
                <button
                  onClick={() => setFilterCategory("ALL")}
                  className={`px-2.5 py-1 rounded-md transition-all whitespace-nowrap cursor-pointer ${
                    filterCategory === "ALL" 
                      ? "bg-sky-500 text-slate-950 font-black shadow" 
                      : "bg-slate-800 text-slate-300 hover:bg-slate-700"
                  }`}
                >
                  Semua ({emails.length})
                </button>
                <button
                  onClick={() => setFilterCategory("OPERATIONAL_TICKET")}
                  className={`px-2 py-1 rounded-md transition-all whitespace-nowrap cursor-pointer ${
                    filterCategory === "OPERATIONAL_TICKET" 
                      ? "bg-sky-500 text-slate-950 font-black" 
                      : "bg-slate-800/80 text-sky-400 hover:bg-slate-700"
                  }`}
                >
                  Tiket
                </button>
                <button
                  onClick={() => setFilterCategory("MEMBERSHIP_ACTIVE")}
                  className={`px-2 py-1 rounded-md transition-all whitespace-nowrap cursor-pointer ${
                    filterCategory === "MEMBERSHIP_ACTIVE" || filterCategory === "MEMBERSHIP_TRIAL" || filterCategory === "MEMBERSHIP_INACTIVE"
                      ? "bg-emerald-500 text-slate-950 font-black" 
                      : "bg-slate-800/80 text-emerald-400 hover:bg-slate-700"
                  }`}
                >
                  Membership
                </button>
                <button
                  onClick={() => setFilterCategory("IT_DOMAIN_PROVISIONING")}
                  className={`px-2 py-1 rounded-md transition-all whitespace-nowrap cursor-pointer ${
                    filterCategory === "IT_DOMAIN_PROVISIONING" || filterCategory === "IT_DOMAIN_ACTIVE"
                      ? "bg-indigo-500 text-white font-black" 
                      : "bg-slate-800/80 text-indigo-400 hover:bg-slate-700"
                  }`}
                >
                  IT Domain
                </button>
              </div>
            </div>

            {/* Email Items Scrollable */}
            <div className="flex-1 overflow-y-auto divide-y divide-slate-800/60 p-2 space-y-1">
              {filteredEmails.length === 0 ? (
                <div className="p-8 text-center text-slate-500 font-mono text-xs">
                  <Inbox className="w-8 h-8 mx-auto mb-2 opacity-40" />
                  Tidak ada email yang cocok dengan filter.
                </div>
              ) : (
                filteredEmails.map((item) => {
                  const isSelected = selectedEmail?.id === item.id;
                  return (
                    <div
                      key={item.id}
                      onClick={() => setSelectedEmail(item)}
                      className={`p-3 rounded-xl cursor-pointer transition-all ${
                        isSelected 
                          ? "bg-slate-800 border border-sky-500/50 shadow-md" 
                          : "hover:bg-slate-900/80 border border-transparent"
                      }`}
                    >
                      <div className="flex items-center justify-between gap-2 mb-1">
                        <span className="font-mono text-[10px] font-bold text-slate-400 truncate max-w-[140px]">
                          {item.tenantName}
                        </span>
                        <span className="font-mono text-[9px] text-slate-500 flex items-center gap-1 shrink-0">
                          <Clock className="w-2.5 h-2.5" />
                          {item.sentAt}
                        </span>
                      </div>

                      <div className="text-xs font-bold text-slate-100 line-clamp-1 mb-1">
                        {item.subject}
                      </div>

                      <p className="text-[11px] text-slate-400 line-clamp-2 mb-2 leading-relaxed">
                        {item.previewSnippet}
                      </p>

                      <div className="flex items-center justify-between pt-1 border-t border-slate-800/50">
                        {getCategoryBadge(item.category)}
                        <span className="font-mono text-[10px] text-emerald-400 flex items-center gap-1">
                          <CheckCircle2 className="w-3 h-3" />
                          {item.deliveryStatus}
                        </span>
                      </div>
                    </div>
                  );
                })
              )}
            </div>
          </div>

          {/* Right Column: Email Body Preview */}
          <div className="w-full md:w-7/12 flex flex-col bg-slate-900">
            {selectedEmail ? (
              <div className="flex-1 flex flex-col h-full overflow-hidden">
                {/* Header Preview Bar */}
                <div className="p-4 border-b border-slate-800 bg-slate-850/60 flex flex-wrap items-center justify-between gap-3">
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      {getCategoryBadge(selectedEmail.category)}
                      <span className="text-xs font-mono text-slate-400">
                        Modul: <strong className="text-white">{selectedEmail.senderModule}</strong>
                      </span>
                    </div>
                    <h3 className="text-sm font-bold text-white">
                      {selectedEmail.subject}
                    </h3>
                    <div className="text-xs text-slate-300 font-mono flex flex-wrap items-center gap-3">
                      <span>Kepada: <strong className="text-sky-300">{selectedEmail.recipientName}</strong> &lt;{selectedEmail.recipientEmail}&gt;</span>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <button
                      onClick={handleCopyHtml}
                      className="px-2.5 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-mono rounded-lg border border-slate-700 flex items-center gap-1.5 transition-all cursor-pointer"
                      title="Salin Kode HTML Surat"
                    >
                      {copiedHtml ? <Check className="w-3.5 h-3.5 text-emerald-400" /> : <Copy className="w-3.5 h-3.5" />}
                      <span>{copiedHtml ? "Tersalin!" : "Copy HTML"}</span>
                    </button>

                    <button
                      onClick={handleResend}
                      className="px-3 py-1.5 bg-sky-600 hover:bg-sky-500 text-white font-bold text-xs font-mono rounded-lg shadow flex items-center gap-1.5 transition-all cursor-pointer"
                    >
                      <Send className="w-3.5 h-3.5" />
                      <span>{resendSuccess ? "Terkirim Ulang!" : "Kirim Ulang Email"}</span>
                    </button>
                  </div>
                </div>

                {/* Email Rendering Box */}
                <div className="flex-1 overflow-y-auto p-4 sm:p-6 bg-slate-950/60">
                  <div className="bg-white rounded-xl shadow-lg p-2 max-w-2xl mx-auto overflow-hidden">
                    <div 
                      className="email-render-container"
                      dangerouslySetInnerHTML={{ __html: selectedEmail.bodyHtml }} 
                    />
                  </div>
                </div>

                {/* Footer Meta */}
                <div className="p-3 bg-slate-950 border-t border-slate-800 text-[11px] font-mono text-slate-400 flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <ShieldCheck className="w-3.5 h-3.5 text-emerald-400" />
                    <span>Terkirim otomatis melalui SMTP Secure Relay Median Cloud</span>
                  </div>
                  <span>Waktu: {selectedEmail.sentAt}</span>
                </div>
              </div>
            ) : (
              <div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-slate-500">
                <Mail className="w-12 h-12 mb-3 opacity-30" />
                <p className="font-mono text-xs">Pilih salah satu email di daftar sebelah kiri untuk melihat preview dokumen resmi.</p>
              </div>
            )}
          </div>

        </div>

      </div>
    </div>
  );
};
