const { useState, useEffect } = React;
const { Mail, Calendar, Eye, ShieldAlert, ArrowRight, CornerDownRight, Inbox } = window.lucide;

function EmailLogsPanel() {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedLog, setSelectedLog] = useState(null);

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

  const fetchLogs = async () => {
    try {
      const res = await fetch('api.php?action=email_logs');
      if (res.ok) {
        const text = await res.text();
        try {
          const data = JSON.parse(text);
          setLogs(data);
          if (data.length > 0) {
            setSelectedLog(data[0]);
          }
        } catch (jsonErr) {
          console.error('Expected JSON from /api/email-logs but got HTML/text:', text.substring(0, 100));
        }
      }
    } catch (e) {
      console.error('Failed to fetch email logs:', e);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-48">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 animate-fade-in">
      {/* Logs List (Left) */}
      <div className="lg:col-span-5 bg-white rounded-xl border border-gray-100 shadow-sm p-5 space-y-4">
        <h2 className="text-sm font-bold text-gray-900 flex items-center gap-2">
          <Inbox className="w-4.5 h-4.5 text-indigo-600" />
          ประวัติการแจ้งเตือนอีเมล (Email Outbox Logs)
        </h2>

        {logs.length === 0 ? (
          <div className="text-center py-12 px-4 border-2 border-dashed border-gray-100 rounded-xl">
            <Mail className="w-10 h-10 text-gray-300 mx-auto mb-3" />
            <p className="text-sm font-medium text-gray-500">ยังไม่มีบันทึกการส่งอีเมล</p>
            <p className="text-xs text-gray-400 mt-1 leading-relaxed">
              เมื่อคุณอัปโหลดสแกนสำเร็จ และเปิดโหมด Email Notification ระบบจะทำการบันทึกและแสดงสรุปจดหมายที่นี่
            </p>
          </div>
        ) : (
          <div className="space-y-2.5 max-h-[500px] overflow-y-auto pr-1 scrollbar-thin">
            {logs.map((log) => (
              <button
                key={log.id}
                onClick={() => setSelectedLog(log)}
                className={`w-full text-left p-3.5 rounded-xl border transition-all flex items-start gap-3 outline-none ${
                  selectedLog?.id === log.id
                    ? 'border-indigo-500 bg-indigo-50/50 ring-1 ring-indigo-100 shadow-sm'
                    : 'border-gray-100 hover:border-gray-200 hover:bg-gray-50'
                }`}
              >
                <div className={`p-2 rounded-lg mt-0.5 ${
                  log.status === 'sent' 
                    ? 'bg-emerald-50 text-emerald-600'
                    : log.status === 'simulated'
                    ? 'bg-amber-50 text-amber-600'
                    : 'bg-rose-50 text-rose-600'
                }`}>
                  <Mail className="w-4 h-4" />
                </div>
                
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-2 mb-1">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-gray-400 flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      {new Date(log.timestamp).toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' })}
                    </span>
                    <span className={`text-[9px] font-extrabold px-1.5 py-0.5 rounded-full uppercase tracking-wider ${
                      log.status === 'sent' 
                        ? 'bg-emerald-100 text-emerald-700'
                        : log.status === 'simulated'
                        ? 'bg-amber-100 text-amber-700'
                        : 'bg-rose-100 text-rose-700'
                    }`}>
                      {log.status === 'sent' ? 'REAL SMTP' : log.status === 'simulated' ? 'SIMULATED' : 'FAILED'}
                    </span>
                  </div>
                  <h4 className="text-xs font-bold text-gray-900 truncate">{log.subject}</h4>
                  <p className="text-[10px] text-gray-500 mt-1 truncate">ส่งถึง: {log.to}</p>
                </div>
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Log Preview Frame (Right) */}
      <div className="lg:col-span-7 flex flex-col bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden min-h-[450px]">
        {selectedLog ? (
          <div className="flex-1 flex flex-col">
            {/* Header */}
            <div className="p-5 border-b border-gray-100 bg-gray-50/50">
              <div className="flex items-start justify-between gap-4 mb-3">
                <div>
                  <h3 className="text-sm font-bold text-gray-900 leading-snug">{selectedLog.subject}</h3>
                  <div className="flex items-center gap-1.5 text-xs text-gray-500 mt-1.5">
                    <span className="font-semibold text-gray-700">ถึง (To):</span>
                    <span className="bg-white px-2 py-0.5 border border-gray-200 rounded text-gray-600 font-mono text-[11px]">{selectedLog.to}</span>
                  </div>
                </div>
                <div className="text-right text-[10px] text-gray-400 font-bold whitespace-nowrap">
                  {new Date(selectedLog.timestamp).toLocaleString('th-TH')}
                </div>
              </div>

              {selectedLog.status === 'simulated' && (
                <div className="flex items-start gap-2 bg-amber-50 border border-amber-200/50 rounded-lg p-2.5 text-[11px] text-amber-800">
                  <ShieldAlert className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
                  <div>
                    <span className="font-bold">โหมดจดหมายจำลอง (Email Simulation):</span> สรุปรายงานสแกนถูกบันทึกสำเร็จโดยไม่ต้องส่งออกจริง หากต้องการส่งตรงเข้า Inbox กรุณากรอกการตั้งค่า SMTP ในแทบ "ตั้งค่าระบบ"
                  </div>
                </div>
              )}

              {selectedLog.status === 'failed' && (
                <div className="flex items-start gap-2 bg-rose-50 border border-rose-200/50 rounded-lg p-2.5 text-[11px] text-rose-800">
                  <ShieldAlert className="w-4 h-4 text-rose-600 shrink-0 mt-0.5" />
                  <div>
                    <span className="font-bold">การส่งอีเมลจริงล้มเหลว (SMTP Error):</span> {selectedLog.errorMessage || 'เกิดข้อผิดพลาดในการเชื่อมต่อเซิร์ฟเวอร์ SMTP'}
                  </div>
                </div>
              )}
            </div>

            {/* Email Body Preview via iframe */}
            <div className="flex-1 p-4 bg-gray-100 flex flex-col min-h-[350px]">
              <div className="bg-white rounded-lg shadow-inner flex-1 overflow-hidden border border-gray-200/80 flex flex-col">
                <div className="bg-gray-100 border-b border-gray-200 px-4 py-2 flex items-center gap-2">
                  <Eye className="w-4 h-4 text-gray-500" />
                  <span className="text-[10px] font-bold text-gray-500 uppercase tracking-wider">Visual Email Renderer</span>
                </div>
                <iframe
                  title="email-preview"
                  srcDoc={selectedLog.body}
                  className="w-full flex-1 border-0 bg-white"
                />
              </div>
            </div>
          </div>
        ) : (
          <div className="flex-1 flex flex-col justify-center items-center text-center p-8 text-gray-400">
            <Mail className="w-12 h-12 text-gray-200 mb-2" />
            <span className="text-sm font-semibold">เลือกรายการแจ้งเตือนเพื่อดูพรีวิว</span>
          </div>
        )}
      </div>
    </div>
  );
}

window.EmailLogsPanel = EmailLogsPanel;
