'use client';

import { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { AppHeader } from '@/components/layout/AppHeader';
import { Sidebar } from '@/components/layout/Sidebar';
import { Breadcrumb } from '@/components/layout/Breadcrumb';
import { DetailSkeleton } from '@/components/ui/Skeleton';

export default function EmailDetail() {
  const searchParams = useSearchParams();
  const bucket = searchParams.get('bucket');
  const key = searchParams.get('key');
  const mailbox = searchParams.get('mailbox');
  const [email, setEmail] = useState({ 
    subject: '', 
    from: '', 
    to: '', 
    html: '', 
    raw: '', 
    processed: '',
    processedAt: null as string | null,
    processedBy: null as string | null,
    queuedTo: null as string | null,
    status: null as string | null,
  });
  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 (
      <>
        <AppHeader />
        <Sidebar />
        <div className="ml-64 mt-16 min-h-screen bg-gray-50">
          <Breadcrumb items={[
            { label: 'Domains', href: '/domains' },
            { label: 'Mailboxes', href: `/mailboxes?bucket=${bucket}` },
            { label: 'Emails', href: `/emails?bucket=${bucket}&mailbox=${encodeURIComponent(mailbox || '')}` },
            { label: 'Detail' }
          ]} />
          <main id="main-content" className="p-8">
            <DetailSkeleton />
          </main>
        </div>
      </>
    );
  }

  if (error) {
    return (
      <>
        <AppHeader />
        <Sidebar />
        <div className="ml-64 mt-16 min-h-screen bg-gray-50">
          <Breadcrumb items={[
            { label: 'Domains', href: '/domains' },
            { label: 'Mailboxes', href: `/mailboxes?bucket=${bucket}` },
            { label: 'Emails', href: `/emails?bucket=${bucket}&mailbox=${encodeURIComponent(mailbox || '')}` },
            { label: 'Detail' }
          ]} />
          <main id="main-content" className="p-8">
            <div className="max-w-4xl mx-auto bg-white rounded-lg shadow-md p-8 fade-in" role="alert">
              <p className="text-red-600 font-medium text-center">{error}</p>
            </div>
          </main>
        </div>
      </>
    );
  }

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

  return (
    <>
      <AppHeader />
      <Sidebar />
      <div className="ml-64 mt-16 min-h-screen bg-gray-50">
        <Breadcrumb items={[
          { label: 'Domains', href: '/domains' },
          { label: 'Mailboxes', href: `/mailboxes?bucket=${bucket}` },
          { label: 'Emails', href: `/emails?bucket=${bucket}&mailbox=${encodeURIComponent(mailbox || '')}` },
          { label: 'Detail' }
        ]} />
        <main id="main-content">
          {/* Email Header */}
          <div className="bg-white border-b border-gray-200 px-8 py-6">
            <div className="flex items-start justify-between mb-4">
              <div className="flex-1">
                <h1 className="text-3xl font-bold text-gray-900 mb-2">{email.subject}</h1>
                <div className="flex items-center gap-3 text-sm text-gray-600">
                  <Link
                    href={`/emails?bucket=${bucket}&mailbox=${encodeURIComponent(mailbox || '')}`}
                    className="text-blue-600 hover:text-blue-800 flex items-center gap-1"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                    </svg>
                    Zurück zur Liste
                  </Link>
                </div>
              </div>
              {email.status && (
                <span className={`inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium ${
                  email.status === 'delivered' ? 'bg-green-100 text-green-800' :
                  email.status === 'failed' ? 'bg-red-100 text-red-800' :
                  'bg-gray-100 text-gray-700'
                }`}>
                  {email.status === 'delivered' && (
                    <svg className="w-4 h-4 mr-1.5" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  )}
                  {email.status === 'failed' && (
                    <svg className="w-4 h-4 mr-1.5" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                    </svg>
                  )}
                  {email.status.charAt(0).toUpperCase() + email.status.slice(1)}
                </span>
              )}
            </div>
          </div>

          <div className="max-w-5xl mx-auto p-8">
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-8 fade-in">
              {/* Email Meta Info */}
              <div className="mb-6 pb-6 border-b border-gray-200">
                <div className="flex items-start gap-4 mb-4">
                  <div className="w-12 h-12 bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold text-lg">
                    {email.from ? email.from.charAt(0).toUpperCase() : 'U'}
                  </div>
                  <div className="flex-1">
                    <div className="font-semibold text-gray-900 mb-1">{email.from || 'Unknown Sender'}</div>
                    <div className="text-sm text-gray-600">to {email.to || 'Unknown'}</div>
                  </div>
                </div>
              </div>

              {/* Technical Details (Collapsible) */}
              <details className="mb-6">
                <summary className="text-sm font-medium text-gray-700 cursor-pointer hover:text-gray-900 mb-3">
                  Technische Details anzeigen
                </summary>
                <div className="grid grid-cols-2 gap-4 mb-6 bg-gray-50 p-6 rounded-lg">
                  <div>
                    <p className="text-gray-700 mb-2"><strong>From:</strong> {email.from}</p>
                    <p className="text-gray-700 mb-2"><strong>To:</strong> {email.to}</p>
                    <p className="text-gray-700 mb-2"><strong>S3 Key:</strong> <span className="text-sm break-all">{key}</span></p>
                  </div>
                  <div>
                    <p className="text-gray-700 mb-2">
                      <strong>Processed:</strong>
                      <span className={`ml-2 px-2 py-1 rounded-full text-xs font-medium ${email.processed === 'true' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}`}>
                        {email.processed === 'true' ? 'Yes' : 'No'}
                      </span>
                    </p>
                    <p className="text-gray-700 mb-2"><strong>Processed At:</strong> {formatDate(email.processedAt)}</p>
                    <p className="text-gray-700 mb-2"><strong>Processed By:</strong> {email.processedBy || 'N/A'}</p>
                    <p className="text-gray-700 mb-2"><strong>Queued To:</strong> {email.queuedTo || 'N/A'}</p>
                    <p className="text-gray-700 mb-2">
                      <strong>Status:</strong>
                      {email.status ? (
                        <span className={`ml-2 px-2 py-1 rounded-full text-xs font-medium ${
                          email.status === 'delivered' ? 'bg-green-100 text-green-800' :
                          email.status === 'failed' ? 'bg-red-100 text-red-800' :
                          'bg-gray-100 text-gray-800'
                        }`}>
                          {email.status}
                        </span>
                      ) : 'N/A'}
                    </p>
                  </div>
                </div>
              </details>

              <div className="flex mb-6 space-x-2 no-print" role="tablist" aria-label="Email view options">
            <button
              role="tab"
              aria-selected={viewMode === 'html'}
              aria-controls="email-content"
              id="tab-html"
              onClick={() => setViewMode('html')}
              className={`px-6 py-3 rounded-lg font-medium transition-all focus-ring ${
                viewMode === 'html'
                  ? 'bg-blue-600 text-white shadow-md'
                  : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
              }`}
            >
              <span className="flex items-center gap-2">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
                </svg>
                HTML
              </span>
            </button>
            <button
              role="tab"
              aria-selected={viewMode === 'raw'}
              aria-controls="email-content"
              id="tab-raw"
              onClick={() => setViewMode('raw')}
              className={`px-6 py-3 rounded-lg font-medium transition-all focus-ring ${
                viewMode === 'raw'
                  ? 'bg-blue-600 text-white shadow-md'
                  : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
              }`}
            >
              <span className="flex items-center gap-2">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                RAW
              </span>
            </button>
              </div>

              <div
                id="email-content"
                role="tabpanel"
                aria-labelledby={viewMode === 'html' ? 'tab-html' : 'tab-raw'}
                className="border border-gray-300 p-6 rounded-lg bg-white overflow-auto max-h-[600px] shadow-inner email-content"
              >
                {viewMode === 'html' ? (
                  <>
                    <div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded text-sm text-yellow-800 no-print">
                      <svg className="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                      </svg>
                      Displaying HTML content from email
                    </div>
                    <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>
      </main>
    </div>
    </>
  );
}
