import React, { useEffect, useState } from "react";
import { loadCSV } from "./measurementParseCsv";

interface DynamicTableProps {
  csvPath: string;
  radioGroupName: "top" | "bottom"; // Make this explicit for clarity
}

export default function DynamicTable({
  csvPath,
  radioGroupName,
}: DynamicTableProps) {
  const [data, setData] = useState<string[][]>([]);
  const [selectedColIndex, setSelectedColIndex] = useState<number | null>(null);

  useEffect(() => {
    loadCSV(csvPath).then((loadedData) => {
      setData(loadedData);

      const headers = loadedData[0];
      const storageKey =
        radioGroupName === "top" ? "selectedTopSize" : "selectedBottomSize";
      const savedSize = localStorage.getItem(storageKey);

      if (savedSize && headers) {
        const index = headers.findIndex((h) => h === savedSize);
        if (index !== -1) {
          setSelectedColIndex(index);
        }
      }
    });
  }, [csvPath, radioGroupName]);

  const handleSelect = (colIndex: number) => {
    setSelectedColIndex(colIndex);

    const headers = data[0];
    const selectedSize = headers[colIndex];

    const storageKey =
      radioGroupName === "top" ? "selectedTopSize" : "selectedBottomSize";

    localStorage.setItem(storageKey, selectedSize);
  };

  if (!data.length) return <p>Loading chart...</p>;

  const headers = data[0];
  const bodyRows = data.slice(1);

  return (
    <div className="max-w-full overflow-auto">
      <table className="min-w-max border-collapse">
        <thead className="mob-noise sticky top-0 bg-gray-100">
          <tr>
            {headers.map((header, colIndex) => (
              <th
                key={colIndex}
                className={`font-bogart border-1 border-gray-950/25 font-light ${
                  colIndex === 0
                    ? "mob-noise sticky left-0 w-25 bg-gray-100 text-left"
                    : "w-18"
                } ${selectedColIndex === colIndex ? "bg-green-200" : ""}`}
              >
                <div className="flex pl-2">{colIndex === 0 ? header : ""}</div>
                {colIndex >= 1 && (
                  <label
                    className={`flex relative w-full cursor-pointer items-center justify-center flex-col gap-1 p-2 ${
                      selectedColIndex === colIndex ? "bg-green-300" : ""
                    }`}
                  >
                    <input
                      type="radio"
                      name={radioGroupName}
                      value={header}
                      onChange={() => handleSelect(colIndex)}
                      checked={selectedColIndex === colIndex}
                      className="relative cursor-pointer size-4 appearance-none rounded-full border-2 border-gray-950/75 bg-white before:absolute before:inset-1 before:rounded-full before:bg-white not-checked:before:hidden checked:bg-gray-950"
                    />
                    <span>{header}</span>
                  </label>
                )}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {bodyRows.map((row, rowIndex) => {
            const nonEmptyCells = row.filter((cell) => cell.trim() !== "");
            const isCaptionRow = nonEmptyCells.length === 1 && row[0] !== "";

            if (isCaptionRow) {
              return (
                <tr key={rowIndex}>
                  <td
                    colSpan={headers.length}
                    className="border border-gray-950/25 bg-gray-50 p-2 text-center font-bold uppercase"
                  >
                    {row[0]}
                  </td>
                </tr>
              );
            }

            return (
              <tr key={rowIndex}>
                {row.map((cell, colIndex) => {
                  if (colIndex === 0) {
                    return (
                      <td
                        key={colIndex}
                        className="font-bogart mob-noise sticky left-0 border-1 border-gray-950/25 bg-gray-100 p-2 font-light"
                      >
                        {cell}
                      </td>
                    );
                  }
                  return (
                    <td
                      key={colIndex}
                      className={`border border-gray-950/25 p-2 text-center text-xs ${
                        selectedColIndex === colIndex ? "bg-green-300 font-medium" : ""
                      }`}
                    >
                      {cell}
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
