
// 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 client = new Signal.State(null);
export const remove = new Signal.State(null);

/**
 * component client modal
 *
 * @param props 
 */
const ComponentClientModal = (props = {}) => {
  // api
  const [api] = useSignal(ApiSignal);
  const [team] = useSignal(TeamSignal);
  const [sClient, setClient] = useSignal(client);

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

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

    // set saving
    setSaving(true);

    // try/catch
    try {
      // save client
      const result = await api.Client[sClient?.id ? 'update' : 'create']({
        ...(sClient || {}),
        team : team?.id,
      });

      // set client value
      setClient(result.client);

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

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

      {sClient?.value ? (
        <Input
          name="value"
          label={api.translate('client:form.value.label', 'Key')}
          value={sClient?.value || ''}
          placeholder={api.translate('client:form.value.placeholder', 'Client API Key')}
          readOnly
        />
      ) : (
        <p>
          {api.translate('client:dialog.pending', 'Please save the client 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('client:button.loading', 'Loading...') : api.translate('client:button.submit', 'Submit')}
        </Button>
        <Button
          color="transparent"
          onClick={() => setClient(null)}
        >
          {api.translate('client:button.cancel', 'Cancel')}
        </Button>
      </div>
    </Overlay>
  )
};

/**
 * export component client modal
 */
export default ComponentClientModal;