import { JSX, For, splitProps, createSignal, Show } from "solid-js";

interface SelectOption {
  value: string;
  label: string;
  disabled?: boolean;
}

interface SelectProps extends Omit<JSX.SelectHTMLAttributes<HTMLSelectElement>, "onChange"> {
  label?: string;
  error?: string;
  hint?: string;
  options: SelectOption[];
  onChange?: (value: string) => void;
}

export function Select(props: SelectProps) {
  const [local, rest] = splitProps(props, ["label", "error", "hint", "options", "onChange", "class"]);
  const [isFocused, setIsFocused] = createSignal(false);

  const handleChange = (e: Event) => {
    const target = e.target as HTMLSelectElement;
    local.onChange?.(target.value);
  };

  return (
    <div class="w-full">
      <Show when={local.label}>
        <label class="block font-display text-sm font-medium text-ink mb-2">
          {local.label}
        </label>
      </Show>
      
      <div class="relative">
        <select
          {...rest}
          onChange={handleChange}
          onFocus={() => setIsFocused(true)}
          onBlur={() => setIsFocused(false)}
          class={[
            "w-full appearance-none bg-canvas border rounded-button px-4 py-3 pr-10",
            "font-sans text-ink",
            "transition-all duration-200",
            "hover:border-border-strong",
            "focus:outline-none focus:ring-3",
            isFocused() ? "border-accent ring-accent/10" : "border-border",
            local.error ? "border-error focus:border-error focus:ring-error/10" : "",
            "cursor-pointer",
            local.class || "",
          ].join(" ")}
        >
          <For each={local.options}>
            {(option) => (
              <option 
                value={option.value}
                disabled={option.disabled}
                class="py-2"
              >
                {option.label}
              </option>
            )}
          </For>
        </select>
        
        {/* Custom dropdown arrow */}
        <div class="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-ink-muted">
          <svg 
            xmlns="http://www.w3.org/2000/svg" 
            width="16" 
            height="16" 
            viewBox="0 0 24 24" 
            fill="none" 
            stroke="currentColor" 
            stroke-width="2" 
            stroke-linecap="round" 
            stroke-linejoin="round"
            class={isFocused() ? "rotate-180 transition-transform duration-200" : "transition-transform duration-200"}
          >
            <path d="m6 9 6 6 6-6"/>
          </svg>
        </div>
      </div>
      
      <Show when={local.error}>
        <p class="mt-1.5 text-sm text-error">{local.error}</p>
      </Show>
      
      <Show when={local.hint && !local.error}>
        <p class="mt-1.5 text-sm text-ink-muted">{local.hint}</p>
      </Show>
    </div>
  );
}
