'use client';

import { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import ReactMarkdown from 'react-markdown';

export default function EmailDetail() {
  const searchParams = useSearchParams();
  const bucket = searchParams.get('bucket');
  const key = searchParams.get('key');
  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-gray-100 p-8">
      <div className="max-w-4xl mx-auto bg-white rounded-lg shadow-md p-6">
        <h1 className="text-3xl font-bold mb-4">{email.subject}</h1>
        <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-4"><strong>Processed:</strong> {email.processed}</p>
        <div className="flex mb-4">
          <button 
            onClick={() => setViewMode('html')} 
            className={`px-4 py-2 rounded-l ${viewMode === 'html' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'} hover:bg-blue-600 transition`}
          >
            HTML
          </button>
          <button 
            onClick={() => setViewMode('raw')} 
            className={`px-4 py-2 rounded-r ${viewMode === 'raw' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'} hover:bg-blue-600 transition`}
          >
            RAW
          </button>
        </div>
        <div className="border border-gray-300 p-4 rounded bg-white overflow-auto max-h-96">
          {viewMode === 'html' ? (
            <div className="prose">
              <ReactMarkdown>{email.html}</ReactMarkdown>
            </div>
          ) : (
            <pre className="whitespace-pre-wrap text-sm">{email.raw}</pre>
          )}
        </div>
      </div>
    </div>
  );
}