// components/InboxViewer.tsx
"use client";

import { useEffect, useState } from "react";
import { X, Mail, Clock, Loader2, Inbox as InboxIcon } from "lucide-react";

interface InboundMessage {
  id: string;
  fromAddress: string;
  subject: string;
  bodyHtml: string;
  bodyText: string;
  receivedAt: string;
}

interface InboxViewerProps {
  tempEmailId: string;
  address: string;
  onClose: () => void;
}

export default function InboxViewer({ tempEmailId, address, onClose }: InboxViewerProps) {
  const [messages, setMessages] = useState<InboundMessage[]>([]);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function loadInbox() {
      try {
        const res = await fetch(`/api/inbox/${tempEmailId}`);
        const data = await res.json();
        if (!res.ok) {
          setError(data.error || "Failed to load inbox");
          return;
        }
        setMessages(data.messages);
        if (data.messages.length > 0) {
          setSelectedId(data.messages[0].id);
        }
      } catch {
        setError("Something went wrong loading the inbox.");
      } finally {
        setIsLoading(false);
      }
    }
    loadInbox();
  }, [tempEmailId]);

  const selectedMessage = messages.find((m) => m.id === selectedId) || null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4">
      <div className="w-full max-w-5xl h-[80vh] bg-slate-900 border border-slate-800 rounded-2xl shadow-xl flex flex-col overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-800 shrink-0">
          <div className="min-w-0">
            <h2 className="text-sm font-semibold text-white flex items-center gap-2">
              <InboxIcon className="w-4 h-4 text-indigo-400" />
              Inbox
            </h2>
            <p className="text-xs text-slate-500 font-mono truncate">{address}</p>
          </div>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>

        {isLoading ? (
          <div className="flex-1 flex items-center justify-center text-slate-500 text-sm gap-2">
            <Loader2 className="w-4 h-4 animate-spin" />
            Loading messages...
          </div>
        ) : error ? (
          <div className="flex-1 flex items-center justify-center text-red-400 text-sm">{error}</div>
        ) : messages.length === 0 ? (
          <div className="flex-1 flex flex-col items-center justify-center text-slate-500 gap-2">
            <Mail className="w-8 h-8 text-slate-700" />
            <p className="text-sm">No messages received yet</p>
          </div>
        ) : (
          <div className="flex flex-1 min-h-0">
            {/* Message list pane */}
            <div className="w-72 shrink-0 border-r border-slate-800 overflow-y-auto">
              {messages.map((msg) => (
                <button
                  key={msg.id}
                  onClick={() => setSelectedId(msg.id)}
                  className={`w-full text-left px-4 py-3 border-b border-slate-800/60 transition-colors ${
                    selectedId === msg.id ? "bg-slate-800" : "hover:bg-slate-800/50"
                  }`}
                >
                  <p className="text-sm font-medium text-white truncate">
                    {msg.subject || "(no subject)"}
                  </p>
                  <p className="text-xs text-slate-500 truncate mt-0.5">{msg.fromAddress}</p>
                  <p className="text-[11px] text-slate-600 flex items-center gap-1 mt-1">
                    <Clock className="w-3 h-3" />
                    {new Date(msg.receivedAt).toLocaleString()}
                  </p>
                </button>
              ))}
            </div>

            {/* Message detail pane */}
            <div className="flex-1 overflow-y-auto p-6">
              {selectedMessage ? (
                <div>
                  <h3 className="text-base font-semibold text-white mb-1">
                    {selectedMessage.subject || "(no subject)"}
                  </h3>
                  <p className="text-xs text-slate-500 mb-4">
                    From <span className="text-slate-300">{selectedMessage.fromAddress}</span> ·{" "}
                    {new Date(selectedMessage.receivedAt).toLocaleString()}
                  </p>
                  <div className="border-t border-slate-800 pt-4">
                    {selectedMessage.bodyHtml ? (
                      <div
                        className="prose prose-invert prose-sm max-w-none"
                        // Content originates from the mail provider's parsed payload and
                        // is stored as-is; sandboxing/sanitization should happen at the
                        // webhook ingestion layer (e.g. via an HTML sanitizer) before
                        // persisting bodyHtml in production.
                        dangerouslySetInnerHTML={{ __html: selectedMessage.bodyHtml }}
                      />
                    ) : (
                      <pre className="whitespace-pre-wrap text-sm text-slate-300 font-sans">
                        {selectedMessage.bodyText || "(empty message)"}
                      </pre>
                    )}
                  </div>
                </div>
              ) : (
                <div className="text-sm text-slate-500">Select a message to view its contents.</div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
