import { useEffect, useState, useMemo } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import {
  Trophy, Target, Gamepad2, Flame, ArrowRight, ChevronRight,
  Swords, Zap, TrendingUp, TrendingDown, Minus, Clock, Map,
  BarChart3, History, Crosshair
} from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { MockToggle } from '@/components/dev/MockToggle';
import { useAuthStore } from '@/stores/authStore';
import { useMockStore } from '@/stores/mockStore';
import { profileAPI, matchAPI } from '@/api/client';
import { cn } from '@/lib/cn';
import { getRankTier, formatRelativeTime } from '@/lib/constants';

interface RecentMatch {
  id: string;
  map: string;
  result: 'win' | 'loss' | 'draw';
  team1_score: number;
  team2_score: number;
  mmr_delta: number;
  kills: number;
  deaths: number;
  assists: number;
  finished_at: string;
}

const stagger = { initial: {}, animate: { transition: { staggerChildren: 0.04, delayChildren: 0.02 } } };
const fadeUp = {
  initial: { opacity: 0, y: 14 },
  animate: { opacity: 1, y: 0, transition: { type: 'spring' as const, stiffness: 300, damping: 24 } },
};

function generateMockDashboard() {
  return {
    user: {
      username: 'ProPlayer',
      mmr: 1850,
      wins: 142,
      losses: 98,
      matches_played: 240,
      current_streak: 4,
      placement_done: true,
      steam_avatar_url: null,
    },
    matches: [
      { id: 'm1', map: 'de_mirage', result: 'win' as const, team1_score: 16, team2_score: 12, mmr_delta: 24, kills: 28, deaths: 14, assists: 6, finished_at: new Date(Date.now() - 3600000).toISOString() },
      { id: 'm2', map: 'de_dust2', result: 'win' as const, team1_score: 16, team2_score: 8, mmr_delta: 26, kills: 22, deaths: 10, assists: 9, finished_at: new Date(Date.now() - 7200000).toISOString() },
      { id: 'm3', map: 'de_inferno', result: 'loss' as const, team1_score: 11, team2_score: 16, mmr_delta: -20, kills: 16, deaths: 20, assists: 4, finished_at: new Date(Date.now() - 18000000).toISOString() },
      { id: 'm4', map: 'de_nuke', result: 'win' as const, team1_score: 16, team2_score: 14, mmr_delta: 22, kills: 25, deaths: 18, assists: 7, finished_at: new Date(Date.now() - 86400000).toISOString() },
      { id: 'm5', map: 'de_anubis', result: 'loss' as const, team1_score: 9, team2_score: 16, mmr_delta: -23, kills: 12, deaths: 19, assists: 3, finished_at: new Date(Date.now() - 172800000).toISOString() },
    ],
  };
}

function WinRateRing({ wins, losses, size = 80 }: { wins: number; losses: number; size?: number }) {
  const total = wins + losses;
  const rate = total > 0 ? Math.round((wins / total) * 100) : 0;
  const r = size * 0.42;
  const circumference = 2 * Math.PI * r;
  const strokeDashoffset = circumference - (rate / 100) * circumference;

  return (
    <div className="relative" style={{ width: size, height: size }}>
      <svg className="w-full h-full -rotate-90" viewBox={`0 0 ${size} ${size}`}>
        <circle cx={size / 2} cy={size / 2} r={r} stroke="#1a1a2a" strokeWidth={size * 0.06} fill="none" />
        <motion.circle
          cx={size / 2} cy={size / 2} r={r} stroke="url(#wr-gradient)" strokeWidth={size * 0.06} fill="none" strokeLinecap="round"
          strokeDasharray={circumference}
          initial={{ strokeDashoffset: circumference }}
          animate={{ strokeDashoffset }}
          transition={{ duration: 1.8, ease: [0.16, 1, 0.3, 1], delay: 0.3 }}
        />
        <defs>
          <linearGradient id="wr-gradient" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" stopColor="#ff6b2c" />
            <stop offset="100%" stopColor="#ff8a50" />
          </linearGradient>
        </defs>
      </svg>
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <span
          className="font-black text-[#f0f0f5] stat-number leading-none"
          style={{ fontSize: size * 0.22 }}
        >
          {rate}%
        </span>
      </div>
    </div>
  );
}

