/* Copyright (C) 2024 Manuel Bustillo*/

'use client';

import { loadGroups } from '@/app/api/groups';
import { loadGuests } from '@/app/api/guests';
import { Group, Guest } from '@/app/lib/definitions';
import { classNames } from '@/app/ui/components/button';
import GuestFormDialog from '@/app/ui/components/guest-form-dialog';
import GroupsTable from '@/app/ui/groups/table';
import SkeletonTable from '@/app/ui/guests/skeleton-row';
import GuestsTable from '@/app/ui/guests/table';
import { TabPanel, TabView } from 'primereact/tabview';
import { Suspense, useEffect, useState } from 'react';


export default function Page() {
  function refreshGuests() {
    loadGuests((guests) => {
      setGuests(guests);
    });
  }

  function refreshGroups() {
    loadGroups((groups) => {
      setGroups(groups);
    });
  }

  const [groups, setGroups] = useState<Array<Group>>([]);
  const [guests, setGuests] = useState<Array<Guest>>([]);
  const [guestBeingEdited, setGuestBeingEdited] = useState<Guest | undefined>(undefined);

  useEffect(() => {
    refreshGroups();
    refreshGuests();
  }, []);

  return (
    <div className="w-full">
      <TabView>
        <TabPanel header="Guests" leftIcon="pi pi-users mx-2">
          <div className="flex flex-col w-full items-center justify-between">
            <button onClick={() => setGuestBeingEdited({})} className={classNames('primary')}>Add new</button>
            <GuestFormDialog
              key={guestBeingEdited?.id}
              groups={groups}
              onCreate={() => { refreshGuests(); setGuestBeingEdited(undefined) }}
              guest={guestBeingEdited}
              visible={guestBeingEdited !== undefined}
              onHide={() => { setGuestBeingEdited(undefined) }}
            />
            <Suspense fallback={<SkeletonTable />}>
              <GuestsTable guests={guests} onUpdate={refreshGuests} onEdit={(guest) => setGuestBeingEdited(guest)} />
            </Suspense>
          </div>
        </ TabPanel>
        <TabPanel header="Groups" leftIcon="pi pi-sitemap mx-2">
          <div className="flex w-full items-center justify-between">
            <Suspense fallback={<SkeletonTable />}>
              <GroupsTable groups={groups} />
            </Suspense>
          </div>
        </ TabPanel>
      </ TabView>
    </div>

  );
}