"use client";
import Papa from "papaparse";
import { useEffect, useState } from "react";

interface TableProps {
  fileName: string;
}

export default function DynamicChart({ fileName}: TableProps) {
  const [data, setData] = useState<string[][]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(`/data/sizechart/${fileName}.csv`);
        const text = await response.text();
        const parsed = Papa.parse<string[]>(text, { header: false });
        setData(parsed.data);
      } catch (error) {
        console.error("Error loading CSV file:", error);
      }
    };

    fetchData();
  }, [fileName]);

  if (data.length === 0) {
    return <p>Loading size chart...</p>;
  }

  return (
    <div className="w-full overflow-x-auto">
      <table className="w-full size-fit table-fixed border-1 border-collapse">
        <thead>
          <tr>
            {data[0].map((header, index) => (
              <th key={index}>{header}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.slice(1).map((row, rowIndex) => (
            <tr key={rowIndex}>
              {row.map((cell, cellIndex) => (
                <td key={cellIndex} className="p-4">{cell}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
