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

type Row = Record<string, string>;

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 [squatCol, setSquatCol] = useState<string>("Squat3Kg");
  const [benchCol, setBenchCol] = useState<string>("Bench3Kg");
  const [deadliftCol, setDeadliftCol] = useState<string>("Deadlift3Kg");

  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]);

  const attemptOptions = (prefix: string) => {
    const labelPrefix = prefix === "Squat" ? "Agachamento" : prefix === "Bench" ? "Supino" : "Levantamento terra";
    const opts = [1, 2, 3, 4]
      .map((n) => ({ key: `${prefix}${n}Kg`, label: `${labelPrefix} ${n}` }))
      .filter((o) => rows.some((r) => o.key in r));
    return opts;
  };

  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>
        <div className="grid grid-cols-3 gap-2" aria-label="Seleção de tentativas">
          <label>
            <span className="block font-semibold">Agachamento</span>
            <select className="mt-1 w-full border p-2" value={squatCol} onChange={(e) => setSquatCol(e.target.value)}>
              {attemptOptions("Squat").map((o) => (
                <option key={o.key} value={o.key}>{o.label}</option>
              ))}
            </select>
          </label>
          <label>
            <span className="block font-semibold">Supino</span>
            <select className="mt-1 w-full border p-2" value={benchCol} onChange={(e) => setBenchCol(e.target.value)}>
              {attemptOptions("Bench").map((o) => (
                <option key={o.key} value={o.key}>{o.label}</option>
              ))}
            </select>
          </label>
          <label>
            <span className="block font-semibold">Deadlift</span>
            <select className="mt-1 w-full border p-2" value={deadliftCol} onChange={(e) => setDeadliftCol(e.target.value)}>
              {attemptOptions("Deadlift").map((o) => (
                <option key={o.key} value={o.key}>{o.label}</option>
              ))}
            </select>
          </label>
        </div>
      </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">Agachamento</th>
              <th scope="col" className="border p-2 text-left">Supino</th>
              <th scope="col" className="border p-2 text-left">Deadlift</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>
                <td className="border p-2">{r[squatCol]}</td>
                <td className="border p-2">{r[benchCol]}</td>
                <td className="border p-2">{r[deadliftCol]}</td>
                <td className="border p-2">{r["TotalKg"]}</td>
                <td className="border p-2">{r["GLPoints"]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}
