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

// locals
import Input from '../Input';
import Button from '../Button';
import Overlay from '../Overlay';
import ApiSignal from '../../signals/Api';
import Signal, { useSignal } from '../../signal';
import { current as TeamSignal } from '../../signals/Teams';

// open
export const branch = new Signal.State(null);
export const remove = new Signal.State(null);

/**
 * component branch modal
 *
 * @param props 
 */
const ComponentBranchModal = (props = {}) => {
  // signals
  const [api] = useSignal(ApiSignal);
  const [sBranch, setBranch] = useSignal(branch);

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

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

    // set saving
    setSaving(true);

    // try/catch
    try {
      // save branch
      const result = await api.WorkflowBranch[sBranch?.id ? 'update' : 'create']({
        ...sBranch,
        team     : TeamSignal.value?.id,
        workflow : props.workflow?.id,
      });

      // set branch value
      setBranch(result.branch);

      // on change
      if (props.onChange) props.onChange(sBranch);
    } catch (e) {
      // log
      console.error(e);
    } finally {
      // set saving
      setSaving(false);
    }
  };

  // return jsx
  return (
    <Overlay
      open={!!sBranch}
      title={sBranch?.name || api.translate('branch:dialog.title', 'Create Branch')}
      onClose={() => setBranch(null)}
      subtitle={api.translate('branch:dialog.subtitle', 'Create a new branch for your workflow')}
    >
      <Input
        name="name"
        type="text"
        label={api.translate('branch:form.name.label', 'Name')}
        value={sBranch?.name || ''}
        onChange={(e) => setBranch({ ...sBranch, name : e.target.value })}
        placeholder={api.translate('branch:form.name.placeholder', 'Branch Name')}
      />
      
      <div className="pt-4 sm:pt-6 sm:flex sm:flex-row-reverse">
        <Button
          color="primary"
          onClick={onSave}
        >
          {saving ? api.translate('branch:button.loading', 'Loading...') : api.translate('branch:button.submit', 'Submit')}
        </Button>
        <Button
          color="transparent"
          onClick={() => setBranch(null)}
        >
          {api.translate('branch:button.cancel', 'Cancel')}
        </Button>
      </div>
    </Overlay>
  )
};

/**
 * export component branch modal
 */
export default ComponentBranchModal;