/* Copyright (C) 2024 Manuel Bustillo*/

'use client'

import React, { useState } from "react"
import { TableArrangement } from '@/app/lib/definitions';
import { classNames } from "../components/button";

export default function ArrangementsTable ({onArrangementSelected}: {onArrangementSelected: (arrangementId: string) => void}) {
    const [arrangements, setArrangements] = useState<Array<TableArrangement>>([]);

    function loadArrangements() {
      fetch("/api/tables_arrangements")
        .then((response) => response.json())
        .then((data) => {
          setArrangements(data.map((record: any) => {
            return ({
              id: record.id,
              discomfort: record.discomfort
            });
          }));
        }, (error) => {
          return [];
        });
    }

    function arrangementClicked(e: React.MouseEvent<HTMLElement>) {
        onArrangementSelected(e.currentTarget.getAttribute('data-arrangement-id') || '');
    }
  
    arrangements.length === 0 && loadArrangements();

    return(
        <div className="w-full relative overflow-x-auto shadow-md sm:rounded-lg">
        <table className="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400">
          <caption className="p-5 text-lg font-semibold text-left rtl:text-right text-gray-900 bg-white dark:text-white dark:bg-gray-800">
            Simulations
            <p className="mt-1 text-sm font-normal text-gray-500 dark:text-gray-400">
              There are {arrangements.length} simmulations in the list
            </p>
          </caption>
          <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
            <tr>
              <th scope="col" className="px-6 py-3">
                ID
              </th>
              <th scope="col" className="px-6 py-3">
                Discomfort
              </th>              
              <th scope="col" className="px-6 py-3">
                Actions
              </th>
            </tr>
          </thead>
          <tbody>
            {arrangements.map((arrangement) => (
              <tr key={arrangement.id} className="bg-white border-b odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800">
                <th scope="row" className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
                  {arrangement.id}
                </th>
                <td className="px-6 py-4">
                  {arrangement.discomfort}
                </td>
                <td>
                    <button data-arrangement-id={arrangement.id} onClick={arrangementClicked} className={classNames('primary')}>Load</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
}