'use client';

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

export default function Mailboxes() {
  const searchParams = useSearchParams();
  const bucket = searchParams.get('bucket');
  const [mailboxes, setMailboxes] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!bucket) {
      setError('No bucket specified');
      setLoading(false);
      return;
    }
    const auth = localStorage.getItem('auth');
    if (!auth) {
      setError('Not authenticated');
      setLoading(false);
      return;
    }

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

  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 className="font-semibold text-gray-700">Mailboxes</li>
        </ol>
      </nav>
      <h1 className="text-4xl font-bold mb-8 text-center text-gray-800">Mailboxes for {bucket}</h1>
      <ul className="max-w-md mx-auto grid gap-4">
        {mailboxes.length === 0 ? (
          <li className="p-6 text-center text-gray-500 bg-white rounded-lg shadow-md">No mailboxes found</li>
        ) : (
          mailboxes.map((m: string) => (
            <li key={m}>
              <Link href={`/emails?bucket=${bucket}&mailbox=${encodeURIComponent(m)}`} className="block p-6 bg-white rounded-lg shadow-md hover:shadow-lg transition hover:bg-blue-50">
                <span className="text-lg font-medium text-blue-600">{m}</span>
              </Link>
            </li>
          ))
        )}
      </ul>
    </div>
  );
}