import React, { useState, useEffect } from "react";
import { 
  EmailGatewayDispatchedRecord, 
  getEmailGatewayLogs, 
  clearEmailGatewayLogs, 
  markEmailLogAsRead 
} from "../services/emailGatewayService";
import { 
  Mail, 
  X, 
  CheckCircle2, 
  Clock, 
  Send, 
  Trash2, 
  ShieldCheck, 
  ExternalLink, 
  User, 
  Building2, 
  AlertTriangle,
  RefreshCw,
  Search,
  Eye
} from "lucide-react";

interface EmailGatewayDrawerModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedEmailId?: string;
}

export const EmailGatewayDrawerModal: React.FC<EmailGatewayDrawerModalProps> = ({
  isOpen,
  onClose,
  selectedEmailId
}) => {
  const [logs, setLogs] = useState<EmailGatewayDispatchedRecord[]>([]);
  const [selectedRecord, setSelectedRecord] = useState<EmailGatewayDispatchedRecord | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterCategory, setFilterCategory] = useState<string>("ALL");

  const loadLogs = () => {
    const list = getEmailGatewayLogs();
    setLogs(list);
    if (selectedEmailId) {
      const found = list.find(l => l.id === selectedEmailId);
      if (found) setSelectedRecord(found);
    } else if (list.length > 0 && !selectedRecord) {
      setSelectedRecord(list[0]);
    }
  };

  useEffect(() => {
    if (isOpen) {
      loadLogs();
    }
  }, [isOpen, selectedEmailId]);

  useEffect(() => {
    const handleUpdate = () => {
      loadLogs();
    };
    window.addEventListener("ems_email_gateway_updated", handleUpdate);
    return () => window.removeEventListener("ems_email_gateway_updated", handleUpdate);
  }, []);

  if (!isOpen) return null;

  const filteredLogs = logs.filter(item => {
    const matchesSearch = 
      item.payload.subject.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.payload.recipientName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.messageId.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCat = filterCategory === "ALL" || item.payload.category === filterCategory;
    return matchesSearch && matchesCat;
  });

  const handleSelect = (rec: EmailGatewayDispatchedRecord) => {
    setSelectedRecord(rec);
    if (!rec.read) {
      markEmailLogAsRead(rec.id);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4 animate-in fade-in duration-200">
      <div className="bg-slate-900 border border-slate-700 rounded-2xl w-full max-w-6xl h-[88vh] flex flex-col shadow-2xl overflow-hidden">
        
        {/* MODAL HEADER */}
        <div className="px-6 py-4 bg-slate-800/80 border-b border-slate-700 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2.5 bg-sky-500/20 text-sky-400 rounded-xl border border-sky-500/30">
              <Mail className="w-5 h-5" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-lg font-bold text-white font-mono tracking-wide">
                  Enterprise Email Gateway Dispatch Logs
                </h2>
                <span className="px-2 py-0.5 text-[11px] font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 rounded-full flex items-center gap-1">
                  <ShieldCheck className="w-3 h-3" /> Live SMTP API
                </span>
              </div>
              <p className="text-xs text-slate-400">
                Log simulasi panggilan API & pengiriman notifikasi surat elektronik otomatis ke Direktur & Manager
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <button
              onClick={() => {
                if (window.confirm("Hapus semua riwayat log email gateway?")) {
                  clearEmailGatewayLogs();
                  setSelectedRecord(null);
                }
              }}
              className="px-3 py-1.5 text-xs font-mono text-slate-400 hover:text-red-400 hover:bg-red-500/10 rounded-lg transition-all flex items-center gap-1.5 border border-slate-700"
              title="Bersihkan Log"
            >
              <Trash2 className="w-3.5 h-3.5" />
              <span>Hapus Log</span>
            </button>

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

        {/* MODAL BODY (TWO COLUMN: LIST + PREVIEW) */}
        <div className="flex-1 grid grid-cols-12 overflow-hidden">
          
          {/* LEFT LIST PANEL */}
          <div className="col-span-5 border-r border-slate-800 flex flex-col bg-slate-950/50">
            
            {/* SEARCH & FILTER BAR */}
            <div className="p-3 border-b border-slate-800 flex flex-col gap-2">
              <div className="relative">
                <Search className="w-4 h-4 text-slate-400 absolute left-3 top-2.5" />
                <input
                  type="text"
                  placeholder="Cari penerima, subjek, atau message ID..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-9 pr-3 py-1.5 text-xs bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:border-sky-500 font-mono"
                />
              </div>

              <div className="flex items-center gap-1.5 overflow-x-auto pb-1 text-[11px] font-mono">
                <button
                  onClick={() => setFilterCategory("ALL")}
                  className={`px-2.5 py-1 rounded-md transition-all ${
                    filterCategory === "ALL"
                      ? "bg-sky-500 text-white font-bold"
                      : "bg-slate-800 text-slate-400 hover:text-white"
                  }`}
                >
                  Semua ({logs.length})
                </button>
                <button
                  onClick={() => setFilterCategory("WORKFLOW_SUBMISSION")}
                  className={`px-2.5 py-1 rounded-md transition-all whitespace-nowrap ${
                    filterCategory === "WORKFLOW_SUBMISSION"
                      ? "bg-sky-500 text-white font-bold"
                      : "bg-slate-800 text-slate-400 hover:text-white"
                  }`}
                >
                  Workflow
                </button>
                <button
                  onClick={() => setFilterCategory("UMK_REQUEST_SUBMISSION")}
                  className={`px-2.5 py-1 rounded-md transition-all whitespace-nowrap ${
                    filterCategory === "UMK_REQUEST_SUBMISSION"
                      ? "bg-emerald-600 text-white font-bold"
                      : "bg-slate-800 text-slate-400 hover:text-white"
                  }`}
                >
                  UMK GA
                </button>
              </div>
            </div>

            {/* EMAILS LIST */}
            <div className="flex-1 overflow-y-auto divide-y divide-slate-800/60 p-2 space-y-1">
              {filteredLogs.length === 0 ? (
                <div className="p-8 text-center text-slate-500 text-xs flex flex-col items-center justify-center h-full">
                  <Mail className="w-8 h-8 text-slate-600 mb-2" />
                  <span>Belum ada notifikasi email yang terkirim.</span>
                  <span className="text-[11px] text-slate-600 mt-1">Ajukan Workflow atau UMK baru untuk memicu pengiriman API.</span>
                </div>
              ) : (
                filteredLogs.map((rec) => {
                  const isSelected = selectedRecord?.id === rec.id;
                  const isUmk = rec.payload.category.includes("UMK");
                  
                  return (
                    <div
                      key={rec.id}
                      onClick={() => handleSelect(rec)}
                      className={`p-3 rounded-xl cursor-pointer transition-all border ${
                        isSelected 
                          ? "bg-sky-950/40 border-sky-500/50 shadow-md"
                          : "bg-slate-900/60 border-slate-800/80 hover:bg-slate-800/50 hover:border-slate-700"
                      }`}
                    >
                      <div className="flex items-center justify-between mb-1.5">
                        <span className={`text-[10px] font-bold px-2 py-0.5 rounded uppercase font-mono ${
                          isUmk
                            ? "bg-emerald-500/20 text-emerald-300 border border-emerald-500/30"
                            : "bg-sky-500/20 text-sky-300 border border-sky-500/30"
                        }`}>
                          {isUmk ? "💼 UMK Kas Kecil" : "⚡ Workflow Direksi"}
                        </span>
                        
                        <span className="text-[10px] text-slate-400 font-mono flex items-center gap-1">
                          <Clock className="w-3 h-3 text-slate-500" />
                          {rec.latencyMs}ms
                        </span>
                      </div>

                      <h4 className="text-xs font-bold text-white line-clamp-1 mb-1">
                        {rec.payload.subject}
                      </h4>

                      <p className="text-[11px] text-slate-400 line-clamp-2 mb-2 font-mono">
                        {rec.payload.textSummary}
                      </p>

                      <div className="flex items-center justify-between text-[10px] text-slate-400 border-t border-slate-800/60 pt-1.5">
                        <span className="font-semibold text-slate-300">
                          Kepada: {rec.payload.recipientName}
                        </span>
                        <span className="text-emerald-400 flex items-center gap-1">
                          <CheckCircle2 className="w-3 h-3" /> Sent
                        </span>
                      </div>
                    </div>
                  );
                })
              )}
            </div>

          </div>

          {/* RIGHT DETAIL & PREVIEW PANEL */}
          <div className="col-span-7 flex flex-col bg-slate-900 overflow-y-auto">
            {selectedRecord ? (
              <div className="p-6 flex flex-col h-full">
                
                {/* METADATA BAR */}
                <div className="bg-slate-950 border border-slate-800 rounded-xl p-4 mb-4">
                  <div className="flex items-center justify-between pb-3 border-b border-slate-800 mb-3">
                    <div>
                      <span className="text-[10px] font-mono text-slate-400 block uppercase tracking-wider">
                        Status Pengiriman API Gateway
                      </span>
                      <div className="flex items-center gap-2 mt-0.5">
                        <span className="text-xs font-bold text-emerald-400 flex items-center gap-1 font-mono">
                          <CheckCircle2 className="w-3.5 h-3.5" /> 200 OK (DELIVERED)
                        </span>
                        <span className="text-slate-600">•</span>
                        <span className="text-xs text-slate-400 font-mono">
                          Latency: <strong className="text-sky-400">{selectedRecord.latencyMs} ms</strong>
                        </span>
                        <span className="text-slate-600">•</span>
                        <span className="text-xs text-slate-400 font-mono">
                          {selectedRecord.gatewayProvider}
                        </span>
                      </div>
                    </div>

                    <span className="text-[11px] text-slate-400 font-mono bg-slate-900 px-2.5 py-1 rounded border border-slate-800">
                      {selectedRecord.timestamp}
                    </span>
                  </div>

                  <div className="space-y-1.5 text-xs font-mono">
                    <div className="flex">
                      <span className="w-24 text-slate-500">Penerima:</span>
                      <span className="text-sky-300 font-bold">
                        {selectedRecord.payload.recipientName} ({Array.isArray(selectedRecord.payload.to) ? selectedRecord.payload.to.join(", ") : selectedRecord.payload.to})
                      </span>
                    </div>
                    <div className="flex">
                      <span className="w-24 text-slate-500">Jabatan:</span>
                      <span className="text-slate-300">{selectedRecord.payload.recipientRole}</span>
                    </div>
                    {selectedRecord.payload.cc && (
                      <div className="flex">
                        <span className="w-24 text-slate-500">Tembusan (CC):</span>
                        <span className="text-slate-400">{selectedRecord.payload.cc.join(", ")}</span>
                      </div>
                    )}
                    <div className="flex">
                      <span className="w-24 text-slate-500">Pengirim:</span>
                      <span className="text-slate-400">{selectedRecord.payload.sender}</span>
                    </div>
                    <div className="flex">
                      <span className="w-24 text-slate-500">Message-ID:</span>
                      <span className="text-slate-500 text-[10px]">{selectedRecord.messageId}</span>
                    </div>
                  </div>
                </div>

                {/* EMAIL SUBJECT */}
                <div className="mb-4">
                  <h3 className="text-base font-bold text-white font-mono flex items-center gap-2">
                    <Mail className="w-4 h-4 text-sky-400" />
                    {selectedRecord.payload.subject}
                  </h3>
                </div>

                {/* HTML PREVIEW FRAME */}
                <div className="flex-1 bg-slate-950 border border-slate-800 rounded-xl overflow-hidden flex flex-col">
                  <div className="bg-slate-800/80 px-4 py-2 text-[11px] font-mono text-slate-400 border-b border-slate-700 flex items-center justify-between">
                    <span>HTML Rendered Body (Email Client Preview)</span>
                    <span className="text-sky-400 font-bold">Responsive Layout</span>
                  </div>
                  <div className="flex-1 overflow-y-auto p-4 bg-[#0f172a]">
                    <div 
                      dangerouslySetInnerHTML={{ __html: selectedRecord.payload.htmlBody }}
                      className="max-w-2xl mx-auto"
                    />
                  </div>
                </div>

              </div>
            ) : (
              <div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-slate-500">
                <Eye className="w-10 h-10 text-slate-600 mb-3" />
                <p className="text-sm font-semibold text-slate-400">Pilih riwayat surat email di sebelah kiri</p>
                <p className="text-xs text-slate-500 mt-1">Preview lengkap format HTML dan meta header API gateway akan ditampilkan di sini.</p>
              </div>
            )}
          </div>

        </div>

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