<script>
  import { onMount } from 'svelte';
  import Header from '$lib/navigation/header.svelte';
  import Nav from '$lib/navigation/nav.svelte';
  import Loading from '$lib/navigation/loading.svelte';
  import ResultIsland from '$lib/islands/result-island.svelte';

  const title = "Reason Codes";
  let isLoading = false;
  let inputValue = '';
  let resultObject = {
    results: false,
    title: "",
    resultLines: []
  }

  function load() {
    isLoading = true;
    resultObject.results = false;
    getData().then(result => {
      handleData(result);
      isLoading = false;
    });
  }


  async function getData() {
    if (inputValue) {
      const url = `https://owlboard.info/api/v2/ref/reasonCode/${inputValue}`;
      const res = await fetch(url);
      return await res.json();
    } else {
      return []
    }
  }

  async function handleData(data) {
    let resultLines = []
    if (data.length) {
      resultObject.title = data[0]['code'];
      resultLines = [
        data[0]['lateReason'],
        data[0]['cancReason']
      ]
    } else {
      resultObject = {
        results: false,
        title: "Not Found",
        resultLines: []
      }
    }
    resultObject.resultLines = resultLines;
    resultObject.results = true;
  }

  onMount(() => {
    isLoading = false;
  });

  function handleInput(event) {
    inputValue = event.target.value;
  }

  function handleSubmit(event) {
    event.preventDefault();
    load();
  }
</script>

<Header {title} />
<p>A reason code is a three digit number that maps to a reason for a delay or cancellation</p>
<form on:submit={handleSubmit}>
  <input type="text" placeholder="Enter Code" autocomplete="off" bind:value={inputValue} on:input={handleInput} />

  <br>

  <button type="submit">Submit</button>
</form>

{#if isLoading}
  <Loading />
{/if}

{#if resultObject.results}
  <ResultIsland {resultObject} />
{/if}

<Nav />

<style>
    p {
      margin-top: 50px;
    }
    input {
        width: 25%;
        min-width: 50px;
        height: 32px;
        margin-top: 10px;
        margin-bottom: 5px;
        border-radius: 50px;
        border: none;
        text-align: center;
        font-family: urwgothic, 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
        text-transform: uppercase;
        font-size: 15px;
    }
    button {
        width: 15%;
        min-width: 40px;
        margin-bottom: 5px;
        margin-top: 5px;
        border: none;
        border-radius: 20px;
        padding: 5px;
        font-family: urwgothic, 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
        font-size: 16px;
        font-weight: 400;
        background-color: var(--overlay-color);
        color: var(--link-color);
    }
</style>