'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { apiRequest, getCurrentUser } from '../../../lib/api';
import { loginHref } from '../../../lib/authRedirect';
import { Button } from '../../../components/Button';
import { ContestCard } from '../../../components/ContestCard';
import { EmptyBlock, ErrorBlock, LoadingBlock } from '../../../components/StateBlock';

export default function HeroesPage() {
  const user = getCurrentUser();
  const [contests, setContests] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = async () => {
    setLoading(true);
    try {
      const res = await apiRequest('/heroes');
      setContests(res.data || []);
      setError('');
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  return (
    <div className="space-y-3">
      <div className="overflow-hidden rounded-2xl bg-gradient-to-r from-amber-500 to-orange-600 px-4 py-4 text-white shadow-sm">
        <p className="text-[11px] font-bold uppercase tracking-wider text-white/80">Special</p>
        <h1 className="font-display text-xl font-bold">Pick Your Heroes</h1>
        <p className="mt-1 text-xs text-white/90">Choose exactly 2 eligible heroes before deadline.</p>
      </div>

      {loading && <LoadingBlock />}
      {error && <ErrorBlock message={error} onRetry={load} />}
      {!loading && !error && contests.length === 0 && (
        <EmptyBlock
          title="No Heroes contests open."
          hint="Check tournaments or come back later."
          action={
            <Link href="/tournaments">
              <Button variant="secondary">Browse tournaments</Button>
            </Link>
          }
        />
      )}

      {contests.map((c) => (
        <div key={c._id} className="space-y-2">
          <ContestCard
            contest={{
              ...c,
              prizePool: c.prizePool,
              entryFee: c.entryFee,
              filledSlots: c.filledSlots,
              maxSlots: c.maxSlots,
              status: c.status,
              title: c.title,
            }}
          />
          <p className="px-1 text-[11px] text-d11-muted">
            {c.tournamentId?.title || 'Tournament'} · Deadline{' '}
            {new Date(c.selectionDeadline).toLocaleString()}
          </p>
          <Link href={user ? `/heroes/${c._id}` : loginHref(`/heroes/${c._id}`)} className="block">
            <Button className="w-full" variant="amber">
              {user ? 'Select heroes' : 'Login to select'}
            </Button>
          </Link>
        </div>
      ))}
    </div>
  );
}
