"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Cookies from "js-cookie";
import axios from "axios";
import toast from "react-hot-toast";

import "../app/styles/layout/history.scss";

export default function Ranking() {
  const [ranking, setRanking] = useState<any[]>([]);
  const api_url = process.env.NEXT_PUBLIC_API_URL;

  useEffect(() => {
    const fetchRanking = async () => {
      try {
        const token = Cookies.get("token");
        const headers = { Authorization: `Bearer ${token}` };

        const response = await axios.get(`${api_url}/equipos/ranking`, {
          headers,
        });

        setRanking(response.data);
      } catch (error) {
        toast.error("No se pudo cargar el ranking");
      }
    };

    fetchRanking();
  }, []);

  return (
    <div className="history-table-container">
      <table className="history-table">
        <thead>
          <tr className="rowTotal">
            <td colSpan={2} className="total">
              Total de equipos censados:
            </td>
            <td colSpan={1} className="total">
              {ranking.reduce((acc, r) => acc + r.total, 0)}
            </td>
          </tr>

          <tr>
            <th>Usuario</th>
            <th>Total Censado</th>
            <th>Ranking</th>
          </tr>
        </thead>

        <tbody>
          {ranking.length > 0 ? (
            ranking.map((item: any, index: number) => (
              <tr
                key={item.id_usuario || index}
                className={
                  index === 0
                    ? "primer-lugar"
                    : index === 1
                    ? "segundo-lugar"
                    : index === 2
                    ? "tercer-lugar"
                    : ""
                }
              >
                <td>{item.nombre}</td>
                <td>{item.total}</td>
                <td>#{index + 1}</td>
              </tr>
            ))
          ) : (
            <tr>
              <td colSpan={3} className="empty-row">
                No hay datos de ranking disponibles
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );
}
