'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { apiRequest, getCurrentUser, idempotencyKey } from '../../../../lib/api';
import { Button } from '../../../../components/Button';
import { Badge } from '../../../../components/Badge';
import { EmptyBlock, ErrorBlock, LoadingBlock } from '../../../../components/StateBlock';

export default function HeroContestPage() {
  const { contestId } = useParams<{ contestId: string }>();
  const router = useRouter();
  const user = getCurrentUser();

  const [contest, setContest] = useState<any>(null);
  const [players, setPlayers] = useState<any[]>([]);
  const [hero1, setHero1] = useState('');
  const [hero2, setHero2] = useState('');
  const [entry, setEntry] = useState<any>(null);
  const [board, setBoard] = useState<any[]>([]);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);

  const load = async () => {
    setLoading(true);
    try {
      const list = await apiRequest('/heroes');
      const c = (list.data || []).find((x: any) => x._id === contestId);
      setContest(c || null);
      if (c?.tournamentId?._id || c?.tournamentId) {
        const tid = c.tournamentId._id || c.tournamentId;
        const t = await apiRequest(`/tournaments/${tid}`);
        setPlayers((t.data?.eligiblePlayers || []).map((ep: any) => ep.playerId).filter(Boolean));
      }
      if (user) {
        try {
          const e = await apiRequest(`/heroes/my-entry/${contestId}`);
          setEntry(e.data);
          if (e.data?.hero1Id) setHero1(String(e.data.hero1Id._id || e.data.hero1Id));
          if (e.data?.hero2Id) setHero2(String(e.data.hero2Id._id || e.data.hero2Id));
        } catch {
          setEntry(null);
        }
      }
      const lb = await apiRequest(`/heroes/leaderboard/${contestId}`);
      setBoard(lb.data || []);
      setError('');
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

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

  const confirm = async () => {
    if (!user) {
      router.push('/login');
      return;
    }
    if (!hero1 || !hero2 || hero1 === hero2) {
      setError('Pick two different heroes.');
      return;
    }
    setBusy(true);
    setError('');
    try {
      await apiRequest('/heroes/confirm', {
        method: 'POST',
        idempotencyKey: idempotencyKey('hero'),
        body: JSON.stringify({ contestId, hero1Id: hero1, hero2Id: hero2 }),
      });
      await load();
    } catch (e: any) {
      setError(e.message || 'Confirm failed');
    } finally {
      setBusy(false);
    }
  };

  if (loading) return <LoadingBlock />;
  if (!contest) {
    return (
      <EmptyBlock
        title="Contest not found"
        action={
          <Link href="/heroes">
            <Button variant="secondary">Back to Heroes</Button>
          </Link>
        }
      />
    );
  }

  const locked = entry?.isLocked || contest.status !== 'OPEN';

  return (
    <div className="space-y-3">
      <Link href="/heroes" className="text-xs font-bold text-d11-muted hover:text-d11-red">
        ← Heroes
      </Link>
      <div className="d11-sheet overflow-hidden">
        <div className="border-b border-gray-100 px-4 py-3">
          <h1 className="font-display text-lg font-bold text-d11-ink">{contest.title}</h1>
          <div className="mt-2 flex flex-wrap gap-2 text-xs text-d11-muted">
            <Badge variant={contest.status === 'OPEN' ? 'amber' : 'slate'}>{contest.status}</Badge>
            <span>Lock {new Date(contest.lockTime).toLocaleString()}</span>
            <span>
              {contest.filledSlots}/{contest.maxSlots}
            </span>
          </div>
        </div>
      </div>

      {error && <ErrorBlock message={error} />}

      <section className="space-y-3">
        <h2 className="px-1 text-sm font-bold text-d11-ink">Select Hero 1 & Hero 2</h2>
        {players.length === 0 ? (
          <EmptyBlock title="No eligible players listed for this tournament." />
        ) : (
          <div className="grid gap-2 sm:grid-cols-2">
            {players.map((p: any) => {
              const id = String(p._id);
              const picked = hero1 === id || hero2 === id;
              return (
                <button
                  key={id}
                  type="button"
                  disabled={locked}
                  onClick={() => {
                    if (hero1 === id) setHero1('');
                    else if (hero2 === id) setHero2('');
                    else if (!hero1) setHero1(id);
                    else if (!hero2) setHero2(id);
                    else setHero2(id);
                  }}
                  className={`d11-card cursor-pointer px-3 py-2 text-left text-sm disabled:opacity-60 ${
                    picked ? 'border-amber-400 bg-amber-50 shadow-sm' : ''
                  }`}
                >
                  <div className="font-medium text-d11-ink">{p.name}</div>
                  <div className="text-xs text-d11-muted">
                    {p.role} · {p.creditValue} cr
                    {hero1 === id ? ' · Hero 1' : ''}
                    {hero2 === id ? ' · Hero 2' : ''}
                  </div>
                </button>
              );
            })}
          </div>
        )}
        {!locked && (
          <Button variant="amber" loading={busy} onClick={confirm}>
            Confirm heroes
          </Button>
        )}
        {locked && entry && (
          <div className="d11-card px-4 py-3 text-sm text-d11-ink">
            Selection locked. Points: {entry.totalPoints ?? 0}
          </div>
        )}
      </section>

      <section>
        <h2 className="mb-2 px-1 text-sm font-bold text-d11-ink">Leaderboard</h2>
        {board.length === 0 ? (
          <EmptyBlock title="No entries on the board yet." />
        ) : (
          <ul className="space-y-2 text-sm">
            {board.slice(0, 20).map((row: any, i: number) => (
              <li key={row._id || i} className="d11-card flex justify-between px-3 py-2">
                <span className="text-d11-ink">
                  #{row.rank || i + 1} {row.userId?.name || 'User'}
                </span>
                <span className="font-mono font-bold text-amber-600">{row.totalPoints ?? row.points ?? 0}</span>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
