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