'use client';

import React, { useEffect, useState } from 'react';
import { Flame, Plus, Settings2, Trophy } 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 ContestsAdminPage() {
  const [activeTab, setActiveTab] = useState<'contests' | 'rules'>('contests');
  const [contests, setContests] = useState<any[]>([]);
  const [matches, setMatches] = useState<any[]>([]);
  const [rules, setRules] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const [form, setForm] = useState({
    title: '',
    matchId: '',
    entryFee: 49,
    prizePool: 10000,
    maxSlots: 250,
    maxEntriesPerUser: 1,
    lockTime: '',
  });

  const loadData = async () => {
    try {
      setLoading(true);
      const [cRes, mRes, rRes] = await Promise.all([
        apiRequest('/contests'),
        apiRequest('/matches'),
        apiRequest('/contests/rules'),
      ]);
      setContests(cRes.data || []);
      setMatches(mRes.data || []);
      setRules(rRes.data || []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const handleCreateContest = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      await apiRequest('/contests', {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          lockTime: new Date(form.lockTime).toISOString(),
        }),
      });
      setIsModalOpen(false);
      loadData();
    } catch (err: any) {
      alert(err.message || 'Failed to create 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">Contest Management & Rules</h1>
          <p className="text-xs text-zinc-400 mt-1">Configure prize pools, entry fees, and custom cricket points rules</p>
        </div>
        {activeTab === 'contests' && (
          <Button onClick={() => setIsModalOpen(true)} className="gap-2">
            <Plus className="w-4 h-4" />
            <span>Create Contest</span>
          </Button>
        )}
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-2 border-b border-zinc-800 pb-2">
        <button
          onClick={() => setActiveTab('contests')}
          className={`px-4 py-2 rounded-xl text-xs font-semibold transition-colors flex items-center gap-2 ${
            activeTab === 'contests'
              ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
              : 'text-zinc-400 hover:text-white'
          }`}
        >
          <Flame className="w-3.5 h-3.5" />
          <span>Contests Pool</span>
        </button>
        <button
          onClick={() => setActiveTab('rules')}
          className={`px-4 py-2 rounded-xl text-xs font-semibold transition-colors flex items-center gap-2 ${
            activeTab === 'rules'
              ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
              : 'text-zinc-400 hover:text-white'
          }`}
        >
          <Settings2 className="w-3.5 h-3.5" />
          <span>Configurable Scoring Rules</span>
        </button>
      </div>

      {activeTab === 'contests' ? (
        <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 contests...</div>
          ) : contests.length === 0 ? (
            <div className="p-8 text-center text-xs text-zinc-400">No contests configured.</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 Title</th>
                  <th className="px-5 py-3">Type</th>
                  <th className="px-5 py-3">Entry Fee</th>
                  <th className="px-5 py-3">Prize Pool</th>
                  <th className="px-5 py-3">Slots Filled</th>
                  <th className="px-5 py-3">Lock Deadline</th>
                  <th className="px-5 py-3">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-zinc-800/60 text-xs font-mono">
                {contests.map((c) => (
                  <tr key={c._id} className="hover:bg-zinc-800/30 transition-colors">
                    <td className="px-5 py-3 font-sans font-medium text-white">{c.title}</td>
                    <td className="px-5 py-3 font-sans">
                      <Badge variant="slate">{c.contestType}</Badge>
                    </td>
                    <td className="px-5 py-3 text-emerald-400 font-bold">
                      {c.entryFee === 0 ? 'FREE' : formatCoins(c.entryFee)}
                    </td>
                    <td className="px-5 py-3 text-white font-bold">{formatCoins(c.prizePool)}</td>
                    <td className="px-5 py-3 text-zinc-300">
                      {c.filledSlots} / {c.maxSlots}
                      <span className="text-[10px] text-zinc-400 ml-1">
                        ({Math.round((c.filledSlots / c.maxSlots) * 100)}%)
                      </span>
                    </td>
                    <td className="px-5 py-3 text-zinc-400">
                      {new Date(c.lockTime).toLocaleString('en-IN', {
                        month: 'short',
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                      })}
                    </td>
                    <td className="px-5 py-3 font-sans">
                      <Badge variant={c.status === 'OPEN' ? 'emerald' : 'slate'}>{c.status}</Badge>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      ) : (
        /* Fantasy Rules Inspector */
        <div className="space-y-4">
          {rules.map((rule) => (
            <div key={rule._id} className="bg-zinc-900/80 border border-zinc-800 rounded-2xl p-6">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="text-base font-bold text-white">{rule.name}</h3>
                  <div className="text-xs text-zinc-400 font-mono">Format: {rule.format} (Server Configured)</div>
                </div>
                <Badge variant="emerald">Default Matrix</Badge>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 text-xs">
                {/* Batting Points */}
                <div className="bg-zinc-950/60 border border-zinc-800/80 rounded-xl p-4 space-y-2">
                  <div className="font-semibold text-emerald-400 uppercase tracking-wider text-[11px] mb-2">
                    Batting Points
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Every Run:</span>
                    <span className="font-mono text-white font-bold">+{rule.batting?.run} pt</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Boundary Bonus (4):</span>
                    <span className="font-mono text-white font-bold">+{rule.batting?.boundaryBonus} pt</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Six Bonus (6):</span>
                    <span className="font-mono text-white font-bold">+{rule.batting?.sixBonus} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Half Century (50):</span>
                    <span className="font-mono text-white font-bold">+{rule.batting?.halfCenturyBonus} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Century (100):</span>
                    <span className="font-mono text-white font-bold">+{rule.batting?.centuryBonus} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Dismissal for Duck:</span>
                    <span className="font-mono text-rose-400 font-bold">{rule.batting?.duckPenalty} pts</span>
                  </div>
                </div>

                {/* Bowling Points */}
                <div className="bg-zinc-950/60 border border-zinc-800/80 rounded-xl p-4 space-y-2">
                  <div className="font-semibold text-emerald-400 uppercase tracking-wider text-[11px] mb-2">
                    Bowling Points
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Wicket (Excl. Run Out):</span>
                    <span className="font-mono text-white font-bold">+{rule.bowling?.wicket} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>LBW / Bowled Bonus:</span>
                    <span className="font-mono text-white font-bold">+{rule.bowling?.lbwBowledBonus} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Maiden Over:</span>
                    <span className="font-mono text-white font-bold">+{rule.bowling?.maidenOver} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>4 Wicket Bonus:</span>
                    <span className="font-mono text-white font-bold">+{rule.bowling?.fourWicketBonus} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>5 Wicket Bonus:</span>
                    <span className="font-mono text-white font-bold">+{rule.bowling?.fiveWicketBonus} pts</span>
                  </div>
                </div>

                {/* Fielding Points */}
                <div className="bg-zinc-950/60 border border-zinc-800/80 rounded-xl p-4 space-y-2">
                  <div className="font-semibold text-emerald-400 uppercase tracking-wider text-[11px] mb-2">
                    Fielding Points
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Catch:</span>
                    <span className="font-mono text-white font-bold">+{rule.fielding?.catch} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Stumping:</span>
                    <span className="font-mono text-white font-bold">+{rule.fielding?.stumping} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Direct Run Out:</span>
                    <span className="font-mono text-white font-bold">+{rule.fielding?.runOutDirect} pts</span>
                  </div>
                  <div className="flex justify-between text-zinc-300">
                    <span>Indirect Run Out:</span>
                    <span className="font-mono text-white font-bold">+{rule.fielding?.runOutIndirect} pts</span>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create Contest Modal */}
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="Create New Fantasy Contest">
        <form onSubmit={handleCreateContest} className="space-y-4 text-xs">
          <div>
            <label className="block text-zinc-300 uppercase font-semibold mb-1">Contest Name</label>
            <input
              type="text"
              required
              placeholder="e.g. Mega Grand Contest"
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
              className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white"
            />
          </div>

          <div>
            <label className="block text-zinc-300 uppercase font-semibold mb-1">Associated Match</label>
            <select
              required
              value={form.matchId}
              onChange={(e) => setForm({ ...form, matchId: e.target.value })}
              className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white"
            >
              <option value="">Select Match</option>
              {matches.map((m) => (
                <option key={m._id} value={m._id}>
                  {m.title}
                </option>
              ))}
            </select>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-zinc-300 uppercase font-semibold mb-1">Entry Fee (₹)</label>
              <input
                type="number"
                min="0"
                required
                value={form.entryFee}
                onChange={(e) => setForm({ ...form, entryFee: parseFloat(e.target.value) })}
                className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white font-mono"
              />
            </div>
            <div>
              <label className="block text-zinc-300 uppercase font-semibold mb-1">Prize Pool (₹)</label>
              <input
                type="number"
                min="0"
                required
                value={form.prizePool}
                onChange={(e) => setForm({ ...form, prizePool: parseFloat(e.target.value) })}
                className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white font-mono"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-zinc-300 uppercase font-semibold mb-1">Max Player Slots</label>
              <input
                type="number"
                min="2"
                required
                value={form.maxSlots}
                onChange={(e) => setForm({ ...form, maxSlots: parseInt(e.target.value) })}
                className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white font-mono"
              />
            </div>
            <div>
              <label className="block text-zinc-300 uppercase font-semibold mb-1">Lock Time</label>
              <input
                type="datetime-local"
                required
                value={form.lockTime}
                onChange={(e) => setForm({ ...form, lockTime: e.target.value })}
                className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white"
              />
            </div>
          </div>

          <div className="pt-2 flex justify-end gap-2">
            <Button type="button" variant="secondary" onClick={() => setIsModalOpen(false)}>
              Cancel
            </Button>
            <Button type="submit" loading={submitting}>
              Publish Contest
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
