"use client";

import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import Link from "next/link";
import {
  Trophy,
  TrendingUp,
  TrendingDown,
  Minus,
  Clock,
  DollarSign,
  Users,
  RefreshCcw,
} from "lucide-react";
import type {
  Leaderboard,
  LeaderboardEntry,
  LeaderboardPeriod,
  RepMetrics,
} from "@/lib/types/experiments.types";

interface LeaderboardCardProps {
  className?: string;
}

export default function LeaderboardCard({
  className = "",
}: LeaderboardCardProps) {
  const [leaderboard, setLeaderboard] = useState<Leaderboard | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [period, setPeriod] = useState<LeaderboardPeriod>("month");
  const [sortBy, setSortBy] = useState<keyof RepMetrics>("demoToCloseRate");

  const fetchLeaderboard = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch(
        `/api/staff/analytics/leaderboard?period=${period}&sortBy=${sortBy}&includeSummary=true&limit=5`,
      );
      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to fetch leaderboard");
      }

      setLeaderboard(data.leaderboard);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, [period, sortBy]);

  useEffect(() => {
    fetchLeaderboard();
  }, [fetchLeaderboard]);

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(value);
  };

  const getTrendIcon = (entry: LeaderboardEntry) => {
    if (entry.trend === "up") {
      return <TrendingUp className="h-4 w-4 text-emerald-500" />;
    } else if (entry.trend === "down") {
      return <TrendingDown className="h-4 w-4 text-red-500" />;
    }
    return <Minus className="h-4 w-4 text-gray-400" />;
  };

  const getRankBadge = (rank: number) => {
    if (rank === 1) {
      return (
        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-amber-100 text-amber-600">
          <Trophy className="h-4 w-4" />
        </div>
      );
    }
    return (
      <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-100 text-sm font-bold text-gray-600">
        {rank}
      </div>
    );
  };

  const getInitials = (name: string) => {
    return name
      .split(" ")
      .map((n) => n[0])
      .join("")
      .toUpperCase()
      .slice(0, 2);
  };

  if (loading) {
    return (
      <div
        className={`rounded-3xl border border-gray-100 bg-white p-6 shadow-lg ${className}`}
      >
        <div className="animate-pulse space-y-4">
          <div className="h-6 w-48 rounded bg-gray-200" />
          <div className="space-y-3">
            {[1, 2, 3, 4, 5].map((i) => (
              <div key={i} className="h-16 rounded-xl bg-gray-100" />
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div
        className={`rounded-3xl border border-red-100 bg-red-50 p-6 ${className}`}
      >
        <div className="flex items-center gap-3 text-red-700">
          <Trophy className="h-5 w-5" />
          <p className="text-sm font-medium">{error}</p>
        </div>
        <button
          onClick={fetchLeaderboard}
          className="mt-4 text-sm font-medium text-red-700 hover:text-red-800"
        >
          Try again
        </button>
      </div>
    );
  }

  if (!leaderboard) return null;

  return (
    <div
      className={`flex flex-col rounded-3xl border border-gray-100 bg-white shadow-lg ${className}`}
    >
      {/* Header */}
      <div className="flex items-center justify-between border-b border-gray-100 bg-gradient-to-r from-amber-50 to-transparent px-6 py-4">
        <div className="flex items-center gap-3">
          <div className="rounded-full bg-amber-600/10 p-2 text-amber-600">
            <Trophy className="h-5 w-5" />
          </div>
          <div>
            <h3 className="text-sm font-semibold text-gray-900">
              Team Leaderboard
            </h3>
            <p className="text-xs text-gray-500">Rep & CSM performance</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <select
            value={period}
            onChange={(e) => setPeriod(e.target.value as LeaderboardPeriod)}
            className="rounded-lg border border-gray-200 bg-white px-2 py-1 text-xs font-medium text-gray-600 focus:border-amber-300 focus:outline-none focus:ring-1 focus:ring-amber-300"
          >
            <option value="week">This Week</option>
            <option value="month">This Month</option>
            <option value="quarter">This Quarter</option>
          </select>
          <button
            onClick={fetchLeaderboard}
            className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
            title="Refresh"
          >
            <RefreshCcw className="h-4 w-4" />
          </button>
        </div>
      </div>

      {/* Sort Options */}
      <div className="flex items-center gap-2 border-b border-gray-100 px-6 py-3">
        <span className="text-xs text-gray-500">Sort by:</span>
        <div className="flex gap-1">
          {[
            { key: "demoToCloseRate" as keyof RepMetrics, label: "Close Rate" },
            { key: "revenue" as keyof RepMetrics, label: "Revenue" },
            {
              key: "avgResponseTimeMinutes" as keyof RepMetrics,
              label: "Response",
            },
          ].map((option) => (
            <button
              key={option.key}
              onClick={() => setSortBy(option.key)}
              className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
                sortBy === option.key
                  ? "bg-amber-100 text-amber-700"
                  : "bg-gray-100 text-gray-600 hover:bg-gray-200"
              }`}
            >
              {option.label}
            </button>
          ))}
        </div>
      </div>

      {/* Totals */}
      <div className="grid grid-cols-3 gap-4 border-b border-gray-100 px-6 py-4">
        <div className="flex items-center gap-2">
          <Users className="h-4 w-4 text-gray-400" />
          <div>
            <p className="text-lg font-bold text-gray-900">
              {leaderboard.totals.totalDemos}
            </p>
            <p className="text-xs text-gray-500">Demos</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <DollarSign className="h-4 w-4 text-gray-400" />
          <div>
            <p className="text-lg font-bold text-gray-900">
              {formatCurrency(leaderboard.totals.totalRevenue)}
            </p>
            <p className="text-xs text-gray-500">Revenue</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Clock className="h-4 w-4 text-gray-400" />
          <div>
            <p className="text-lg font-bold text-gray-900">
              {leaderboard.totals.avgResponseTime}m
            </p>
            <p className="text-xs text-gray-500">Avg Response</p>
          </div>
        </div>
      </div>

      {/* Leaderboard Entries */}
      <div className="flex-1 divide-y divide-gray-100">
        {leaderboard.entries.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-center">
            <Trophy className="h-12 w-12 text-gray-300" />
            <p className="mt-4 text-sm text-gray-500">
              No data for this period
            </p>
          </div>
        ) : (
          leaderboard.entries.map((entry) => (
            <div
              key={entry.id}
              className="flex items-center gap-4 px-6 py-4 transition-colors hover:bg-gray-50"
            >
              {/* Rank */}
              {getRankBadge(entry.rank)}

              {/* Avatar & Name */}
              <div className="flex min-w-0 flex-1 items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-gray-100 to-gray-200 text-sm font-bold text-gray-600">
                  {entry.avatar ? (
                    <Image
                      src={entry.avatar}
                      alt={entry.name}
                      width={40}
                      height={40}
                      className="h-full w-full rounded-full object-cover"
                    />
                  ) : (
                    getInitials(entry.name)
                  )}
                </div>
                <div className="min-w-0">
                  <p className="truncate text-sm font-medium text-gray-900">
                    {entry.name}
                  </p>
                  <p className="text-xs text-gray-500">{entry.role}</p>
                </div>
              </div>

              {/* Key Metric */}
              <div className="text-right">
                {sortBy === "demoToCloseRate" && (
                  <>
                    <p className="text-lg font-bold text-gray-900">
                      {entry.metrics.demoToCloseRate.toFixed(1)}%
                    </p>
                    <p className="text-xs text-gray-500">Close Rate</p>
                  </>
                )}
                {sortBy === "revenue" && (
                  <>
                    <p className="text-lg font-bold text-gray-900">
                      {formatCurrency(entry.metrics.revenue)}
                    </p>
                    <p className="text-xs text-gray-500">Revenue</p>
                  </>
                )}
                {sortBy === "avgResponseTimeMinutes" && (
                  <>
                    <p className="text-lg font-bold text-gray-900">
                      {entry.metrics.avgResponseTimeMinutes}m
                    </p>
                    <p className="text-xs text-gray-500">Avg Response</p>
                  </>
                )}
              </div>

              {/* Trend */}
              <div className="flex items-center gap-1">
                {getTrendIcon(entry)}
                {entry.rankChange !== 0 && (
                  <span
                    className={`text-xs font-medium ${
                      entry.rankChange > 0 ? "text-emerald-600" : "text-red-600"
                    }`}
                  >
                    {entry.rankChange > 0 ? "+" : ""}
                    {entry.rankChange}
                  </span>
                )}
              </div>
            </div>
          ))
        )}
      </div>

      {/* Footer */}
      <div className="border-t border-gray-100 px-6 py-3 text-center">
        <Link
          href="/staff/dashboard/analytics"
          className="text-sm font-medium text-amber-600 hover:text-amber-700"
        >
          View full leaderboard →
        </Link>
      </div>
    </div>
  );
}
