/* Copyright (C) 2024 Manuel Bustillo*/

'use client';

import TableOfContents from '../components/table-of-contents';
import React, { useState } from 'react';
import { Group } from '@/app/lib/definitions';

export default function GroupsTable() {
  const [groups, setGroups] = useState<Array<Group>>([]);
  const [groupsLoaded, setGroupsLoaded] = useState(false);

  function loadGroups() {
    fetch("/api/groups")
      .then((response) => response.json())
      .then((data) => {
        setGroups(data.map((record: any) => {
          return ({
            id: record.id,
            name: record.name,
            color: record.color,
            attendance: {
              considered: record.considered,
              invited: record.invited,
              confirmed: record.confirmed,
              tentative: record.tentative,
              declined: record.declined,
              total: record.total,
            }
          });
        }));
        setGroupsLoaded(true);
      }, (error) => {
        return [];
      });
  }

  !groupsLoaded && loadGroups();

  return (
    <TableOfContents
      headers={['Name', 'Color', 'Confirmed', 'Tentative', 'Pending', 'Declined', 'Considered', 'Total']}
      caption='Groups'
      elements={groups}
      rowRender={(group) => (
        <tr key={group.id} className="bg-white border-b odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800">
          <td scope="row" className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
            {group.name}
          </td>
          <td className="px-6">
            <div className="w-8 h-8 rounded-full" style={{ backgroundColor: group.color }}></div>
          </td>
          <td className="px-6 text-lg">
            {group.attendance?.confirmed}
          </td>
          <td className="px-6 text-sm">
            {group.attendance?.tentative}
          </td>
          <td className="px-6 text-sm">
            {group.attendance?.invited}
          </td>
          <td className="px-6 text-sm">
            {group.attendance?.declined}
          </td>
          <td className="px-6 text-sm">
            {group.attendance?.considered}
          </td>
          <td className="px-6 text-sm">
            {group.attendance?.total}
          </td>
        </tr>
      )}
    />
  )
}