"use client";

import { useState } from "react";
import { useUser } from "@/lib/context";
import { Users, Flame, Award, ArrowUpRight, Check, Trophy, Footprints, Landmark } from "lucide-react";

interface TeamChallenge {
  id: string;
  title: string;
  description: string;
  reward: number;
  current: number;
  goal: number;
  joined: boolean;
  icon: React.ReactNode;
}

export default function LeaderboardSection() {
  const { profile, addLyts } = useUser();
  const [challenges, setChallenges] = useState<TeamChallenge[]>([
    {
      id: "ch-steps",
      title: "Weekend Step Sprint",
      description: "Collectively log 50,000 steps with your team this weekend.",
      reward: 100,
      current: 38400,
      goal: 50000,
      joined: false,
      icon: <Footprints className="w-5 h-5 text-accent-lime" />,
    },
    {
      id: "ch-stores",
      title: "Starbucks Double Drop",
      description: "Check in at any two Starbucks locations within 7 days.",
      reward: 40,
      current: 1,
      goal: 2,
      joined: true,
      icon: <Landmark className="w-5 h-5 text-emerald-400" />,
    },
    {
      id: "ch-ref",
      title: "Referral Rush",
      description: "Invite 3 friends to join LytsUp. Earn bonus points.",
      reward: 150,
      current: 2,
      goal: 3,
      joined: false,
      icon: <Users className="w-5 h-5 text-accent-pink" />,
    },
  ]);

  const leaderboardUsers = [
    { rank: 1, name: "Zara Cole", level: 6, steps: 14200, points: 285, avatar: "Z" },
    { rank: 2, name: "Marcus Lee", level: 5, steps: 12100, points: 240, avatar: "M" },
    { rank: 3, name: "Chloe Vane", level: 4, steps: 9400, points: 188, avatar: "C" },
    { rank: 4, name: "Alex Stark (You)", level: profile.level, steps: profile.stepsToday, points: Math.round(profile.stepsToday / 15), avatar: "A", highlight: true },
    { rank: 5, name: "Devon Shaw", level: 3, steps: 5900, points: 118, avatar: "D" },
  ];

  const handleJoinChallenge = (id: string, reward: number) => {
    setChallenges((prev) =>
      prev.map((ch) => {
        if (ch.id === id) {
          // If already joined, complete it to give points for the simulation
          if (ch.joined) {
            addLyts(reward);
            return { ...ch, current: ch.goal, completed: true };
          }
          return { ...ch, joined: true };
        }
        return ch;
      })
    );
  };

  return (
    <section id="leaderboard" className="py-24 bg-[#090909] relative overflow-hidden">
      {/* Background ambient lighting */}
      <div className="absolute top-1/3 left-0 w-80 h-80 rounded-full bg-accent-lime/5 blur-[100px] pointer-events-none" />
      <div className="absolute bottom-1/3 right-0 w-80 h-80 rounded-full bg-accent-purple/5 blur-[100px] pointer-events-none" />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        
        {/* Section Header */}
        <div className="text-center max-w-3xl mx-auto mb-20 space-y-4">
          <span className="text-accent-pink font-extrabold text-xs tracking-widest uppercase">
            Community Hub
          </span>
          <h2 className="text-3xl sm:text-5xl font-extrabold font-sora text-white leading-tight">
            Play Together. <span className="text-glow-yellow text-primary">Earn Together.</span>
          </h2>
          <p className="text-white/60 text-base sm:text-lg">
            Join squad goals to multiply your LYT earnings, or compete for the top spots on the daily leaderboard.
          </p>
        </div>

        {/* Contents Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-start">
          
          {/* Left Column: Team Challenges */}
          <div className="space-y-6">
            <h3 className="text-2xl font-bold font-sora text-white flex items-center gap-2">
              <Trophy className="w-6 h-6 text-primary" />
              <span>Active Squad Challenges</span>
            </h3>

            <div className="space-y-4">
              {challenges.map((ch) => {
                const percentage = Math.min(100, Math.round((ch.current / ch.goal) * 100));
                const isCompleted = ch.current >= ch.goal;

                return (
                  <div
                    key={ch.id}
                    className={`glassmorphism rounded-3xl p-6 border transition-colors ${
                      ch.joined ? "border-primary/20 bg-primary/2" : "border-white/5"
                    }`}
                  >
                    <div className="flex justify-between items-start gap-4 mb-4">
                      <div className="flex items-center space-x-3">
                        <div className="w-10 h-10 rounded-xl bg-white/5 border border-white/10 flex items-center justify-center">
                          {ch.icon}
                        </div>
                        <div>
                          <h4 className="text-base font-bold text-white font-sora">{ch.title}</h4>
                          <p className="text-white/60 text-xs mt-0.5 leading-relaxed">{ch.description}</p>
                        </div>
                      </div>
                      
                      <div className="text-right">
                        <span className="text-xs text-white/40 font-bold uppercase tracking-wider block">Reward</span>
                        <span className="text-sm font-extrabold text-primary">+{ch.reward} LYTs</span>
                      </div>
                    </div>

                    {/* Progress Slider */}
                    <div className="space-y-2">
                      <div className="flex justify-between text-xs font-semibold">
                        <span className="text-white/50">{ch.current.toLocaleString()} / {ch.goal.toLocaleString()}</span>
                        <span className="text-primary">{percentage}%</span>
                      </div>
                      <div className="w-full h-2 bg-white/5 rounded-full overflow-hidden">
                        <div
                          style={{ width: `${percentage}%` }}
                          className="h-full bg-gradient-to-r from-primary to-accent-lime rounded-full"
                        />
                      </div>
                    </div>

                    {/* Button */}
                    <div className="mt-6 flex justify-end">
                      <button
                        onClick={() => handleJoinChallenge(ch.id, ch.reward)}
                        disabled={isCompleted}
                        className={`px-5 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
                          isCompleted
                            ? "bg-accent-lime/10 border border-accent-lime/20 text-accent-lime cursor-not-allowed"
                            : ch.joined
                            ? "bg-primary text-dark hover:bg-primary/90"
                            : "bg-white/5 border border-white/10 text-white hover:bg-white/10"
                        }`}
                      >
                        {isCompleted ? (
                          <>
                            <Check className="w-3.5 h-3.5" />
                            <span>Claimed</span>
                          </>
                        ) : ch.joined ? (
                          <>
                            <span>Complete & Claim</span>
                            <ArrowUpRight className="w-3.5 h-3.5" />
                          </>
                        ) : (
                          <span>Join Challenge</span>
                        )}
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Right Column: Leaderboard list */}
          <div className="space-y-6">
            <h3 className="text-2xl font-bold font-sora text-white flex items-center gap-2">
              <Users className="w-6 h-6 text-accent-pink" />
              <span>Daily Leaderboard</span>
            </h3>

            <div className="glassmorphism rounded-3xl p-6 space-y-4">
              <div className="flex items-center justify-between text-xs text-white/40 font-bold uppercase tracking-wider px-3 border-b border-white/5 pb-3">
                <span>User</span>
                <div className="flex space-x-12">
                  <span>Steps</span>
                  <span>Est. LYTs</span>
                </div>
              </div>

              <div className="space-y-3">
                {leaderboardUsers.map((user) => (
                  <div
                    key={user.rank}
                    className={`flex items-center justify-between p-3 rounded-2xl transition-all ${
                      user.highlight
                        ? "bg-accent-pink/10 border border-accent-pink/20 shadow-[0_0_15px_rgba(255,46,136,0.1)]"
                        : "bg-white/3 border border-transparent hover:border-white/5"
                    }`}
                  >
                    <div className="flex items-center space-x-3">
                      {/* Rank badge */}
                      <span
                        className={`w-6 text-center font-sora font-extrabold text-sm ${
                          user.rank === 1
                            ? "text-primary text-glow-yellow"
                            : user.rank === 2
                            ? "text-slate-300"
                            : user.rank === 3
                            ? "text-amber-600"
                            : "text-white/60"
                        }`}
                      >
                        #{user.rank}
                      </span>

                      {/* Avatar */}
                      <div className="relative">
                        <div className="w-9 h-9 rounded-full bg-white/10 flex items-center justify-center font-bold text-sm text-white font-sora">
                          {user.avatar}
                        </div>
                        <span className="absolute -bottom-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-[#181818] text-[9px] font-bold text-white/80 border border-white/10">
                          L{user.level}
                        </span>
                      </div>

                      {/* Profile Details */}
                      <div>
                        <span className="text-sm font-bold text-white block">{user.name}</span>
                        {user.highlight && (
                          <span className="text-[10px] text-accent-pink font-semibold flex items-center gap-1 mt-0.5">
                            <Flame className="w-3 h-3 fill-current animate-pulse" />
                            <span>{profile.streak} days active streak</span>
                          </span>
                        )}
                      </div>
                    </div>

                    <div className="flex items-center space-x-12 text-right">
                      {/* Steps */}
                      <span className="text-xs font-semibold text-white/80 font-mono">
                        {user.steps.toLocaleString()}
                      </span>

                      {/* Points */}
                      <span className="text-sm font-bold text-primary font-mono">
                        +{user.points}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

        </div>
      </div>
    </section>
  );
}
