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

// locals
import Input from '../Input';
import Button from '../Button';
import Overlay from '../Overlay';
import useTeam from '../../hooks/useTeam';
import ApiSignal from '../../signals/Api';
import Signal, { useSignal } from '../../signal';

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

/**
 * component secret modal
 *
 * @param props 
 */
const ComponentSecretModal = (props = {}) => {
  // signals
  const [sApi] = useSignal(ApiSignal);
  const [sSecret, setSecret] = useSignal(secret);
   
  // use state
  const [saving, setSaving] = useState(false);

  // use team
  const team = useTeam();

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

    // set saving
    setSaving(true);

    // try/catch
    try {
      // save secret
      const result = await sApi.Secret[sSecret?.id ? 'update' : 'create']({
        ...sSecret,
        team : team?.id,
      });

      console.log(result);

      // set secret value
      setSecret(null);

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

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

/**
 * export component secret modal
 */
export default ComponentSecretModal;