<script lang="ts">
  import Icon from '@iconify/svelte';
	import type { Model } from "$lib/utils/type";

  let open = false;

  export let items: Model[];
  export let value: string;
  export let onChange: (value: string) => void;

  $: selectedModel = items.find(({ id }) => id === value)

  const handleSelect = (id: string) => {
    onChange(id)
    open = false;
  }

  const handleOpen = () => open = !open
</script>

<div class="w-full flex flex-col gap-2.5">
  <label
    for="model"
    class="font-sans text-slate-400 font-regular text-sm"
  >
    Model:
  </label>
  <div
    id="model"
    class={`cursor-pointer shadow-inner font-code border hover:bg-slate-900/90 hover:border-slate-700/80 text-white rounded-lg text-sm w-full transition-all duration-200 leading-relaxed outline-none relative ${open ? 'bg-slate-900/90 border-slate-700/80' : 'border-slate-800 bg-slate-900/60'}`}
  >
    <button class="w-full flex justify-between items-center px-4 py-3" role="searchbox" on:click={handleOpen}>
      {#if selectedModel}
        <div class="flex items-center justify-start gap-3">
          <img
            src={selectedModel.logo}
            alt={selectedModel.id}
            width={22}
            height={22}
            class="rounded-full"
          />
          <p>{selectedModel?.label ?? selectedModel?.id}</p>
          {#if selectedModel?.label}
            <p class="text-slate-400 text-xs">({selectedModel?.id})</p>
          {/if}
        </div>
        {:else}
        <p class="opacity-70">Select a model</p>
      {/if}
      <Icon icon="iconamoon:arrow-right-2-light" class={`text-slate-400 w-5 h-5 transition-all duration-150 ${open && 'transform rotate-90'}`}  />
    </button>
    <div
      class="absolute bottom-0 left-0 w-full pt-4 translate-y-full transition-all duration-150"
      class:pointer-events-none={!open}
      class:opacity-0={!open}
    >
      <div class="bg-slate-900 border border-slate-700/80 text-white p-2 font-code rounded-lg">
        {#each items as { id, logo, label }}
          <button
            class={`w-full flex items-center justify-start gap-3 p-2 cursor-pointer hover:bg-slate-800/60 rounded-lg ${selectedModel?.id === id && 'bg-slate-800/60'}`}
            on:click={() => handleSelect(id)}
          >
            <img
              src={logo}
              alt={id}
              width={22}
              height={22}
              class="rounded-full"
            />
            <p>{label ?? id}</p>
          </button>
        {/each}
      </div>
    </div>
  </div>
</div>