import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { Gamepad2, XCircle, RotateCcw } from 'lucide-react';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { Modal } from '@/components/ui/Modal';
import { Input } from '@/components/ui/Input';
import { SkeletonRow } from '@/components/ui/Skeleton';
import { useToast } from '@/components/ui/Toast';
import { LiveIndicator } from '@/components/match/LiveIndicator';
import { adminAPI } from '@/api/client';
import { formatRelativeTime } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function MatchAdmin() {
  const { toast } = useToast();
  const [matches, setMatches] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [cancelModal, setCancelModal] = useState<string | null>(null);
  const [cancelReason, setCancelReason] = useState('');

  useEffect(() => {
    adminAPI.getMatches().then(({ data }) => {
      setMatches(data.matches || []);
    }).catch(() => {}).finally(() => setLoading(false));
  }, []);

  async function handleCancel() {
    if (!cancelModal || !cancelReason) return;
    try {
      await adminAPI.cancelMatch(cancelModal, { reason: cancelReason });
      toast('Match cancelled', 'success');
      setCancelModal(null);
      setCancelReason('');
    } catch {
      toast('Failed to cancel match', 'error');
    }
  }

  async function handleNullify(matchId: string) {
    try {
      await adminAPI.nullifyMatch(matchId, { reason: 'Admin nullification' });
      toast('Match nullified, MMR reverted', 'success');
    } catch {
      toast('Failed to nullify match', 'error');
    }
  }

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

      {loading ? (
        <div className="space-y-3">{[...Array(5)].map((_, i) => <SkeletonRow key={i} />)}</div>
      ) : matches.length > 0 ? (
        <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-2">
          {matches.map((match) => {
            const isLive = match.status === 'live';
            return (
              <motion.div key={match.id} variants={staggerItem}>
                <Card className="flex items-center gap-4">
                  <Gamepad2 className="w-5 h-5 text-text-muted flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-text-primary capitalize">
                      {(match.map || '').replace('de_', '')}
                    </p>
                    <p className="text-xs text-text-muted">
                      {match.team1_score}-{match.team2_score} · {match.game_mode}
                    </p>
                  </div>
                  {isLive ? <LiveIndicator size="sm" /> : (
                    <Badge variant={match.status === 'finished' ? 'success' : 'default'}>
                      {match.status}
                    </Badge>
                  )}
                  <span className="text-xs text-text-muted">
                    {match.created_at ? formatRelativeTime(match.created_at) : ''}
                  </span>
                  {isLive && (
                    <Button variant="danger" size="sm" onClick={() => setCancelModal(match.id)}>
                      <XCircle className="w-3.5 h-3.5" /> Cancel
                    </Button>
                  )}
                  {match.status === 'finished' && (
                    <Button variant="secondary" size="sm" onClick={() => handleNullify(match.id)}>
                      <RotateCcw className="w-3.5 h-3.5" /> Nullify
                    </Button>
                  )}
                </Card>
              </motion.div>
            );
          })}
        </motion.div>
      ) : (
        <Card className="text-center py-12">
          <Gamepad2 className="w-12 h-12 text-text-muted/20 mx-auto mb-3" />
          <p className="text-text-secondary">No matches found</p>
        </Card>
      )}

      <Modal open={!!cancelModal} onClose={() => setCancelModal(null)} title="Cancel Match">
        <p className="text-sm text-text-secondary mb-4">This will force-cancel the match and notify all players. This action cannot be undone.</p>
        <Input label="Reason" value={cancelReason} onChange={(e) => setCancelReason(e.target.value)} />
        <div className="flex justify-end gap-3 mt-4">
          <Button variant="secondary" onClick={() => setCancelModal(null)}>Nevermind</Button>
          <Button variant="danger" onClick={handleCancel} disabled={!cancelReason}>Cancel Match</Button>
        </div>
      </Modal>
    </div>
  );
}
