<script lang="ts">
    import IoMdEye from 'svelte-icons/io/IoMdEye.svelte';
    import IoMdEyeOff from 'svelte-icons/io/IoMdEyeOff.svelte';

    export let label: string;
    export let value = ""
    export let type = "text"
    let show = type != 'password';
    const id = Math.random().toString(36).substr(2, 9);
    const toggle = () => {

        const element = document.getElementById(id) as HTMLInputElement;
        if (element === null) return;
        element.type = show === true ? 'password' : 'text';
        show = !show;
    };
    let test: HTMLInputElement;

    function typeAction(node: HTMLInputElement) {
        node.type = type;
    }

    export let errors: string[] = []
</script>

<div class="input">
    <div class="labeled">
        {#if label != null}<label for={id}>{label}</label>
        {/if}

        <input use:typeAction {id} bind:value {...$$restProps}/>
        {#if type == 'password'}
            <div class="toggle" on:click={toggle} on:keypress={() => {}}>
                {#if show == false}
                    <IoMdEyeOff/>
                {:else if show == true}
                    <IoMdEye/>
                {/if}
            </div>
        {/if}
    </div>
    {#if errors.length !== 0}
        <p class="error-msg">{errors[0]}</p>
    {/if}
</div>

<style lang="scss">

  .input {
    display: flex;
    flex-direction: column;
    margin: 0.5rem;
  }

  .labeled {
    display: flex;
    flex-direction: column;

    position: relative;
  }

  .toggle {
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    right: 0;
    width: 20px;
    height: 20px;
    cursor: pointer;
  }

  .error-msg{
    color: $red;
    margin-top: 5px;
  }
  label {
    font-size: 0.8rem;
    margin-bottom: 0.2rem;
    text-transform: uppercase;
  }

  input {
    border-radius: 0.2rem;
    background: #160339;
    border: 1px solid $border;
    color: #f8f8f8;
    border-radius: 0;
    padding: 12px 8px;

    &:focus {
      border: 1px solid $contrast;
      outline: none;
      box-shadow: 0 0 0 3px #1a0f7a;
    }
  }
</style>