"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { PageHeader } from "@/components/shared/page-header";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar } from "@/components/ui/avatar";
import { NativeSelect } from "@/components/ui/native-select";
import { LoadingPage } from "@/components/ui/loading";
import {
  gamificationApi,
  locationsApi,
  LeaderboardEntry,
  LeaderboardScoreEntry,
  Location,
  PointType,
} from "@/lib/api-client";
import { Trophy, Medal, Crown, Zap, TrendingUp, Users } from "lucide-react";

const periodLabels: Record<string, string> = {
  daily: "Today",
  weekly: "This Week",
  monthly: "This Month",
  all_time: "All Time",
};

const rankIcons = [
  <Crown key="1" className="h-5 w-5 text-yellow-500" />,
  <Medal key="2" className="h-5 w-5 text-gray-400" />,
  <Medal key="3" className="h-5 w-5 text-amber-600" />,
];

export default function LeaderboardPage() {
  const [period, setPeriod] = useState<string>("weekly");
  const [locationId, setLocationId] = useState<string>("all");
  const [pointTypeId, setPointTypeId] = useState<string>("all");

  const { data: leaderboard, isLoading } = useQuery({
    queryKey: ["leaderboard", period, locationId, pointTypeId],
    queryFn: async () => {
      if (pointTypeId !== "all") {
        const response = await gamificationApi.getLeaderboardScores({
          period,
          pointTypeId,
          limit: 50,
        });
        return response.data;
      }

      const params: Record<string, unknown> = {
        period,
        limit: 50,
      };
      if (locationId !== "all") {
        params.locationId = locationId;
      }
      const response = await gamificationApi.getLeaderboard(params);
      return response.data;
    },
  });

  const { data: locations } = useQuery({
    queryKey: ["locations-list"],
    queryFn: async () => {
      const response = await locationsApi.getAll({ limit: 100 });
      return response.data.data;
    },
  });

  const { data: pointTypes } = useQuery({
    queryKey: ["point-types"],
    queryFn: async () => {
      const response = await gamificationApi.getPointTypes();
      return response.data;
    },
  });

  if (isLoading) {
    return <LoadingPage />;
  }

  // Get top 3 for podium
  const topThree = leaderboard?.slice(0, 3) || [];
  const restOfLeaderboard = leaderboard?.slice(3) || [];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Leaderboard"
        description="View top performers across your platform"
      />

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-4">
        <div className="flex items-center gap-2">
          <TrendingUp className="h-4 w-4 text-muted-foreground" />
          <NativeSelect
            value={period}
            onChange={(e) => setPeriod(e.target.value)}
            options={[
              { value: "daily", label: "Today" },
              { value: "weekly", label: "This Week" },
              { value: "monthly", label: "This Month" },
              { value: "all_time", label: "All Time" },
            ]}
            className="w-40"
          />
        </div>
        <div className="flex items-center gap-2">
          <Users className="h-4 w-4 text-muted-foreground" />
          <NativeSelect
            value={locationId}
            onChange={(e) => setLocationId(e.target.value)}
            options={[
              { value: "all", label: "All Locations" },
              ...(locations?.map((loc: Location) => ({ value: loc.id, label: loc.name })) || []),
            ]}
            className="w-48"
          />
        </div>
        <div className="flex items-center gap-2">
          <Zap className="h-4 w-4 text-muted-foreground" />
          <NativeSelect
            value={pointTypeId}
            onChange={(e) => setPointTypeId(e.target.value)}
            options={[
              { value: "all", label: "All Point Types" },
              ...(pointTypes?.map((type: PointType) => ({ value: type.id, label: type.name })) || []),
            ]}
            className="w-48"
          />
        </div>
      </div>

      {leaderboard?.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Trophy className="h-12 w-12 text-muted-foreground mb-4" />
            <h3 className="text-lg font-semibold">No data yet</h3>
            <p className="text-muted-foreground mt-1">
              Leaderboard will populate as users earn points
            </p>
          </CardContent>
        </Card>
      ) : (
        <>
          {/* Podium - Top 3 */}
          {topThree.length > 0 && (
            <div className="grid gap-4 md:grid-cols-3">
              {/* 2nd Place */}
              {topThree[1] && (
                <Card className="md:mt-8">
                  <CardContent className="pt-6">
                    <div className="flex flex-col items-center text-center">
                      <div className="relative">
                        <Avatar
                          src={topThree[1].user?.avatarUrl}
                          fallback={`${topThree[1].user?.firstName} ${topThree[1].user?.lastName}`}
                          size="lg"
                          className="h-20 w-20"
                        />
                        <div className="absolute -top-2 -right-2 h-8 w-8 rounded-full bg-gray-400 flex items-center justify-center text-white font-bold">
                          2
                        </div>
                      </div>
                      <h3 className="font-semibold mt-4">
                        {topThree[1].user?.firstName} {topThree[1].user?.lastName}
                      </h3>
                      <div className="flex items-center gap-1 mt-2 text-lg font-bold text-primary">
                        <Zap className="h-5 w-5" />
                        {(topThree[1] as LeaderboardEntry).points !== undefined
                          ? (topThree[1] as LeaderboardEntry).points.toLocaleString()
                          : (topThree[1] as LeaderboardScoreEntry).score.toLocaleString()}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* 1st Place */}
              {topThree[0] && (
                <Card className="border-primary/50 bg-gradient-to-b from-primary/5 to-transparent">
                  <CardContent className="pt-6">
                    <div className="flex flex-col items-center text-center">
                      <Crown className="h-8 w-8 text-yellow-500 mb-2" />
                      <div className="relative">
                        <Avatar
                          src={topThree[0].user?.avatarUrl}
                          fallback={`${topThree[0].user?.firstName} ${topThree[0].user?.lastName}`}
                          size="lg"
                          className="h-24 w-24 ring-4 ring-yellow-500/50"
                        />
                        <div className="absolute -top-2 -right-2 h-10 w-10 rounded-full bg-yellow-500 flex items-center justify-center text-white font-bold text-lg">
                          1
                        </div>
                      </div>
                      <h3 className="font-bold text-lg mt-4">
                        {topThree[0].user?.firstName} {topThree[0].user?.lastName}
                      </h3>
                      <div className="flex items-center gap-1 mt-2 text-2xl font-bold text-primary">
                        <Zap className="h-6 w-6" />
                        {(topThree[0] as LeaderboardEntry).points !== undefined
                          ? (topThree[0] as LeaderboardEntry).points.toLocaleString()
                          : (topThree[0] as LeaderboardScoreEntry).score.toLocaleString()}
                      </div>
                      <Badge className="mt-2">Champion</Badge>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* 3rd Place */}
              {topThree[2] && (
                <Card className="md:mt-12">
                  <CardContent className="pt-6">
                    <div className="flex flex-col items-center text-center">
                      <div className="relative">
                        <Avatar
                          src={topThree[2].user?.avatarUrl}
                          fallback={`${topThree[2].user?.firstName} ${topThree[2].user?.lastName}`}
                          size="lg"
                          className="h-16 w-16"
                        />
                        <div className="absolute -top-2 -right-2 h-7 w-7 rounded-full bg-amber-600 flex items-center justify-center text-white font-bold text-sm">
                          3
                        </div>
                      </div>
                      <h3 className="font-semibold mt-4">
                        {topThree[2].user?.firstName} {topThree[2].user?.lastName}
                      </h3>
                      <div className="flex items-center gap-1 mt-2 text-lg font-bold text-primary">
                        <Zap className="h-5 w-5" />
                        {(topThree[2] as LeaderboardEntry).points !== undefined
                          ? (topThree[2] as LeaderboardEntry).points.toLocaleString()
                          : (topThree[2] as LeaderboardScoreEntry).score.toLocaleString()}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          )}

          {/* Rest of Leaderboard */}
          {restOfLeaderboard.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Rankings</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {restOfLeaderboard.map((entry: LeaderboardEntry | LeaderboardScoreEntry, index: number) => (
                    <div
                      key={entry.user?.id || index}
                      className="flex items-center gap-4 p-3 rounded-lg hover:bg-muted/50 transition-colors"
                    >
                      {/* Rank */}
                      <div className="w-8 text-center font-bold text-muted-foreground">
                        {index + 4}
                      </div>

                      {/* Avatar */}
                      <Avatar
                        src={entry.user?.avatarUrl}
                        fallback={`${entry.user?.firstName} ${entry.user?.lastName}`}
                        size="sm"
                      />

                      {/* Name */}
                      <div className="flex-1">
                        <p className="font-medium">
                          {entry.user?.firstName} {entry.user?.lastName}
                        </p>
                      </div>

                      {/* Points */}
                      <div className="flex items-center gap-1 font-semibold">
                        <Zap className="h-4 w-4 text-primary" />
                        {"points" in entry
                          ? entry.points.toLocaleString()
                          : entry.score.toLocaleString()}
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </>
      )}
    </div>
  );
}
