'use client';

import { cn } from '@/lib/utils';
// import { Timer } from '../Timer';
import type { ScoreEvent } from '@/lib/leaderboard';
import type { SWRSubscription } from 'swr/subscription';
import useSWRSubscription from 'swr/subscription';
import Podium from './podium/Podium';
import { Timer } from '../Timer';

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

export default function EventLeaderboard({ id }: { token: string; id: number }) {
  const subscription: SWRSubscription<string, ScoreEvent, Error> = (key, { next }) => {
    const socket = new WebSocket(key);

    socket.addEventListener('message', (event) => {
      next(null, JSON.parse(event.data));
    });

    socket.addEventListener('error', (event) => {
      console.error(event);
    });

    return () => socket.close();
  };

  const { data, error } = useSWRSubscription(
    `wss://${process.env.NEXT_PUBLIC_API_URL?.split('//')[1]}/rleaderboard/${id}`,
    subscription
  );

  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">
      {data && <Podium score={scores} />}
      {data && data.end_date && <Timer targetDate={new Date(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">
          {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 && group.players.length > 1
                        ? group.players
                            .map((player) => player.pseudo || 'Anonyme')
                            .sort((a, b) => a.localeCompare(b))
                            .join(', ')
                        : group.players[0].pseudo}
                    </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>
  );
}
