import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Settings, ArrowRight } 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 { Button } from '@/components/ui/Button';
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 { SteamLinkCard } from '@/components/profile/SteamLinkCard';
import { RankBadge } from '@/components/profile/RankBadge';
import { useAuthStore } from '@/stores/authStore';
import { profileAPI } from '@/api/client';
import { formatNumber } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function Profile() {
  const authUser = useAuthStore((s) => s.user);
  const [profile, setProfile] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    profileAPI.me()
      .then(({ data }) => {
        setProfile(data.user || data);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  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>
    );
  }

  const user = profile || authUser;
  if (!user) return null;

  return (
    <PageTransition className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <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={user.steam_avatar_url}
                  username={user.username}
                  size="xl"
                />
              </motion.div>

              <div className="flex-1 text-center sm:text-left">
                <div className="flex flex-col sm:flex-row items-center sm:items-start gap-2 mb-1">
                  <h1 className="text-2xl font-extrabold text-[#f0f0f5] tracking-tight">
                    {user.username}
                  </h1>
                  {user.tier === 'premium' && <Badge variant="premium">Premium</Badge>}
                  {user.tier === 'vip' && <Badge variant="vip">VIP</Badge>}
                </div>
                <p className="text-sm text-[#a0a0b8]">
                  {formatNumber(user.mmr)} MMR &middot;{' '}
                  Member since{' '}
                  {new Date(user.created_at).toLocaleDateString('en-US', {
                    month: 'long',
                    year: 'numeric',
                  })}
                </p>

                <div className="flex items-center gap-3 mt-4 justify-center sm:justify-start">
                  <Link to="/settings">
                    <Button variant="secondary" size="sm">
                      <Settings className="w-3.5 h-3.5" />
                      Settings
                    </Button>
                  </Link>
                  <Link to="/history">
                    <Button variant="ghost" size="sm">
                      Match History
                      <ArrowRight className="w-3.5 h-3.5" />
                    </Button>
                  </Link>
                </div>
              </div>

              <RankBadge
                mmr={user.mmr}
                placementDone={user.placement_done}
                matchesPlayed={user.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={user.mmr} />
          <WinRateRing wins={user.wins} losses={user.losses} />
          <MatchCountChart total={user.matches_played} />
        </motion.div>

        {profile?.mmr_history && profile.mmr_history.length > 0 && (
          <motion.div variants={staggerItem}>
            <MMRHistoryChart
              data={profile.mmr_history.map((h: any) => ({
                date: h.created_at || h.date,
                mmr: h.mmr || h.new_mmr || h.MMR,
              }))}
            />
          </motion.div>
        )}

        <motion.div variants={staggerItem}>
          <SteamLinkCard
            steamId={user.steam_id}
            personaName={user.steam_persona_name}
            avatarUrl={user.steam_avatar_url}
            linkedAt={user.steam_linked_at}
            onLinked={() => profileAPI.me().then(({ data }) => { const u = data.user || data; setProfile(u); useAuthStore.getState().updateUser(u); }).catch(() => {})}
          />
        </motion.div>

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