import { useEffect, useState, useCallback } from 'react';
import { useParams, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { Copy, Check, ArrowLeft, Radio } from 'lucide-react';
import { PageTransition } from '@/components/layout/PageTransition';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { SkeletonCard } from '@/components/ui/Skeleton';
import { ScoreHeader } from '@/components/match/ScoreHeader';
import { Scoreboard } from '@/components/match/Scoreboard';
import { RoundTimeline } from '@/components/match/RoundTimeline';
import { VictoryOverlay } from '@/components/match/VictoryOverlay';
import { matchAPI } from '@/api/client';
import { useSSE } from '@/hooks/useSSE';
import { useAuthStore } from '@/stores/authStore';
import { cn } from '@/lib/cn';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function MatchLive() {
  const { id } = useParams<{ id: string }>();
  const user = useAuthStore((s) => s.user);
  const [match, setMatch] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState(false);
  const [showVictory, setShowVictory] = useState(false);

  useEffect(() => {
    if (!id) return;
    matchAPI.getLive(id)
      .then(({ data }) => setMatch(data))
      .catch(() => {
        matchAPI.get(id).then(({ data }) => {
          const m = data.match || data;
          setMatch({
            match_id: m.id || id,
            status: m.status,
            map: m.map,
            team1_name: m.team1_name || 'Team Alpha',
            team2_name: m.team2_name || 'Team Beta',
            team1_score: m.team1_score || 0,
            team2_score: m.team2_score || 0,
            team1: data.team1 || [],
            team2: data.team2 || [],
            connect_string: m.connect_string,
            rounds: m.rounds || [],
            current_round: m.current_round,
            team1_side: m.team1_side,
            team2_side: m.team2_side,
            started_at: m.started_at,
          });
        }).catch(() => {});
      })
      .finally(() => setLoading(false));
  }, [id]);

  useSSE(`/matches/${id}/stream`, {
    enabled: !!id && (match?.status === 'live' || match?.status === 'knife_round' || match?.status === 'side_selection'),
    onMessage: (event) => {
      try {
        const update = JSON.parse(event.data);
        setMatch((prev: any) => {
          if (!prev) return update;
          return { ...prev, ...update };
        });
        if (update.status === 'finished') {
          setShowVictory(true);
          setTimeout(() => setShowVictory(false), 4000);
        }
      } catch { /* */ }
    },
  });

  const handleCopy = useCallback(() => {
    if (match?.connect_string) {
      navigator.clipboard.writeText(match.connect_string);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  }, [match]);

  if (loading) {
    return (
      <PageTransition className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="space-y-4">
          <SkeletonCard />
          <SkeletonCard />
          <div className="grid grid-cols-2 gap-4">
            <SkeletonCard />
            <SkeletonCard />
          </div>
        </div>
      </PageTransition>
    );
  }

  if (!match) {
    return (
      <PageTransition className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-16 text-center">
        <h2 className="text-xl font-bold text-[#f0f0f5] mb-2">Match not found</h2>
        <p className="text-[#a0a0b8] mb-6">This match may have been cancelled or doesn't exist.</p>
        <Link to="/history" className="text-[#ff6b2c] hover:text-[#ff8a50] transition-colors">
          View Match History
        </Link>
      </PageTransition>
    );
  }

  const isLive = match.status === 'live' || match.status === 'knife_round' || match.status === 'side_selection';
  const isFinished = match.status === 'finished';

  const team1Players = match.team1 || match.team1_players || [];
  const team2Players = match.team2 || match.team2_players || [];

  const userTeam = team1Players.find((p: any) => p.user_id === user?.id)
    ? 1
    : team2Players.find((p: any) => p.user_id === user?.id)
      ? 2
      : null;
  const winnerTeam = match.team1_score > match.team2_score
    ? 1
    : match.team2_score > match.team1_score
      ? 2
      : null;
  const isUserWinner = userTeam !== null && userTeam === winnerTeam;

  return (
    <PageTransition className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <AnimatePresence>
        {showVictory && winnerTeam && (
          <VictoryOverlay
            winnerName={winnerTeam === 1 ? match.team1_name : match.team2_name}
            isUserWinner={isUserWinner}
          />
        )}
      </AnimatePresence>

      <motion.div
        initial={{ opacity: 0, x: -8 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ delay: 0.1 }}
      >
        <Link to="/history" className="inline-flex items-center gap-1.5 text-sm text-[#5a5a72] hover:text-[#a0a0b8] transition-colors mb-6">
          <ArrowLeft className="w-4 h-4" /> Back to History
        </Link>
      </motion.div>

      <motion.div
        variants={staggerContainer}
        initial="initial"
        animate="animate"
        className="space-y-4"
      >
        {isLive && (
          <motion.div variants={staggerItem} className="flex justify-center">
            <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-red-500/10 border border-red-500/20">
              <span className="relative flex h-2 w-2">
                <span className="absolute inline-flex h-full w-full rounded-full bg-red-500 opacity-75 animate-ping" />
                <span className="relative inline-flex rounded-full h-2 w-2 bg-red-500" />
              </span>
              <span className="text-xs font-medium text-red-400 uppercase tracking-wider">Live Match</span>
              <Radio className="w-3 h-3 text-red-400" />
            </div>
          </motion.div>
        )}

        <motion.div variants={staggerItem}>
          <ScoreHeader
            team1Name={match.team1_name || 'Team Alpha'}
            team2Name={match.team2_name || 'Team Beta'}
            team1Score={match.team1_score}
            team2Score={match.team2_score}
            team1Side={match.team1_side}
            team2Side={match.team2_side}
            round={match.current_round}
            isLive={isLive}
            status={match.status}
          />
        </motion.div>

        {match.rounds && match.rounds.length > 0 && (
          <motion.div variants={staggerItem}>
            <RoundTimeline
              rounds={match.rounds}
              currentRound={match.current_round}
            />
          </motion.div>
        )}

        <motion.div variants={staggerItem} className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          <Scoreboard
            teamName={match.team1_name || 'Team Alpha'}
            side={match.team1_side}
            players={team1Players}
            highlight={user?.id}
            showMmr={isFinished}
          />
          <Scoreboard
            teamName={match.team2_name || 'Team Beta'}
            side={match.team2_side}
            players={team2Players}
            highlight={user?.id}
            showMmr={isFinished}
          />
        </motion.div>

        {match.connect_string && isLive && (
          <motion.div variants={staggerItem}>
            <Card variant="glow" className="flex flex-col sm:flex-row items-center justify-between gap-4">
              <div>
                <p className="text-xs text-[#5a5a72] uppercase tracking-widest mb-1">Connect</p>
                <p className="text-base font-mono font-bold text-[#f0f0f5]">{match.connect_string}</p>
              </div>
              <div className="flex items-center gap-2">
                <Button variant="secondary" size="sm" onClick={handleCopy}>
                  {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                  {copied ? 'Copied' : 'Copy'}
                </Button>
                <Button
                  size="sm"
                  onClick={() =>
                    window.open(
                      `steam://connect/${match.connect_string.replace('connect ', '')}`,
                      '_blank'
                    )
                  }
                >
                  Connect
                </Button>
              </div>
            </Card>
          </motion.div>
        )}
      </motion.div>
    </PageTransition>
  );
}
