'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 { CardSkeleton } from '@/components/ui/Skeleton';

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 (
      <>
        <AppHeader />
        <Sidebar />
        <div className="ml-64 mt-16 min-h-screen bg-gray-50">
          <Breadcrumb
            items={[
              { label: 'Domains', href: '/domains' },
              { label: 'Mailboxes' }
            ]}
          />
          <main id="main-content" className="p-8">
            <h1 className="text-3xl font-bold mb-8 text-gray-800 fade-in">Mailboxes for {bucket}</h1>
            <CardSkeleton count={5} />
          </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' }
            ]}
          />
          <main id="main-content" className="p-8">
            <div className="max-w-md 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>
      </>
    );
  }

  return (
    <>
      <AppHeader />
      <Sidebar />
      <div className="ml-64 mt-16 min-h-screen bg-gray-50">
        <Breadcrumb
          items={[
            { label: 'Domains', href: '/domains' },
            { label: 'Mailboxes' }
          ]}
        />
        <main id="main-content" className="p-8">
          <h1 className="text-3xl font-bold mb-8 text-gray-800 fade-in">Mailboxes for {bucket}</h1>
          <ul className="max-w-2xl grid gap-4 fade-in-stagger" role="list">
          {mailboxes.length === 0 ? (
            <li className="p-6 text-center text-gray-500 bg-white rounded-lg shadow-md">
              <div className="flex flex-col items-center gap-2">
                <svg className="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 19v-8.93a2 2 0 01.89-1.664l7-4.666a2 2 0 012.22 0l7 4.666A2 2 0 0121 10.07V19M3 19a2 2 0 002 2h14a2 2 0 002-2M3 19l6.75-4.5M21 19l-6.75-4.5M3 10l6.75 4.5M21 10l-6.75 4.5m0 0l-1.14.76a2 2 0 01-2.22 0l-1.14-.76" />
                </svg>
                <p>No mailboxes found</p>
              </div>
            </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-all hover:bg-blue-50 button-hover-lift focus-ring"
                  aria-label={`View emails for ${m}`}
                >
                  <span className="text-lg font-medium text-blue-600">{m}</span>
                </Link>
              </li>
            ))
          )}
        </ul>
          <div role="status" aria-live="polite" className="sr-only">
            {mailboxes.length} mailboxes loaded
          </div>
        </main>
      </div>
    </>
  );
}