'use client';

import { useState, useEffect } from 'react';
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 Domains() {
  const [domains, setDomains] = useState([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

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

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

  if (loading) {
    return (
      <>
        <AppHeader />
        <Sidebar />
        <div className="ml-64 mt-16 min-h-screen bg-gray-50">
          <Breadcrumb items={[{ label: 'Domains' }]} />
          <main id="main-content" className="p-8">
            <h1 className="text-3xl font-bold mb-8 text-gray-800 fade-in">All Domains</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' }]} />
          <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' }]} />
        <main id="main-content" className="p-8">
          <h1 className="text-3xl font-bold mb-8 text-gray-800 fade-in">All Domains</h1>
          <ul className="max-w-2xl grid gap-4 fade-in-stagger" role="list">
            {domains.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="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
                  </svg>
                  <p>No domains found</p>
                </div>
              </li>
            ) : (
              domains.map((d: any) => (
                <li key={d.bucket}>
                  <Link
                    href={`/mailboxes?bucket=${d.bucket}`}
                    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 mailboxes for ${d.domain}`}
                  >
                    <div className="flex items-center justify-between">
                      <span className="text-lg font-medium text-blue-600">{d.domain}</span>
                      <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                      </svg>
                    </div>
                  </Link>
                </li>
              ))
            )}
          </ul>
          <div role="status" aria-live="polite" className="sr-only">
            {domains.length} domains loaded
          </div>
        </main>
      </div>
    </>
  );
}