/* Copyright (C) 2024 Manuel Bustillo*/

'use client';

import { Guest } from '@/app/lib/definitions';
import { getCsrfToken } from '@/app/lib/utils';
import { classNames } from '@/app/ui/components/button';
import clsx from 'clsx';
import React from 'react';
import InlineTextField from '../components/form/inlineTextField';
import TableOfContents from '../components/table-of-contents';

export default function guestsTable({ guests, updateGuestStatus }: { guests: Guest[], updateGuestStatus: (id: string, status: string) => void }) {
  const handleInviteGuest = (e: React.MouseEvent<HTMLElement>) => handleGuestChange(e, 'invited');
  const handleConfirmGuest = (e: React.MouseEvent<HTMLElement>) => handleGuestChange(e, 'confirmed');
  const handleDeclineGuest = (e: React.MouseEvent<HTMLElement>) => handleGuestChange(e, 'declined');
  const handleTentativeGuest = (e: React.MouseEvent<HTMLElement>) => handleGuestChange(e, 'tentative');

  const handleGuestUpdate = (guest: Guest) => {
    fetch(`/api/guests/${guest.id}`,
      {
        method: 'PUT',
        body: JSON.stringify({ guest: { name: guest.name } }),
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-TOKEN': getCsrfToken(),
        }
      })
      .catch((error) => console.error(error));
  }


  const handleGuestChange = (e: React.MouseEvent<HTMLElement>, status: string) => {
    updateGuestStatus(e.currentTarget.getAttribute('data-guest-id') || '', status);
  }


  return (
    <TableOfContents
      headers={['Name', 'Group', 'Status', 'Actions']}
      caption='Guests'
      elements={guests}
      rowRender={(guest) => (
        <tr key={guest.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">
            <InlineTextField initialValue={guest.name} onChange={(newName) => { guest.name = newName; handleGuestUpdate(guest) }} />
          </td>
          <td className="px-6 py-4">
            {guest.group_name}
          </td>
          <td className="px-6 py-4">
            <span className="flex items-center text-sm dark:text-white me-3">
              <span className={clsx(
                'flex w-2.5 h-2.5 rounded-full me-1.5 flex-shrink-0',
                {
                  'bg-gray-400': guest.status === 'considered',
                  'bg-blue-400': guest.status === 'invited',
                  'bg-green-600': guest.status === 'confirmed',
                  'bg-red-400': guest.status === 'declined',
                  'bg-yellow-400': guest.status === 'tentative',
                }
              )}>
              </span>
              {guest.status}
            </span>
          </td>
          <td>
            {guest.status === 'considered' && (<button data-guest-id={guest.id} onClick={handleInviteGuest} className={classNames('blue')}>
              Invite
            </button>)}
            {(guest.status === 'invited' || guest.status === 'tentative') && (
              <>
                <button data-guest-id={guest.id} onClick={handleConfirmGuest} className={classNames('green')}>Confirm</button>
                {guest.status != 'tentative' && <button data-guest-id={guest.id} onClick={handleTentativeGuest} className={classNames('yellow')}>Tentative</button>}
                <button data-guest-id={guest.id} onClick={handleDeclineGuest} className={classNames('red')}>Decline</button>
              </>
            )}
          </td>
        </tr>
      )}
    />
  );
}
