
// imports
import { useRouter } from 'next/navigation';
import React, { useState } from 'react';

// locals
import Input from '../Input';
import Button from '../Button';
import Overlay from '../Overlay';
import ApiSignal from '../../signals/Api';
import TeamsSignal from '../../signals/Teams';
import { addSnack } from '../../signals/Snacks';
import Signal, { useSignal } from '../../signal';

// update
export const update = new Signal.State(null);

/**
 * component team globals
 */
const ComponentTeamGlobals = (props = {}) => {
  // translation
  const [sApi] = useSignal(ApiSignal);
  const [sTeams, setTeams] = useSignal(TeamsSignal);
  const [sUpdate, setUpdate] = useSignal(update);

  // state
  const [saving, setSaving] = useState(false);

  // use router
  const router = useRouter();

  // on save
  const onSave = async () => {
    // saving
    if (saving) return;

    // set saving
    setSaving(true);

    // try/catch
    try {
      // call api
      const result = await sApi.Team[sUpdate.id ? 'update' : 'create'](sUpdate);

      // check message
      if (result?.message) {
        // add snack
        addSnack({
          id       : 'team.save',
          message  : sApi.translate(`team:validate.${result.message}`),
          severity : 'error',
        });

        // return
        return;
      }

      // check team
      if (result?.team) {
        // if not in teams signal
        if (!sTeams.find((team) => team.id === result.team.id)) {
          // push
          sTeams.push(result.team);
        }

        // replace in teams signal
        setTeams(sTeams.map((team) => {
          // check id
          if (team.id === result.team.id) {
            // return result team
            return result.team;
          }

          // return team
          return team;
        }));
        
        // update team
        router.push(`/${result.team.id}`);
      }

      // close
      setUpdate(null);
    } catch (e) {
      // error
      console.error(e);
    } finally {
      // set saving
      setSaving(false);
    }
  };

  // return jsx
  return sApi && (
    <Overlay
      open={!!sUpdate}
      title={sApi.translate('team:dialog.team.title')}
      onClose={() => setUpdate(null)}
      subtitle={sApi.translate('team:dialog.subtitle')}
    >
      <Input
        name="name"
        type="text"
        label={sApi.translate('team:form.team.name.label')}
        value={sUpdate?.name || ''}
        onChange={(e) => setUpdate({
          ...(sUpdate || {}),
          name : e.target.value,
        })}
        placeholder={sApi.translate('team:form.team.name.placeholder')}
      />
      
      <div className="pt-4 sm:pt-6 sm:flex sm:flex-row-reverse">
        <Button
          color="primary"
          onClick={onSave}
        >
          {saving ? sApi.translate('team:button.loading') : sApi.translate(`team:button.submit`)}
        </Button>
        <Button
          color="transparent"
          onClick={() => setUpdate(null)}
        >
          {sApi.translate('team:button.cancel')}
        </Button>
      </div>
    </Overlay>
  );
};

/**
 * export team globals
 */
export default ComponentTeamGlobals;