<script>
  import { onMount } from 'svelte';
  import { valueSets } from '$lib/stores/valuesets.js';
  import { ChevronDown } from 'lucide-svelte';

  /**
   * @typedef {Object} Props
   * @property {string} label - Input label
   * @property {string} name - Input name
   * @property {string} [value] - Selected value
   * @property {string} [valueSetKey] - ValueSet key to load options from
   * @property {Array<{value: string, label: string}>} [options] - Manual options array
   * @property {string} [placeholder] - Placeholder text
   * @property {boolean} [required] - Whether input is required
   * @property {boolean} [disabled] - Whether input is disabled
   * @property {string} [error] - Error message
   * @property {string} [class] - Additional CSS classes
   */

  /** @type {Props} */
  let {
    label,
    name,
    value = $bindable(''),
    valueSetKey = '',
    options = [],
    placeholder = 'Select...',
    required = false,
    disabled = false,
    error = '',
    class: className = '',
  } = $props();

  let loading = $state(false);
  let dropdownOptions = $state([]);

  // Load options from ValueSet if key is provided
  onMount(async () => {
    if (valueSetKey) {
      loading = true;
      try {
        const items = await valueSets.load(valueSetKey);
        if (!items || items.length === 0) {
          console.warn('SelectDropdown: No items loaded for valueset:', valueSetKey);
        }
        dropdownOptions = items.map((item) => ({
          value: item.value || item.Value || item.code || item.Code || item.ItemCode || item.itemCode || '',
          label: item.label || item.Label || item.description || item.Description || item.name || item.Name || item.value || item.Value || '',
        }));
      } catch (err) {
        console.error('SelectDropdown error loading valueset:', err);
      } finally {
        loading = false;
      }
    } else if (options.length > 0) {
      dropdownOptions = options;
    }
  });

  // Watch for changes in manual options
  $effect(() => {
    if (!valueSetKey) {
      dropdownOptions = options;
    }
  });

  // Check if current value exists in options (empty string is always valid)
  let hasValidValue = $derived(
    value === '' || value === null || value === undefined || dropdownOptions.some(opt => opt.value === value)
  );
</script>

<div class="form-control w-full {className}">
  <label class="label" for={name}>
    <span class="label-text font-medium">
      {label}
      {#if required}
        <span class="text-error">*</span>
      {/if}
    </span>
  </label>
  
  <div class="relative">
    {#key `${value}-${dropdownOptions.length}`}
      <select
        {name}
        id={name}
        bind:value
        {required}
        {disabled}
        class="select select-sm select-bordered w-full pr-10 bg-none {error ? 'select-error' : ''}"
        class:opacity-50={loading}
      >
        <option value="">{placeholder}</option>
        
        {#each dropdownOptions as option (option.value)}
          <option value={option.value}>{option.label}</option>
        {/each}
      </select>
    {/key}
    
    <div class="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
      {#if loading}
        <span class="loading loading-spinner loading-sm"></span>
      {:else}
        <ChevronDown class="w-4 h-4 opacity-50" />
      {/if}
    </div>
  </div>
  
  {#if error}
    <label class="label">
      <span class="label-text-alt text-error">{error}</span>
    </label>
  {/if}
</div>
