import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { ArrowLeft, ShieldOff } from 'lucide-react';
import { PageTransition } from '@/components/layout/PageTransition';
import { Card } from '@/components/ui/Card';
import { Avatar } from '@/components/ui/Avatar';
import { Badge } from '@/components/ui/Badge';
import { SkeletonCard } from '@/components/ui/Skeleton';
import { MMRCard } from '@/components/stats/MMRCard';
import { WinRateRing } from '@/components/stats/WinRateRing';
import { MatchCountChart } from '@/components/stats/MatchCountChart';
import { MMRHistoryChart } from '@/components/stats/MMRHistoryChart';
import { MapPerformance } from '@/components/stats/MapPerformance';
import { RankBadge } from '@/components/profile/RankBadge';
import { profileAPI } from '@/api/client';
import { formatNumber } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function PublicProfile() {
  const { username } = useParams<{ username: string }>();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    if (!username) return;
    profileAPI.getByUsername(username)
      .then(({ data: resp }) => setData(resp))
      .catch(() => setError(true))
      .finally(() => setLoading(false));
  }, [username]);

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

  if (error || !data?.profile) {
    return (
      <PageTransition className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-16 text-center">
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
        >
          <div className="w-16 h-16 rounded-full bg-[#0f0f18] flex items-center justify-center mx-auto mb-4">
            <ShieldOff className="w-8 h-8 text-[#5a5a72]" />
          </div>
          <h2 className="text-xl font-bold text-[#f0f0f5] mb-2">Player not found</h2>
          <p className="text-[#a0a0b8] mb-6">
            The player "{username}" doesn't exist or their profile is private.
          </p>
          <Link to="/leaderboard" className="text-[#ff6b2c] hover:text-[#ff8a50] transition-colors text-sm font-medium">
            View Leaderboard
          </Link>
        </motion.div>
      </PageTransition>
    );
  }

  const profile = data.profile;
  const isBanned = data.is_banned;
  const mmrHistory = (data.mmr_history || []).map((h: any) => ({
    date: h.created_at || h.date,
    mmr: h.mmr || h.new_mmr || h.MMR,
  }));

  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="/leaderboard" 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 Leaderboard
        </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="absolute inset-0 bg-gradient-to-r from-[#ff6b2c]/[0.03] via-transparent to-transparent pointer-events-none" />

            <div className="relative flex flex-col sm:flex-row items-center sm:items-start gap-6">
              <motion.div
                initial={{ scale: 0.8, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ type: 'spring', stiffness: 200, damping: 18 }}
              >
                <Avatar src={profile.steam_avatar_url} username={profile.username} size="xl" />
              </motion.div>

              <div className="flex-1 text-center sm:text-left">
                <div className="flex flex-wrap items-center gap-2 mb-1 justify-center sm:justify-start">
                  <h1 className="text-2xl font-extrabold text-[#f0f0f5] tracking-tight">
                    {profile.username}
                  </h1>
                  {profile.tier === 'premium' && <Badge variant="premium">Premium</Badge>}
                  {profile.tier === 'vip' && <Badge variant="vip">VIP</Badge>}
                  {isBanned && <Badge variant="danger">Banned</Badge>}
                </div>
                <p className="text-sm text-[#a0a0b8]">
                  {formatNumber(profile.mmr)} MMR &middot; {profile.matches_played} matches played
                </p>
              </div>

              <RankBadge
                mmr={profile.mmr}
                placementDone={profile.placement_done}
                matchesPlayed={profile.matches_played}
                size="lg"
              />
            </div>
          </Card>
        </motion.div>

        <motion.div variants={staggerItem} className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <MMRCard mmr={profile.mmr} />
          <WinRateRing wins={profile.wins} losses={profile.losses} />
          <MatchCountChart total={profile.matches_played} />
        </motion.div>

        {mmrHistory.length > 0 && (
          <motion.div variants={staggerItem}>
            <MMRHistoryChart data={mmrHistory} />
          </motion.div>
        )}

        {profile.map_stats && profile.map_stats.length > 0 && (
          <motion.div variants={staggerItem}>
            <MapPerformance maps={profile.map_stats} />
          </motion.div>
        )}
      </motion.div>
    </PageTransition>
  );
}
