'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-gray-100 p-8">
      <h1 className="text-3xl font-bold mb-6 text-center">Mailboxes for {bucket}</h1>
      <ul className="max-w-md mx-auto bg-white rounded-lg shadow-md divide-y divide-gray-200">
        {mailboxes.length === 0 ? (
          <li className="p-4 text-center text-gray-500">No mailboxes found</li>
        ) : (
          mailboxes.map((m: string) => (
            <li key={m} className="p-4 hover:bg-gray-50 transition">
              <Link href={`/emails?bucket=${bucket}&mailbox=${encodeURIComponent(m)}`} className="text-blue-500 hover:underline">
                {m}
              </Link>
            </li>
          ))
        )}
      </ul>
    </div>
  );
}