'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { apiRequest } from '../../../lib/api';
import { Badge } from '../../../components/Badge';
import { PageHeader } from '../../../components/PageHeader';
import { EmptyBlock, ErrorBlock, LoadingBlock } from '../../../components/StateBlock';

export default function TournamentsPage() {
  const [rows, setRows] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

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

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

  return (
    <div className="space-y-3">
      <PageHeader title="Tournaments" subtitle="Seasons, fantasy & heroes contests" />
      {loading && <LoadingBlock />}
      {error && <ErrorBlock message={error} onRetry={load} />}
      {!loading && !error && rows.length === 0 && <EmptyBlock title="No tournaments published." />}
      <div className="grid gap-3 sm:grid-cols-2">
        {rows.map((t) => (
          <div key={t._id} className="d11-card flex flex-col p-4">
            <div className="flex items-start justify-between gap-2">
              <h2 className="font-semibold text-d11-ink">{t.title}</h2>
              <Badge variant="cyan">{t.code}</Badge>
            </div>
            <p className="mt-2 text-xs text-d11-muted">
              {t.season} · {new Date(t.startDate).toLocaleDateString()} –{' '}
              {new Date(t.endDate).toLocaleDateString()}
            </p>
            <div className="mt-3 flex flex-wrap gap-2 text-xs">
              <Badge variant={t.fantasyEnabled ? 'emerald' : 'slate'}>
                Fantasy {t.fantasyEnabled ? 'ON' : 'OFF'}
              </Badge>
              <Badge variant={t.heroesEnabled ? 'amber' : 'slate'}>
                Heroes {t.heroesEnabled ? 'ON' : 'OFF'}
              </Badge>
            </div>
            <div className="mt-4 flex flex-wrap gap-3 text-xs font-bold">
              {t.fantasyEnabled && (
                <Link href="/fantasy" className="text-d11-red hover:underline">
                  Play fantasy →
                </Link>
              )}
              {t.heroesEnabled && (
                <Link href="/heroes" className="text-amber-700 hover:underline">
                  Pick Heroes →
                </Link>
              )}
              <Link href="/matches" className="text-d11-muted hover:text-d11-red hover:underline">
                Matches →
              </Link>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
