'use client';

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

export default function EmailDetail() {
  const searchParams = useSearchParams();
  const bucket = searchParams.get('bucket');
  const key = searchParams.get('key');
  const mailbox = searchParams.get('mailbox');  // Für Breadcrumb
  const [email, setEmail] = useState({ subject: '', from: '', to: '', html: '', raw: '', processed: '' });
  const [viewMode, setViewMode] = useState('html');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

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

    fetch(`/api/email?bucket=${bucket}&key=${key}`, { 
      headers: { Authorization: `Basic ${auth}` } 
    })
      .then(res => {
        if (!res.ok) throw new Error('Failed to fetch email');
        return res.json();
      })
      .then(setEmail)
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, [bucket, key]);

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

  return (
    <div className="min-h-screen bg-gradient-to-b from-blue-50 to-gray-100 p-8">
      <nav className="max-w-4xl mx-auto mb-6 bg-white p-4 rounded-lg shadow-sm">
        <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="/domains" className="hover:text-blue-600">Domains</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><Link href={`/emails?bucket=${bucket}&mailbox=${encodeURIComponent(mailbox || '')}`} className="hover:text-blue-600">Emails</Link></li>
          <li className="mx-1">/</li>
          <li className="font-semibold text-gray-700">Detail</li>
        </ol>
      </nav>
      <div className="max-w-4xl mx-auto bg-white rounded-lg shadow-md p-8">
        <h1 className="text-4xl font-bold mb-6 text-gray-800">{email.subject}</h1>
        <p className="text-gray-700 mb-2 text-lg"><strong>From:</strong> {email.from}</p>
        <p className="text-gray-700 mb-2 text-lg"><strong>To:</strong> {email.to}</p>
        <p className="text-gray-700 mb-2 text-lg"><strong>S3 Key:</strong> {key}</p>
        <p className="text-gray-700 mb-6 text-lg"><strong>Processed:</strong> {email.processed}</p>
        <div className="flex mb-6 space-x-2">
          <button 
            onClick={() => setViewMode('html')} 
            className={`px-6 py-3 rounded-md font-medium ${viewMode === 'html' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700'} hover:bg-blue-700 transition`}
          >
            HTML
          </button>
          <button 
            onClick={() => setViewMode('raw')} 
            className={`px-6 py-3 rounded-md font-medium ${viewMode === 'raw' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700'} hover:bg-blue-700 transition`}
          >
            RAW
          </button>
        </div>
        <div className="border border-gray-300 p-6 rounded-lg bg-white overflow-auto max-h-[600px] shadow-inner">
          {viewMode === 'html' ? (
            <div dangerouslySetInnerHTML={{ __html: email.html }} className="prose prose-lg max-w-none" />
          ) : (
            <pre className="whitespace-pre-wrap text-sm font-mono bg-gray-50 p-4 rounded">{email.raw}</pre>
          )}
        </div>
      </div>
    </div>
  );
}