'use client';

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

export default function HeroesAdminPage() {
  const [contests, setContests] = useState<any[]>([]);
  const [tournaments, setTournaments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    title: '',
    tournamentId: '',
    entryFee: 0,
    prizePool: 0,
    maxSlots: 1000,
    selectionDeadline: '',
    lockTime: '',
  });

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

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

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      await apiRequest('/heroes', {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          entryFee: Number(form.entryFee),
          prizePool: Number(form.prizePool),
          maxSlots: Number(form.maxSlots),
          selectionDeadline: new Date(form.selectionDeadline).toISOString(),
          lockTime: new Date(form.lockTime).toISOString(),
        }),
      });
      setIsModalOpen(false);
      loadData();
    } catch (err: any) {
      alert(err.message || 'Failed to create heroes contest');
    } finally {
      setSubmitting(false);
    }
  };

  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">Pick Your Heroes</h1>
          <p className="text-xs text-zinc-400 mt-1">
            Contest setup, deadlines, slot caps, and lock configuration
          </p>
        </div>
        <Button onClick={() => setIsModalOpen(true)} className="gap-2">
          <Plus className="w-4 h-4" />
          <span>Create Heroes Contest</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 heroes contests...</div>
        ) : contests.length === 0 ? (
          <div className="p-8 text-center text-xs text-zinc-400">No heroes contests 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">Contest</th>
                <th className="px-5 py-3">Tournament</th>
                <th className="px-5 py-3">Entry / Prize</th>
                <th className="px-5 py-3">Slots</th>
                <th className="px-5 py-3">Deadline</th>
                <th className="px-5 py-3">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-800/60 text-xs">
              {contests.map((c) => (
                <tr key={c._id} className="hover:bg-zinc-800/30 transition-colors">
                  <td className="px-5 py-3 font-medium text-white flex items-center gap-2">
                    <Award className="w-3.5 h-3.5 text-amber-400" />
                    {c.title}
                  </td>
                  <td className="px-5 py-3 text-zinc-300">
                    {c.tournamentId?.title || c.tournamentId?.code || '—'}
                  </td>
                  <td className="px-5 py-3 font-mono text-zinc-300">
                    {formatCoins(c.entryFee)} / {formatCoins(c.prizePool)}
                  </td>
                  <td className="px-5 py-3 text-zinc-400">
                    {c.filledSlots || 0}/{c.maxSlots}
                  </td>
                  <td className="px-5 py-3 text-zinc-400">
                    {new Date(c.selectionDeadline).toLocaleString()}
                  </td>
                  <td className="px-5 py-3">
                    <Badge
                      variant={
                        c.status === 'OPEN' ? 'emerald' : c.status === 'LOCKED' ? 'amber' : 'slate'
                      }
                    >
                      {c.status}
                    </Badge>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="Create Heroes Contest">
        <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>
            <label className="block text-xs font-medium text-zinc-400 mb-1.5">Tournament *</label>
            <select
              required
              value={form.tournamentId}
              onChange={(e) => setForm({ ...form, tournamentId: 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"
            >
              <option value="">Select tournament</option>
              {tournaments.map((t) => (
                <option key={t._id} value={t._id}>
                  {t.title} ({t.code})
                </option>
              ))}
            </select>
          </div>
          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className="block text-xs font-medium text-zinc-400 mb-1.5">Entry Fee</label>
              <input
                type="number"
                min={0}
                value={form.entryFee}
                onChange={(e) => setForm({ ...form, entryFee: Number(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">Prize Pool</label>
              <input
                type="number"
                min={0}
                value={form.prizePool}
                onChange={(e) => setForm({ ...form, prizePool: Number(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">Max Slots</label>
              <input
                type="number"
                min={2}
                value={form.maxSlots}
                onChange={(e) => setForm({ ...form, maxSlots: Number(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">Selection Deadline *</label>
              <input
                required
                type="datetime-local"
                value={form.selectionDeadline}
                onChange={(e) => setForm({ ...form, selectionDeadline: 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">Lock Time *</label>
              <input
                required
                type="datetime-local"
                value={form.lockTime}
                onChange={(e) => setForm({ ...form, lockTime: 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="flex justify-end gap-2 pt-2">
            <Button type="button" variant="ghost" onClick={() => setIsModalOpen(false)}>
              Cancel
            </Button>
            <Button type="submit" loading={submitting}>
              Create Contest
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
