import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { ArrowLeft, Clock, MapPin, Swords, Trophy, Skull, Target, Flame, Star, Crosshair } from 'lucide-react';
import { PageTransition } from '@/components/layout/PageTransition';
import { Card } from '@/components/ui/Card';
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 { matchAPI } from '@/api/client';
import { useAuthStore } from '@/stores/authStore';
import { useCountUp } from '@/hooks/useCountUp';
import { cn } from '@/lib/cn';
import { staggerContainer, staggerItem } from '@/lib/animations';
import type { ReactNode } from 'react';

function StatCard({ label, value, icon, color }: { label: string; value: number | string; icon?: ReactNode; color?: string }) {
  const numValue = typeof value === 'number' ? value : 0;
  const animated = useCountUp(numValue);
  return (
    <Card className="text-center relative overflow-hidden group">
      <div className={cn(
        'absolute top-0 left-0 right-0 h-0.5 opacity-50',
        color || 'bg-[#ff6b2c]'
      )} />
      {icon && (
        <div className="flex justify-center mb-2 text-[#5a5a72] opacity-40 group-hover:opacity-60 transition-opacity">
          {icon}
        </div>
      )}
      <p className="text-2xl font-mono font-bold text-[#f0f0f5]">
        {typeof value === 'number' ? animated : value}
      </p>
      <p className="text-[10px] text-[#5a5a72] uppercase tracking-widest mt-1.5 font-medium">{label}</p>
    </Card>
  );
}

