import { useId } from "react";
import { HaloIcon } from "@/components/ui/HaloIcon";
import type { HaloIconName } from "@/components/ui/HaloIcon";
import styles from "./prism-select.module.css";

export type PrismSelectOption = {
  value: string;
  label: string;
  disabled?: boolean;
};

type PrismSelectProps = {
  ariaLabel?: string;
  className?: string;
  defaultValue?: string;
  disabled?: boolean;
  helperText?: string;
  id?: string;
  label?: string;
  leadingIcon?: HaloIconName;
  name?: string;
  onChange?: (value: string) => void;
  options: PrismSelectOption[];
  size?: "compact" | "standard";
  status?: "default" | "error";
  value?: string;
  width?: "content" | "compact" | "medium" | "rooftop" | "workflow" | "period" | "full";
};

export function PrismSelect({
  ariaLabel,
  className,
  defaultValue,
  disabled = false,
  helperText,
  id,
  label,
  leadingIcon,
  name,
  onChange,
  options,
  size = "compact",
  status = "default",
  value,
  width = "content"
}: PrismSelectProps) {
  const generatedId = useId();
  const selectId = id ?? generatedId;
  const helperId = helperText ? `${selectId}-helper` : undefined;

  return (
    <div
      className={[styles.field, className].filter(Boolean).join(" ")}
      data-size={size}
      data-status={disabled ? "disabled" : status}
      data-width={width}
    >
      {label ? (
        <label className={styles.label} htmlFor={selectId}>
          {label}
        </label>
      ) : null}
      <div className={styles.control}>
        {leadingIcon ? (
          <span className={styles.leadingIcon} aria-hidden="true">
            <HaloIcon name={leadingIcon} />
          </span>
        ) : null}
        <select
          aria-describedby={helperId}
          aria-invalid={status === "error" ? true : undefined}
          aria-label={ariaLabel ?? label}
          className={styles.select}
          defaultValue={value === undefined ? defaultValue : undefined}
          disabled={disabled}
          id={selectId}
          name={name}
          onChange={(event) => onChange?.(event.target.value)}
          value={value}
        >
          {options.map((option) => (
            <option disabled={option.disabled} key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
        <span className={styles.chevron} aria-hidden="true">
          <HaloIcon name="chevronDown" />
        </span>
      </div>
      {helperText ? (
        <span className={styles.helper} id={helperId}>
          {helperText}
        </span>
      ) : null}
    </div>
  );
}
