/* Copyright (C) 2024 Manuel Bustillo*/

'use client';

import { Group } from '@/app/lib/definitions';
import { getCsrfToken } from '@/app/lib/utils';
import { classNames } from '@/app/ui/components/button';
import { Dialog } from 'primereact/dialog';
import { Dropdown } from 'primereact/dropdown';
import { FloatLabel } from 'primereact/floatlabel';
import { InputText } from 'primereact/inputtext';
import { useState } from 'react';

export default function CreationDialog({ groups, onCreate }: { groups: Group[], onCreate?: () => void }) {
  const [visible, setVisible] = useState(false);

  const [name, setName] = useState('');
  const [group, setGroup] = useState(null);
  function createGuest() {
    fetch("/api/guests", {
      method: 'POST',
      body: JSON.stringify({ name: name, group_id: group }),
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': getCsrfToken(),
      }
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        setVisible(false);
        onCreate && onCreate();
      })
      .catch((error) => console.error(error));
  }

  return (
    <>
      <button onClick={() => setVisible(true)} className={classNames('primary')}>Add new</button>

      <Dialog header="Add guest" visible={visible} style={{ width: '50vw' }} onHide={() => { if (!visible) return; setVisible(false); }}>
        <div className="card flex justify-evenly py-5">
          <FloatLabel>
            <InputText id="username" className='rounded-sm' value={name} onChange={(e) => setName(e.target.value)} />
            <label htmlFor="username">Username</label>
          </FloatLabel>
          <FloatLabel>
            <Dropdown id="group" className='rounded-sm min-w-32' value={group} onChange={(e) => setGroup(e.target.value)} options={
              groups.map((group) => {
                return { label: group.name, value: group.id };
              })
            } />
            <label htmlFor="group">Group</label>
          </FloatLabel>
          <button className={classNames('primary')} onClick={createGuest} disabled={!(name.length > 0 && group)}>Create</button>
        </div>
      </Dialog>
    </>
  );
}