"use client";

import { useEffect, useState } from "react";
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 api_url = process.env.NEXT_PUBLIC_API_URL;

  const currentYear = new Date().getFullYear();

  const [year, setYear] = useState<number>(currentYear);

  const [ranking, setRanking] = useState<any[]>([]);

  const years = [];
  for (let y = 2025; y <= currentYear; y++) {
    years.push(y);
  }

  useEffect(() => {
    const fetchRanking = async () => {
      try {
        const token = Cookies.get("token");

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

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

    fetchRanking();
  }, [year, api_url]);

  return (
    <section>
      <div className="year-selector">
        <div>
          <label>Año:</label>
          <select
            value={year}
            onChange={(e) => setYear(Number(e.target.value))}
          >
            {years.map((y) => (
              <option key={y} value={y}>
                {y}
              </option>
            ))}
          </select>
        </div>
      </div>
      <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}
                  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>
    </section>
  );
}