export default function Dashboard() {
  const navigate = useNavigate();
  const realUser = useAuthStore((s) => s.user);
  const updateUser = useAuthStore((s) => s.updateUser);
  const [recentMatches, setRecentMatches] = useState<RecentMatch[]>([]);
  const [loading, setLoading] = useState(true);
  const useMock = useMockStore((s) => s.enabled);

  const mockData = useMemo(() => generateMockDashboard(), []);

  useEffect(() => {
    profileAPI.me().then(({ data }) => updateUser(data)).catch(() => {});
  }, [updateUser]);

  useEffect(() => {
    matchAPI.list({ page: 1 }).then(({ data }) => {
      const entries = (data.matches || []).slice(0, 5);
      const mapped: RecentMatch[] = entries.map((entry: any) => {
        const m = entry.match || entry;
        const p = entry.player || {};
        const s = entry.stats || {};
        const team1 = m.team1_score ?? 0;
        const team2 = m.team2_score ?? 0;
        const isDraw = team1 === team2;
        const won = p.team === 1 ? team1 > team2 : team2 > team1;
        return {
          id: m.id,
          map: m.map ?? '',
          result: isDraw ? 'draw' : won ? 'win' : 'loss',
          team1_score: team1,
          team2_score: team2,
          mmr_delta: p.mmr_delta ?? 0,
          kills: s.kills ?? 0,
          deaths: s.deaths ?? 0,
          assists: s.assists ?? 0,
          finished_at: m.finished_at ?? m.created_at ?? '',
        };
      });
      setRecentMatches(mapped);
    }).catch(() => {}).finally(() => setLoading(false));
  }, []);

  const user = useMock ? { ...realUser, ...mockData.user } : realUser;
  const displayMatches = useMock ? mockData.matches : recentMatches;

  if (!user) return null;

  const rank = getRankTier(user.mmr, user.placement_done);
  const total = user.wins + user.losses;
  const kd = total > 0 ? (user.wins / Math.max(user.losses, 1)).toFixed(2) : '0.00';

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <MockToggle />
      <motion.div variants={stagger} initial="initial" animate="animate">

        <motion.div variants={fadeUp} className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-8">
          <div>
            <h1 className="text-2xl sm:text-3xl font-black tracking-tight text-[#f0f0f5] font-display">
              {user.username}
            </h1>
            <p className="text-[#5a5a72] text-sm mt-1 font-medium flex items-center gap-2">
              <span className="w-2 h-2 rounded-full" style={{ background: rank.color, boxShadow: `0 0 8px ${rank.color}50` }} />
              <span style={{ color: rank.color }} className="font-bold">{rank.name}</span>
              <span className="text-[#3a3a4e]">/</span>
              {user.mmr} MMR
            </p>
          </div>
          <div className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => navigate('/history')}
            >
              <History className="w-3.5 h-3.5" />
              History
            </Button>
            <Button
              size="lg"
              glow
              onClick={() => navigate('/queue?mode=competitive')}
              className="px-8"
            >
              <Zap className="w-4 h-4" />
              Play Now
            </Button>
          </div>
        </motion.div>

        <motion.div variants={fadeUp} className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-[1px] bg-border rounded-2xl overflow-hidden border border-border mb-6">
          <div className="bg-bg-card p-4 sm:p-5 relative overflow-hidden">
            <div
              className="absolute top-0 left-1/2 -translate-x-1/2 w-32 h-16 pointer-events-none rounded-full blur-2xl"
              style={{ background: `${rank.color}10` }}
            />
            <div className="relative flex items-center gap-3">
              <div
                className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
                style={{
                  background: `${rank.color}12`,
                  border: `1px solid ${rank.color}25`,
                }}
              >
                <Trophy className="w-5 h-5" style={{ color: rank.color }} />
              </div>
              <div className="min-w-0">
                <p className="text-2xl font-black text-[#f0f0f5] stat-number font-display leading-none">{user.mmr}</p>
                <p className="text-[10px] font-bold uppercase tracking-[0.12em] mt-0.5" style={{ color: rank.color }}>
                  {rank.name}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-bg-card p-4 sm:p-5">
            <div className="flex items-center gap-3">
              <WinRateRing wins={user.wins} losses={user.losses} size={44} />
              <div className="min-w-0">
                <p className="text-[10px] font-bold text-[#5a5a72] uppercase tracking-wider">Win Rate</p>
                <p className="text-xs text-[#a0a0b8] font-semibold mt-0.5">
                  {user.wins}W, {user.losses}L
                </p>
              </div>
            </div>
          </div>

          <div className="bg-bg-card p-4 sm:p-5">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-[#6366f1]/10 border border-[#6366f1]/20 flex items-center justify-center flex-shrink-0">
                <Target className="w-5 h-5 text-[#6366f1]" />
              </div>
              <div className="min-w-0">
                <p className="text-2xl font-black text-[#f0f0f5] stat-number font-display leading-none">{user.matches_played}</p>
                <p className="text-[10px] font-bold text-[#5a5a72] uppercase tracking-wider mt-0.5">Matches</p>
              </div>
            </div>
          </div>

          <div className="bg-bg-card p-4 sm:p-5">
            <div className="flex items-center gap-3">
              <div className={cn(
                'w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0',
                user.current_streak > 0
                  ? 'bg-emerald-500/10 border border-emerald-500/20'
                  : user.current_streak < 0
                  ? 'bg-red-500/10 border border-red-500/20'
                  : 'bg-[#1a1a2a] border border-border'
              )}>
                <Flame className={cn(
                  'w-5 h-5',
                  user.current_streak > 0 ? 'text-emerald-400' : user.current_streak < 0 ? 'text-red-400' : 'text-[#5a5a72]'
                )} />
              </div>
              <div className="min-w-0">
                <p className="text-2xl font-black text-[#f0f0f5] stat-number font-display leading-none">
                  {Math.abs(user.current_streak)}
                </p>
                <p className={cn(
                  'text-[10px] font-bold uppercase tracking-wider mt-0.5',
                  user.current_streak > 0 ? 'text-emerald-400' : user.current_streak < 0 ? 'text-red-400' : 'text-[#5a5a72]'
                )}>
                  {user.current_streak > 0 ? 'Win streak' : user.current_streak < 0 ? 'Loss streak' : 'Streak'}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-bg-card p-4 sm:p-5">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-[#22d3ee]/10 border border-[#22d3ee]/20 flex items-center justify-center flex-shrink-0">
                <BarChart3 className="w-5 h-5 text-[#22d3ee]" />
              </div>
              <div className="min-w-0">
                <p className="text-2xl font-black text-[#f0f0f5] stat-number font-display leading-none">{kd}</p>
                <p className="text-[10px] font-bold text-[#5a5a72] uppercase tracking-wider mt-0.5">W/L Ratio</p>
              </div>
            </div>
          </div>
        </motion.div>

        <motion.div variants={fadeUp} className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-8">
          {[
            { label: 'Competitive', desc: '5v5 Ranked', icon: Crosshair, href: '/queue?mode=competitive', color: '#ff6b2c' },
            { label: 'Casual', desc: '5v5 Unranked', icon: Gamepad2, href: '/queue?mode=casual', color: '#6366f1' },
            { label: 'Leaderboard', desc: 'View rankings', icon: Trophy, href: '/leaderboard', color: '#f59e0b' },
            { label: 'Profile', desc: 'View stats', icon: BarChart3, href: '/profile', color: '#22d3ee' },
          ].map((action) => (
            <Link
              key={action.label}
              to={action.href}
              className="group relative rounded-xl border border-border bg-bg-card p-4 hover:border-border-hover hover:bg-bg-card-hover transition-all duration-300 overflow-hidden"
            >
              <div
                className="absolute top-0 left-1/2 -translate-x-1/2 w-24 h-12 rounded-full blur-2xl opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none"
                style={{ background: `${action.color}15` }}
              />
              <div className="relative">
                <action.icon className="w-4 h-4 mb-3" style={{ color: action.color }} />
                <p className="text-sm font-bold text-[#f0f0f5] mb-0.5">{action.label}</p>
                <p className="text-[10px] text-[#5a5a72] font-medium">{action.desc}</p>
              </div>
              <ArrowRight className="absolute top-4 right-4 w-3.5 h-3.5 text-[#3a3a4e] group-hover:text-[#5a5a72] group-hover:translate-x-0.5 transition-all duration-200" />
            </Link>
          ))}
        </motion.div>

        <motion.div variants={fadeUp}>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xs font-extrabold text-[#5a5a72] uppercase tracking-[0.15em]">
              Recent Matches
            </h2>
            {displayMatches.length > 0 && (
              <Link to="/history" className="text-xs text-[#ff6b2c] hover:text-[#ff8a50] flex items-center gap-1 transition-colors font-bold">
                View all <ChevronRight className="w-3.5 h-3.5" />
              </Link>
            )}
          </div>

          {loading ? (
            <div className="space-y-2">
              {[...Array(3)].map((_, i) => (
                <div key={i} className="h-14 rounded-xl animate-shimmer" />
              ))}
            </div>
          ) : displayMatches.length > 0 ? (
            <div className="rounded-2xl border border-border overflow-hidden bg-bg-card">
              <div className="hidden sm:grid grid-cols-[60px_1fr_80px_70px_90px_80px] gap-3 px-5 py-2.5 text-[9px] font-bold text-[#3a3a4e] uppercase tracking-[0.12em] border-b border-border bg-bg-surface/50">
                <span>Result</span>
                <span>Map</span>
                <span>Score</span>
                <span>MMR</span>
                <span>K / D / A</span>
                <span className="text-right">Time</span>
              </div>

              {displayMatches.map((match, i) => (
                <Link key={match.id} to={`/match/${match.id}`}>
                  <motion.div
                    initial={{ opacity: 0, x: -8 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: i * 0.04 }}
                    className={cn(
                      'grid grid-cols-[60px_1fr_80px_70px_90px_80px] gap-3 items-center px-5 py-3 hover:bg-white/[0.015] transition-colors cursor-pointer',
                      i < displayMatches.length - 1 && 'border-b border-border/50'
                    )}
                  >
                    <span className={cn(
                      'text-[10px] font-extrabold uppercase w-12 text-center py-1 rounded-md tracking-wide',
                      match.result === 'win'
                        ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/15'
                        : match.result === 'loss'
                        ? 'bg-red-500/10 text-red-400 border border-red-500/15'
                        : 'bg-[#1a1a2a] text-[#5a5a72] border border-border'
                    )}>
                      {match.result === 'win' ? 'WIN' : match.result === 'loss' ? 'LOSS' : 'DRAW'}
                    </span>

                    <div className="flex items-center gap-2 min-w-0">
                      <Map className="w-3.5 h-3.5 text-[#3a3a4e] flex-shrink-0" />
                      <span className="text-sm text-[#f0f0f5] font-semibold capitalize truncate">
                        {match.map.replace('de_', '')}
                      </span>
                    </div>

                    <span className="text-sm font-mono text-[#f0f0f5] font-bold">
                      {match.team1_score}
                      <span className="text-[#3a3a4e] mx-0.5">:</span>
                      {match.team2_score}
                    </span>

                    <span className={cn(
                      'text-sm font-mono font-bold flex items-center gap-1',
                      match.mmr_delta > 0 ? 'text-emerald-400' : match.mmr_delta < 0 ? 'text-red-400' : 'text-[#5a5a72]'
                    )}>
                      {match.mmr_delta > 0 ? (
                        <TrendingUp className="w-3 h-3" />
                      ) : match.mmr_delta < 0 ? (
                        <TrendingDown className="w-3 h-3" />
                      ) : (
                        <Minus className="w-3 h-3" />
                      )}
                      {match.mmr_delta > 0 ? '+' : ''}{match.mmr_delta}
                    </span>

                    <span className="text-xs text-[#a0a0b8] font-mono">
                      <span className="text-[#f0f0f5] font-semibold">{match.kills}</span>
                      <span className="text-[#3a3a4e]"> / </span>
                      <span className="text-[#5a5a72]">{match.deaths}</span>
                      <span className="text-[#3a3a4e]"> / </span>
                      <span className="text-[#5a5a72]">{match.assists}</span>
                    </span>

                    <span className="text-[10px] text-[#3a3a4e] font-medium text-right flex items-center gap-1 justify-end">
                      <Clock className="w-2.5 h-2.5" />
                      {formatRelativeTime(match.finished_at)}
                    </span>
                  </motion.div>
                </Link>
              ))}
            </div>
          ) : (
            <div className="rounded-2xl border border-border bg-bg-card text-center py-20">
              <motion.div
                initial={{ scale: 0.9, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ delay: 0.1, type: 'spring', stiffness: 300, damping: 20 }}
              >
                <div className="w-16 h-16 rounded-2xl bg-[#1a1a2a] border border-border flex items-center justify-center mx-auto mb-5">
                  <Swords className="w-8 h-8 text-[#3a3a4e]" />
                </div>
                <p className="text-[#f0f0f5] font-bold text-lg mb-1 font-display">No matches yet</p>
                <p className="text-[#5a5a72] text-sm mb-8 font-medium">
                  Jump into your first game and start climbing
                </p>
                <Button onClick={() => navigate('/queue')} size="lg">
                  <Crosshair className="w-4 h-4" /> Find a Match
                </Button>
              </motion.div>
            </div>
          )}
        </motion.div>
      </motion.div>
    </div>
  );
}
