<script>
  import api from "$/client/api.js";
  import FormField from '$/client/components/FormField.svelte';

  let form = {
    to_address: "",
  }

  let error;
  let message;
  let config;

  const send_test = async () => {
    const [status, data] = await api.post(`/api/admin/email`, form);

    if(status == 200) {
      message = data.message;
      config = data.config;
    } else {
      error = data.message;
      form = Object.assign(form, data);
    }
  }
</script>

<form>
  <card>
  <middle>
  <FormField form={ form } field="to_address" label="To Email">
    <input type="text" id="to_address" bind:value={form.to_address } name="to_address">
  </FormField>
  {#if message}
    <br/>
    <callout class="info" data-testid="result-message">
    <span>{ message }</span>
    </callout>
  {/if}
  </middle>

  <bottom>
  <button-group>
    <button data-testid="send-button" on:click|preventDefault={ () => send_test() }>Send</button>
  </button-group>
  </bottom>
  </card>
</form>

{#if error}
  <callout class="error">
  <span>Fatal Error: { error }</span>
  </callout>
{/if}

{#if config}
  <h2>Mail Server Config</h2>
<pre>
<code>
{JSON.stringify(config, null, 2)}
</code>
</pre>
{/if}
