import { useEffect, useState, type FormEvent } from 'react';
import { motion } from 'framer-motion';
import { Card } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Toggle } from '@/components/ui/Toggle';
import { Button } from '@/components/ui/Button';
import { SkeletonCard } from '@/components/ui/Skeleton';
import { useToast } from '@/components/ui/Toast';
import { adminAPI } from '@/api/client';
import { staggerContainer, staggerItem } from '@/lib/animations';

const fields = [
  { key: 'k_factor_base', label: 'K-Factor (Base)', desc: 'Base K-factor for MMR changes' },
  { key: 'k_factor_new_player', label: 'K-Factor (New Player)', desc: 'Higher K for first N matches' },
  { key: 'new_player_threshold', label: 'New Player Threshold', desc: 'Matches before switching to base K' },
  { key: 'k_factor_high_mmr', label: 'K-Factor (High MMR)', desc: 'Lower K for high-MMR players' },
  { key: 'high_mmr_threshold', label: 'High MMR Threshold', desc: 'MMR above which reduced K applies' },
  { key: 'placement_matches', label: 'Placement Matches', desc: 'Number of placement matches' },
  { key: 'placement_k_factor', label: 'Placement K-Factor', desc: 'K-factor during placement' },
  { key: 'min_mmr', label: 'Min MMR', desc: 'MMR floor' },
  { key: 'max_mmr', label: 'Max MMR', desc: 'MMR ceiling' },
  { key: 'default_mmr', label: 'Default MMR', desc: 'Starting MMR for new players' },
  { key: 'round_score_weight', label: 'Round Score Weight', desc: 'Impact of round score margin (0-1)' },
  { key: 'individual_perf_weight', label: 'Individual Perf Weight', desc: 'Impact of individual performance (0-1)' },
  { key: 'streak_bonus', label: 'Streak Bonus', desc: 'Extra MMR % per consecutive win' },
  { key: 'streak_cap', label: 'Streak Cap', desc: 'Max win streak multiplier' },
  { key: 'decay_days', label: 'Decay Days', desc: 'Days before decay starts' },
  { key: 'decay_per_day', label: 'Decay Per Day', desc: 'MMR lost per day of inactivity' },
  { key: 'decay_floor', label: 'Decay Floor', desc: "MMR won't decay below this" },
];

export default function EloConfig() {
  const { toast } = useToast();
  const [config, setConfig] = useState<Record<string, any>>({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    adminAPI.getEloConfig().then(({ data }) => setConfig(data)).catch(() => {}).finally(() => setLoading(false));
  }, []);

  async function handleSave(e: FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      await adminAPI.updateEloConfig(config);
      toast('Elo configuration saved', 'success');
    } catch {
      toast('Failed to save configuration', 'error');
    } finally {
      setSaving(false);
    }
  }

  if (loading) return <div className="p-6 space-y-4">{[...Array(3)].map((_, i) => <SkeletonCard key={i} />)}</div>;

  return (
    <div className="p-6">
      <h1 className="text-xl font-bold text-text-primary mb-6">Elo Configuration</h1>

      <form onSubmit={handleSave}>
        <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-6">
          <motion.div variants={staggerItem}>
            <Card>
              <h2 className="text-sm font-bold text-text-muted uppercase tracking-widest mb-4">Parameters</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {fields.map((f) => (
                  <div key={f.key}>
                    <Input
                      label={f.label}
                      type="number"
                      value={config[f.key] ?? ''}
                      onChange={(e) => setConfig((prev) => ({ ...prev, [f.key]: parseFloat(e.target.value) || 0 }))}
                    />
                    <p className="text-[10px] text-text-muted mt-0.5 pl-1">{f.desc}</p>
                  </div>
                ))}
              </div>
            </Card>
          </motion.div>

          <motion.div variants={staggerItem}>
            <Card>
              <h2 className="text-sm font-bold text-text-muted uppercase tracking-widest mb-4">Decay</h2>
              <Toggle
                checked={config.decay_enabled ?? true}
                onChange={(v) => setConfig((prev) => ({ ...prev, decay_enabled: v }))}
                label="Enable MMR Decay"
              />
            </Card>
          </motion.div>

          <div className="flex justify-end">
            <Button type="submit" loading={saving} size="lg">Apply Changes</Button>
          </div>
        </motion.div>
      </form>
    </div>
  );
}
