'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { authApi, wishlistsApi, type Wishlist } from '@/lib/api';

export default function HomePage() {
  const router = useRouter();
  const params = useSearchParams();
  const [state, setState] = useState<'checking' | 'guest' | 'none'>('checking');
  const [wishlists, setWishlists] = useState<Wishlist[]>([]);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const adm = params.get('adm');
      const usr = params.get('usr');
      try {
        if (adm) {
          await authApi.session({ adm });
          router.replace('/admin');
          return;
        }
        if (usr) {
          await authApi.session({ usr });
        }
        const who = await authApi.whoami();
        if (cancelled) return;
        if (who.role === 'admin') {
          router.replace('/admin');
          return;
        }
        if (who.role === 'guest') {
          const lists = await wishlistsApi.getAllPublic();
          if (cancelled) return;
          if (lists.length === 1) {
            router.replace(`/${lists[0].slug}`);
            return;
          }
          setWishlists(lists);
          setState('guest');
          return;
        }
        setState('none');
      } catch {
        if (!cancelled) setState('none');
      }
    })();
    return () => { cancelled = true; };
  }, [params, router]);

  if (state === 'checking') {
    return <div className="min-h-screen flex items-center justify-center text-gray-500">Carregando…</div>;
  }

  if (state === 'guest') {
    return (
      <div className="min-h-screen flex items-center justify-center px-6">
        <div className="w-full max-w-2xl text-center">
          <h1 className="text-3xl font-bold mb-6">Bem-vindo</h1>
          {wishlists.length === 0 ? (
            <p className="text-gray-500">Nenhuma lista disponível ainda.</p>
          ) : (
            <ul className="space-y-3 text-left">
              {wishlists.map((w) => (
                <li key={w.id}>
                  <Link
                    href={`/${w.slug}`}
                    className="block rounded-lg border border-gray-200 dark:border-gray-700 p-4 hover:border-indigo-400 hover:bg-indigo-50/30 dark:hover:bg-indigo-900/10 transition"
                  >
                    <div className="font-semibold text-lg">{w.name}</div>
                    {w.description && (
                      <div className="text-sm text-gray-500 mt-1">{w.description}</div>
                    )}
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center text-center px-6">
      <div>
        <h1 className="text-3xl font-bold mb-2">Convite necessário</h1>
        <p className="text-gray-500">Esta página é por convite. Use o link que recebeu.</p>
      </div>
    </div>
  );
}
