'use client';

import { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';

interface Email {
  key: string;
  subject: string;
  date: string;
  processed: string;
  processedAt: string | null;
  processedBy: string | null;
  queuedTo: string | null;
  status: string | null;
}

export default function Emails() {
  const searchParams = useSearchParams();
  const bucket = searchParams.get('bucket');
  const mailbox = searchParams.get('mailbox');
  const [emails, setEmails] = useState<Email[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!bucket || !mailbox) {
      setError('Missing parameters');
      setLoading(false);
      return;
    }
    const auth = localStorage.getItem('auth');
    if (!auth) {
      setError('Not authenticated');
      setLoading(false);
      return;
    }

    fetch(`/api/emails?bucket=${bucket}&mailbox=${encodeURIComponent(mailbox)}`, { 
      headers: { Authorization: `Basic ${auth}` } 
    })
      .then(res => {
        if (!res.ok) throw new Error('Failed to fetch emails');
        return res.json();
      })
      .then(data => {
        const sorted = data.sort((a: Email, b: Email) => new Date(b.date).getTime() - new Date(a.date).getTime());
        setEmails(sorted);
      })
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, [bucket, mailbox]);

  if (loading) return <div className="min-h-screen flex items-center justify-center bg-gray-50">Loading...</div>;
  if (error) return <div className="min-h-screen flex items-center justify-center bg-gray-50 text-red-500">{error}</div>;

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return date.toLocaleString('en-US', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
  };

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <nav className="w-full mb-8 bg-white p-4 rounded shadow-sm border border-gray-100">
        <ol className="flex flex-wrap space-x-2 text-sm text-gray-500">
          <li><Link href="/" className="hover:text-blue-600">Home</Link></li>
          <li className="mx-1">/</li>
          <li><Link href={`/mailboxes?bucket=${bucket}`} className="hover:text-blue-600">Mailboxes</Link></li>
          <li className="mx-1">/</li>
          <li className="font-semibold text-gray-700">Emails</li>
        </ol>
      </nav>
      
      <h1 className="text-2xl font-bold mb-8 text-gray-800 break-all">
        {mailbox} <span className="text-gray-400 font-normal text-lg">in {bucket}</span>
      </h1>
      
      {/* Container mit Padding für den "Rahmen um die Tabelle" */}
      <div className="w-full bg-white rounded shadow-sm border border-gray-200 p-2 overflow-hidden">
        
        {/* table-fixed: Zwingt die Tabelle, die definierten Breiten einzuhalten (kein Überlauf).
            border-separate + border-spacing-x-2: Erzeugt die "Gaps" zwischen den Spalten.
        */}
        <table className="w-full table-fixed border-separate border-spacing-x-2 border-spacing-y-1 text-left">
          <thead className="text-xs font-semibold text-gray-600 uppercase tracking-wider">
            <tr>
              {/* SUBJECT: Keine Breite definiert (w-auto) -> nimmt den RESTLICHEN Platz */}
              <th className="pb-3 border-b border-gray-200">Subject</th>

              {/* FESTE BREITEN für den Rest, damit sie nicht zerdrückt werden */}
              <th className="pb-3 border-b border-gray-200 w-28">Date</th>
              <th className="pb-3 border-b border-gray-200 w-[28rem]">Key</th> {/* Breit genug für lange Keys */}
              <th className="pb-3 border-b border-gray-200 text-center w-12">Proc.</th>
              <th className="pb-3 border-b border-gray-200 w-32">Proc. By</th>
              <th className="pb-3 border-b border-gray-200 w-32">Queued</th>
              <th className="pb-3 border-b border-gray-200 w-24">Status</th>
              <th className="pb-3 border-b border-gray-200 text-right w-16">Action</th>
            </tr>
          </thead>
          <tbody className="text-sm">
            {emails.length === 0 ? (
              <tr>
                <td colSpan={8} className="py-8 text-center text-gray-500">No emails found</td>
              </tr>
            ) : emails.map((e: Email) => (
              <tr key={e.key} className="hover:bg-blue-50 transition-colors group">
                
                {/* 1. Subject: truncate sorgt für "..." am Ende, da die Tabellenbreite fix ist */}
                <td className="py-2 text-gray-900 truncate" title={e.subject}>
                  <div className="truncate">{e.subject}</div>
                </td>

                <td className="py-2 text-gray-500 text-xs whitespace-nowrap">
                  {formatDate(e.date)}
                </td>
                
                {/* Key: Monospace für exakte Breite, text-xs damit er in die 28rem passt */}
                <td className="py-2 font-mono text-xs text-gray-600 select-all truncate" title={e.key}>
                  {e.key}
                </td>
                
                <td className="py-2 text-center align-middle">
                   {/* Kleinerer Badge */}
                  <span className={`inline-block w-4 h-4 rounded-full ${e.processed === 'true' ? 'bg-green-400' : 'bg-gray-300'}`} title={e.processed === 'true' ? 'Processed' : 'Not processed'}></span>
                </td>
                
                <td className="py-2 text-gray-500 text-xs truncate" title={e.processedBy || ''}>
                  {e.processedBy ? e.processedBy.split('@')[0] : '-'}
                </td>
                
                <td className="py-2 text-gray-500 text-xs truncate" title={e.queuedTo || ''}>
                   {e.queuedTo || '-'}
                </td>
                
                <td className="py-2 whitespace-nowrap">
                  {e.status ? (
                    <span className={`text-xs font-medium ${
                      e.status === 'delivered' ? 'text-green-600' : 
                      e.status === 'failed' ? 'text-red-600' : 
                      'text-gray-500'
                    }`}>
                      {e.status}
                    </span>
                  ) : <span className="text-gray-300">-</span>}
                </td>
                
                <td className="py-2 text-right font-medium">
                  <Link href={`/email?bucket=${bucket}&key=${e.key}&mailbox=${encodeURIComponent(mailbox || '')}`} className="text-blue-600 hover:text-blue-800 underline decoration-blue-200 hover:decoration-blue-800">
                    View
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}