export default function MatchDetails() {
  const { id } = useParams<{ id: string }>();
  const user = useAuthStore((s) => s.user);
  const [matchData, setMatchData] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!id) return;
    matchAPI.get(id)
      .then(({ data }) => setMatchData(data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [id]);

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

  if (!matchData) {
    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 doesn't exist or has been removed.</p>
        <Link to="/history" className="text-[#ff6b2c] hover:text-[#ff8a50] transition-colors">
          View Match History
        </Link>
      </PageTransition>
    );
  }

  const match = matchData.match || matchData;
  const team1Players = (matchData.team1 || []).map((p: any) => ({
    user_id: p.user_id || p.UserID,
    username: p.user?.username || p.User?.Username || p.username || 'Unknown',
    avatar_url: p.user?.steam_avatar_url || p.User?.SteamAvatarURL || p.avatar_url,
    team: 1,
    kills: p.stats?.kills ?? p.kills ?? 0,
    deaths: p.stats?.deaths ?? p.deaths ?? 0,
    assists: p.stats?.assists ?? p.assists ?? 0,
    headshots: p.stats?.headshots ?? p.headshots ?? 0,
    damage: p.stats?.damage ?? p.damage ?? 0,
    mvps: p.stats?.mvps ?? p.mvps ?? 0,
    mmr_delta: p.stats?.mmr_delta ?? p.mmr_delta ?? 0,
  }));
  const team2Players = (matchData.team2 || []).map((p: any) => ({
    user_id: p.user_id || p.UserID,
    username: p.user?.username || p.User?.Username || p.username || 'Unknown',
    avatar_url: p.user?.steam_avatar_url || p.User?.SteamAvatarURL || p.avatar_url,
    team: 2,
    kills: p.stats?.kills ?? p.kills ?? 0,
    deaths: p.stats?.deaths ?? p.deaths ?? 0,
    assists: p.stats?.assists ?? p.assists ?? 0,
    headshots: p.stats?.headshots ?? p.headshots ?? 0,
    damage: p.stats?.damage ?? p.damage ?? 0,
    mvps: p.stats?.mvps ?? p.mvps ?? 0,
    mmr_delta: p.stats?.mmr_delta ?? p.mmr_delta ?? 0,
  }));

  const allPlayers = [...team1Players, ...team2Players];
  const userStats = allPlayers.find((p: any) => p.user_id === user?.id);
  const userTeam = team1Players.find((p: any) => p.user_id === user?.id)
    ? 1
    : team2Players.find((p: any) => p.user_id === user?.id)
      ? 2
      : null;

  const team1Score = match.team1_score || match.Team1Score || 0;
  const team2Score = match.team2_score || match.Team2Score || 0;
  const totalRounds = team1Score + team2Score;
  const isWin = userTeam && (
    (userTeam === 1 && team1Score > team2Score) ||
    (userTeam === 2 && team2Score > team1Score)
  );
  const isDraw = team1Score === team2Score;
  const mapName = (match.map || match.Map || '').replace('de_', '');

  return (
    <PageTransition className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <motion.div
        initial={{ opacity: 0, x: -8 }}
        animate={{ opacity: 1, x: 0 }}
      >
        <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-6"
      >
        <motion.div variants={staggerItem}>
          <Card className="relative overflow-hidden">
            <div className={cn(
              'absolute top-0 left-0 right-0 h-1',
              isWin ? 'bg-gradient-to-r from-emerald-500 to-emerald-600' :
              isDraw ? 'bg-gradient-to-r from-[#1e1e30] to-[#0f0f18]' :
              userTeam ? 'bg-gradient-to-r from-red-500 to-red-600' :
              'bg-gradient-to-r from-[#ff6b2c] to-[#e85d1c]'
            )} />

            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
              <div>
                <div className="flex flex-wrap items-center gap-3 mb-2">
                  <h1 className="text-xl font-bold text-[#f0f0f5] capitalize">
                    {mapName}
                  </h1>
                  <Badge variant="default">
                    <MapPin className="w-3 h-3 mr-1" />
                    {match.game_mode || match.GameMode || 'Competitive'}
                  </Badge>
                </div>
                <div className="flex items-center gap-3 text-sm text-[#5a5a72]">
                  {match.finished_at && (
                    <span className="flex items-center gap-1">
                      <Clock className="w-3.5 h-3.5" />
                      {new Date(match.finished_at).toLocaleString()}
                    </span>
                  )}
                  {match.duration && (
                    <span>&middot; {match.duration}</span>
                  )}
                  <span>&middot; {totalRounds} rounds</span>
                </div>
              </div>
              {userTeam && (
                <motion.div
                  initial={{ scale: 0.8, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  transition={{ delay: 0.3, type: 'spring', stiffness: 200 }}
                >
                  <Badge
                    variant={isWin ? 'success' : isDraw ? 'default' : 'danger'}
                    className="text-base px-5 py-2"
                  >
                    {isWin ? (
                      <><Trophy className="w-4 h-4 mr-1.5" /> VICTORY</>
                    ) : isDraw ? (
                      <><Swords className="w-4 h-4 mr-1.5" /> DRAW</>
                    ) : (
                      <><Skull className="w-4 h-4 mr-1.5" /> DEFEAT</>
                    )}
                    {userStats?.mmr_delta ? (
                      <span className="ml-2 opacity-80">
                        ({userStats.mmr_delta > 0 ? '+' : ''}{userStats.mmr_delta} MMR)
                      </span>
                    ) : null}
                  </Badge>
                </motion.div>
              )}
            </div>
          </Card>
        </motion.div>

        <motion.div variants={staggerItem}>
          <ScoreHeader
            team1Name={match.team1_name || match.Team1Name || 'Team Alpha'}
            team2Name={match.team2_name || match.Team2Name || 'Team Beta'}
            team1Score={team1Score}
            team2Score={team2Score}
            status="Finished"
          />
        </motion.div>

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

        {userStats && (
          <motion.div variants={staggerItem}>
            <h2 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest mb-4">Your Performance</h2>
            <motion.div
              variants={staggerContainer}
              initial="initial"
              animate="animate"
              className="grid grid-cols-3 sm:grid-cols-6 gap-3"
            >
              {[
                {
                  label: 'Kills',
                  value: userStats.kills,
                  icon: <Target className="w-4 h-4" />,
                  color: 'bg-[#ff6b2c]',
                },
                {
                  label: 'Deaths',
                  value: userStats.deaths,
                  icon: <Skull className="w-4 h-4" />,
                  color: 'bg-red-500',
                },
                {
                  label: 'Assists',
                  value: userStats.assists,
                  icon: <Swords className="w-4 h-4" />,
                  color: 'bg-blue-500',
                },
                {
                  label: 'HS%',
                  value: userStats.kills > 0
                    ? `${Math.round((userStats.headshots / userStats.kills) * 100)}%`
                    : '0%',
                  icon: <Crosshair className="w-4 h-4" />,
                  color: 'bg-purple-500',
                },
                {
                  label: 'ADR',
                  value: userStats.damage
                    ? Math.round(userStats.damage / Math.max(1, totalRounds))
                    : 0,
                  icon: <Flame className="w-4 h-4" />,
                  color: 'bg-[#ff6b2c]',
                },
                {
                  label: 'MVPs',
                  value: userStats.mvps || 0,
                  icon: <Star className="w-4 h-4" />,
                  color: 'bg-yellow-500',
                },
              ].map((stat) => (
                <motion.div key={stat.label} variants={staggerItem}>
                  <StatCard {...stat} />
                </motion.div>
              ))}
            </motion.div>
          </motion.div>
        )}

        <motion.div variants={staggerItem}>
          <h2 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest mb-4">Scoreboard</h2>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <Scoreboard
              teamName={match.team1_name || match.Team1Name || 'Team Alpha'}
              players={team1Players}
              highlight={user?.id}
              showMmr
            />
            <Scoreboard
              teamName={match.team2_name || match.Team2Name || 'Team Beta'}
              players={team2Players}
              highlight={user?.id}
              showMmr
            />
          </div>
        </motion.div>
      </motion.div>
    </PageTransition>
  );
}
