'use client';

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

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 <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 className="font-semibold text-gray-700">Domains</li>
        </ol>
      </nav>
      <h1 className="text-4xl font-bold mb-8 text-center text-gray-800">Domains</h1>
      <ul className="max-w-md mx-auto grid gap-4">
        {domains.length === 0 ? (
          <li className="p-6 text-center text-gray-500 bg-white rounded-lg shadow-md">No domains found</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 hover:bg-blue-50">
                <span className="text-lg font-medium text-blue-600">{d.domain}</span>
              </Link>
            </li>
          ))
        )}
      </ul>
    </div>
  );
}