
// 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 useTeam from '../../hooks/useTeam';
import Signal, { useSignal } from '../../signal';

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

/**
 * component key modal
 *
 * @param props 
 */
const ComponentKeyModal = (props = {}) => {
  // signals
  const [api] = useSignal(ApiSignal);
  const [sKey, setKey] = useSignal(key);

  // team
  const team = useTeam();

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

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

    // set saving
    setSaving(true);

    // try/catch
    try {
      // save key
      const result = await api.Key[sKey?.id ? 'update' : 'create']({
        ...sKey,
        team : team?.id,
      });

      // set key value
      setKey(result.key);

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

  // return jsx
  return (
    <Overlay
      open={!!sKey}
      title={sKey?.name || api.translate('key:dialog.title', 'Create API Key')}
      onClose={() => setKey(null)}
      subtitle={api.translate('key:dialog.subtitle', 'Create a new API key to access your account')}
    >
      <Input
        name="name"
        type="text"
        label={api.translate('key:form.name.label', 'Name')}
        value={sKey?.name || ''}
        onChange={(e) => setKey({ ...sKey, name : e.target.value })}
        placeholder={api.translate('key:form.name.placeholder', 'API Key Name')}
      />

      {sKey?.value ? (
        <Input
          name="value"
          label={api.translate('key:form.key.label', 'Key')}
          value={sKey?.value || ''}
          placeholder={api.translate('key:form.key.placeholder', 'API Key')}
          readOnly
        />
      ) : (
        <p>
          {api.translate('key:dialog.pending', 'Please save the key to view the API key')}
        </p>
      )}
      
      <div className="pt-4 sm:pt-6 sm:flex sm:flex-row-reverse">
        <Button
          color="primary"
          onClick={onSave}
        >
          {saving ? api.translate('key:button.loading', 'Loading...') : api.translate('key:button.submit', 'Submit')}
        </Button>
        <Button
          color="transparent"
          onClick={() => setKey(null)}
        >
          {api.translate('key:button.cancel', 'Cancel')}
        </Button>
      </div>
    </Overlay>
  )
};

/**
 * export component key modal
 */
export default ComponentKeyModal;