'use client';

import React, { useEffect, useState } from 'react';
import { Trophy, Plus } from 'lucide-react';
import { apiRequest } from '../../../lib/api';
import { Badge } from '../../../components/Badge';
import { Button } from '../../../components/Button';
import { Modal } from '../../../components/Modal';
import { AdminImageUpload } from '../../../components/AdminImageUpload';

export default function TournamentsAdminPage() {
  const [tournaments, setTournaments] = useState<any[]>([]);
  const [teams, setTeams] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    title: '',
    code: '',
    season: '2026',
    startDate: '',
    endDate: '',
    fantasyEnabled: true,
    heroesEnabled: true,
    logoUrl: '',
    teamIds: [] as string[],
  });

  const loadData = async () => {
    try {
      setLoading(true);
      const [tRes, teamRes] = await Promise.all([apiRequest('/tournaments'), apiRequest('/teams')]);
      setTournaments(tRes.data || []);
      setTeams(teamRes.data || []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const body: any = {
        ...form,
        code: form.code.toUpperCase(),
        startDate: new Date(form.startDate).toISOString(),
        endDate: new Date(form.endDate).toISOString(),
      };
      if (!body.logoUrl) delete body.logoUrl;
      await apiRequest('/tournaments', {
        method: 'POST',
        body: JSON.stringify(body),
      });
      setIsModalOpen(false);
      setForm({
        title: '',
        code: '',
        season: '2026',
        startDate: '',
        endDate: '',
        fantasyEnabled: true,
        heroesEnabled: true,
        logoUrl: '',
        teamIds: [],
      });
      loadData();
    } catch (err: any) {
      alert(err.message || 'Failed to create tournament');
    } finally {
      setSubmitting(false);
    }
  };

  const toggleTeam = (id: string) => {
    setForm((prev) => ({
      ...prev,
      teamIds: prev.teamIds.includes(id)
        ? prev.teamIds.filter((t) => t !== id)
        : [...prev.teamIds, id],
    }));
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-white">Tournaments</h1>
          <p className="text-xs text-zinc-400 mt-1">League seasons, fantasy enablement, and Heroes configuration</p>
        </div>
        <Button onClick={() => setIsModalOpen(true)} className="gap-2">
          <Plus className="w-4 h-4" />
          <span>Create Tournament</span>
        </Button>
      </div>

      <div className="bg-zinc-900/80 border border-zinc-800 rounded-2xl overflow-hidden">
        {loading ? (
          <div className="p-8 text-center text-xs text-zinc-400">Loading tournaments...</div>
        ) : tournaments.length === 0 ? (
          <div className="p-8 text-center text-xs text-zinc-400">No tournaments found.</div>
        ) : (
          <table className="w-full text-left text-sm">
            <thead className="text-[11px] font-semibold text-zinc-400 uppercase tracking-wider bg-zinc-950/40 border-b border-zinc-800">
              <tr>
                <th className="px-5 py-3">Tournament</th>
                <th className="px-5 py-3">Code</th>
                <th className="px-5 py-3">Season</th>
                <th className="px-5 py-3">Window</th>
                <th className="px-5 py-3">Fantasy</th>
                <th className="px-5 py-3">Heroes</th>
                <th className="px-5 py-3">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-800/60 text-xs">
              {tournaments.map((t) => (
                <tr key={t._id} className="hover:bg-zinc-800/30 transition-colors">
                  <td className="px-5 py-3 font-medium text-white">
                    <span className="inline-flex items-center gap-2">
                      {t.logoUrl ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={t.logoUrl} alt="" className="h-8 w-8 rounded-lg object-cover" />
                      ) : (
                        <Trophy className="h-3.5 w-3.5 text-amber-400" />
                      )}
                      {t.title}
                    </span>
                  </td>
                  <td className="px-5 py-3 font-mono text-emerald-400">{t.code}</td>
                  <td className="px-5 py-3 text-zinc-300">{t.season}</td>
                  <td className="px-5 py-3 text-zinc-400">
                    {new Date(t.startDate).toLocaleDateString()} — {new Date(t.endDate).toLocaleDateString()}
                  </td>
                  <td className="px-5 py-3">
                    <Badge variant={t.fantasyEnabled ? 'emerald' : 'slate'}>
                      {t.fantasyEnabled ? 'ON' : 'OFF'}
                    </Badge>
                  </td>
                  <td className="px-5 py-3">
                    <Badge variant={t.heroesEnabled ? 'amber' : 'slate'}>
                      {t.heroesEnabled ? 'ON' : 'OFF'}
                    </Badge>
                  </td>
                  <td className="px-5 py-3">
                    <Badge variant="cyan">{t.status || 'ACTIVE'}</Badge>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="Create Tournament" maxWidth="max-w-xl">
        <form onSubmit={handleCreate} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-zinc-400 mb-1.5">Title *</label>
            <input
              required
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
              className="w-full px-3.5 py-2 bg-zinc-950 border border-zinc-800 rounded-xl text-sm text-white focus:outline-none focus:border-emerald-500"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-zinc-400 mb-1.5">Code *</label>
              <input
                required
                value={form.code}
                onChange={(e) => setForm({ ...form, code: e.target.value })}
                className="w-full px-3.5 py-2 bg-zinc-950 border border-zinc-800 rounded-xl text-sm text-white uppercase focus:outline-none focus:border-emerald-500"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-zinc-400 mb-1.5">Season *</label>
              <input
                required
                value={form.season}
                onChange={(e) => setForm({ ...form, season: e.target.value })}
                className="w-full px-3.5 py-2 bg-zinc-950 border border-zinc-800 rounded-xl text-sm text-white focus:outline-none focus:border-emerald-500"
              />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-zinc-400 mb-1.5">Start Date *</label>
              <input
                required
                type="date"
                value={form.startDate}
                onChange={(e) => setForm({ ...form, startDate: e.target.value })}
                className="w-full px-3.5 py-2 bg-zinc-950 border border-zinc-800 rounded-xl text-sm text-white focus:outline-none focus:border-emerald-500"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-zinc-400 mb-1.5">End Date *</label>
              <input
                required
                type="date"
                value={form.endDate}
                onChange={(e) => setForm({ ...form, endDate: e.target.value })}
                className="w-full px-3.5 py-2 bg-zinc-950 border border-zinc-800 rounded-xl text-sm text-white focus:outline-none focus:border-emerald-500"
              />
            </div>
          </div>
          <AdminImageUpload
            kind="tournaments"
            label="Tournament logo / cover"
            value={form.logoUrl}
            onChange={(logoUrl) => setForm({ ...form, logoUrl })}
            aspect="wide"
          />
          <div className="flex gap-4 text-xs text-zinc-300">
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={form.fantasyEnabled}
                onChange={(e) => setForm({ ...form, fantasyEnabled: e.target.checked })}
              />
              Fantasy enabled
            </label>
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={form.heroesEnabled}
                onChange={(e) => setForm({ ...form, heroesEnabled: e.target.checked })}
              />
              Heroes enabled
            </label>
          </div>
          {teams.length > 0 && (
            <div>
              <label className="block text-xs font-medium text-zinc-400 mb-2">Participating Teams</label>
              <div className="flex flex-wrap gap-2 max-h-32 overflow-y-auto">
                {teams.map((team) => (
                  <button
                    key={team._id}
                    type="button"
                    onClick={() => toggleTeam(team._id)}
                    className={`px-2.5 py-1 rounded-lg text-xs border transition-colors ${
                      form.teamIds.includes(team._id)
                        ? 'bg-emerald-500/15 border-emerald-500/40 text-emerald-400'
                        : 'bg-zinc-950 border-zinc-800 text-zinc-400'
                    }`}
                  >
                    {team.shortName}
                  </button>
                ))}
              </div>
            </div>
          )}
          <div className="flex justify-end gap-2 pt-2">
            <Button type="button" variant="ghost" onClick={() => setIsModalOpen(false)}>
              Cancel
            </Button>
            <Button type="submit" loading={submitting}>
              Create Tournament
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
