'use client';

import { useLeaderboardEvent } from '@/lib/hooks/use-leaderboard';
import { cn } from '@/lib/utils';
// import { Timer } from '../Timer';
import Podium from './podium/Podium';
import { useMemo } from 'react';

const SCORE_COLORS = ['text-yellow-400', 'text-gray-400', 'text-orange-400'];

export default function EventLeaderboard({ token, id }: { token: string; id: number }) {
  const { data, isLoading } = useLeaderboardEvent({ token, id });

  const scores = [data?.groups]
    .flat()
    .sort((a, b) => a!.rank - b!.rank)
    .map((group, place) => ({
      ...group,
      place
    }));

  return (
    <section className="flex h-full w-full flex-col space-y-4 p-4">
      {!isLoading && data && <Podium score={scores} />}
      {/* <Timer targetDate={data && data.end_date} />   */}
      <main className="flex flex-col justify-between space-x-0 space-y-4 pb-4">
        <ul className="flex flex-col space-y-2">
          {!isLoading &&
            data?.groups.map((group, key) => (
              <li key={key} className="flex justify-between space-x-2">
                <div className="flex items-center space-x-4">
                  <span className={cn('font-semibold', SCORE_COLORS[group.rank - 1])}>
                    {group.rank}
                  </span>
                  <div className="flex items-center space-x-2">
                    <div className="flex flex-col gap-x-2 sm:flex-row sm:items-center">
                      <span className="text-lg">{group.name}</span>
                      <span className="text-sm text-muted">
                        {group.players
                          ?.map((p) => p.pseudo)
                          .sort((a, b) => a.localeCompare(b))
                          .join(', ')}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="flex items-center space-x-4">
                  <div className="flex flex-col">
                    <span className="text-sm font-semibold">Essaies</span>
                    <span className="text-lg text-muted">
                      {group.players.reduce((a, b) => a + b.tries, 0)}
                    </span>
                  </div>
                  <div className="flex flex-col">
                    <span className="text-sm font-semibold">Score</span>
                    <span className="text-lg text-muted">
                      {group.players.reduce((a, b) => a + b.score, 0)}
                    </span>
                  </div>
                </div>
              </li>
            ))}
        </ul>
      </main>
    </section>
  );
}
