"use client";
import React, { useEffect, useMemo, useState } from "react";

type Row = Record<string, string>;

type LiftType = "Squat" | "Bench" | "Deadlift";

const liftTypeLabels: Record<LiftType, string> = {
  Squat: "Agachamento",
  Bench: "Supino",
  Deadlift: "Deadlift",
};

const ResultCell = ({ value, isTotal = false }: { value: string | undefined; isTotal?: boolean }) => {
  if (!value) return <td className="border p-2">—</td>;
  
  const numValue = parseFloat(value);
  const isNegative = numValue < 0;
  const isPositive = numValue > 0;
  
  const displayValue = isNegative ? Math.abs(numValue).toString() : value;
  
  // For total cells, just make text bold
  if (isTotal) {
    return <td className="border p-2 font-bold">{displayValue}</td>;
  }
  
  // For lift attempt cells, show colored backgrounds
  if (isNegative) {
    return (
      <td className="border p-2 bg-red-600 text-white font-semibold">
        {displayValue}
      </td>
    );
  }
  
  if (isPositive) {
    return (
      <td className="border p-2 bg-green-600 text-white font-semibold">
        {displayValue}
      </td>
    );
  }
  
  return <td className="border p-2">{value}</td>;
};

export function ResultsTable() {
  const [meets, setMeets] = useState<{ id: string; name: string }[]>([]);
  const [selectedMeet, setSelectedMeet] = useState<string>("");
  const [rows, setRows] = useState<Row[]>([]);
  const [query, setQuery] = useState<string>("");
  const [selectedLiftType, setSelectedLiftType] = useState<LiftType>("Squat");

  useEffect(() => {
    (async () => {
      const res = await fetch("/api/openpowerlifting/meets");
      const data = await res.json();
      setMeets(data.meets ?? []);
    })();
  }, []);

  useEffect(() => {
    if (!selectedMeet) return;
    (async () => {
      const res = await fetch(`/api/openpowerlifting/results?id=${selectedMeet}`);
      const json = await res.json();
      setRows(json.data ?? []);
    })();
  }, [selectedMeet]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return rows.filter((r) => (r["Name"] || "").toLowerCase().includes(q));
  }, [rows, query]);

  // Get the column keys for the three attempts of the selected lift type
  const getAttemptColumns = (liftType: LiftType) => {
    return [1, 2, 3].map((n) => `${liftType}${n}Kg`);
  };

  const attemptColumns = getAttemptColumns(selectedLiftType);

  return (
    <section aria-labelledby="results-title">
      <h1 id="results-title" className="text-2xl font-bold">Resultados</h1>

      <div className="grid gap-4 md:grid-cols-3 mt-4" role="region" aria-label="Controlo de pesquisa e seleção">
        <label className="block">
          <span className="block font-semibold">Competição</span>
          <select
            className="mt-1 w-full border p-2"
            aria-label="Selecionar competição"
            value={selectedMeet}
            onChange={(e) => setSelectedMeet(e.target.value)}
          >
            <option value="">Escolha uma competição</option>
            {meets.map((m) => (
              <option key={m.id} value={m.id}>{m.name}</option>
            ))}
          </select>
        </label>
        <label className="block">
          <span className="block font-semibold">Pesquisar atleta</span>
          <input
            type="search"
            className="mt-1 w-full border p-2"
            placeholder="Nome do atleta"
            aria-label="Pesquisar por nome"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </label>
        <label className="block">
          <span className="block font-semibold">Tipo de levantamento</span>
          <select
            className="mt-1 w-full border p-2"
            aria-label="Selecionar tipo de levantamento"
            value={selectedLiftType}
            onChange={(e) => setSelectedLiftType(e.target.value as LiftType)}
          >
            {(Object.keys(liftTypeLabels) as LiftType[]).map((type) => (
              <option key={type} value={type}>{liftTypeLabels[type]}</option>
            ))}
          </select>
        </label>
      </div>

      <div className="mt-6 overflow-x-auto" role="region" aria-label="Tabela de resultados">
        <table className="min-w-full border" role="table">
          <caption className="sr-only">Resultados da competição selecionada</caption>
          <thead>
            <tr>
              {(["Place","Name","Sex","Age","Equipment","Division","Bodyweight (kg)"] as const).map((h) => (
                <th key={h} scope="col" className="border p-2 text-left">{h}</th>
              ))}
              <th scope="col" className="border p-2 text-left">{liftTypeLabels[selectedLiftType]} 1</th>
              <th scope="col" className="border p-2 text-left">{liftTypeLabels[selectedLiftType]} 2</th>
              <th scope="col" className="border p-2 text-left">{liftTypeLabels[selectedLiftType]} 3</th>
              {(["Total (kg)","GLPoints"] as const).map((h) => (
                <th key={h} scope="col" className="border p-2 text-left">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map((r, idx) => (
              <tr key={idx} className="even:bg-gray-50">
                <td className="border p-2">{r["Place"]}</td>
                <td className="border p-2">{r["Name"]}</td>
                <td className="border p-2">{r["Sex"]}</td>
                <td className="border p-2">{r["Age"]}</td>
                <td className="border p-2">{r["Equipment"]}</td>
                <td className="border p-2">{r["Division"]}</td>
                <td className="border p-2">{r["BodyweightKg"]}</td>
                <ResultCell value={r[attemptColumns[0]]} />
                <ResultCell value={r[attemptColumns[1]]} />
                <ResultCell value={r[attemptColumns[2]]} />
                <ResultCell value={r["TotalKg"]} isTotal />
                <ResultCell value={r["GLPoints"]} isTotal />
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}
