"use client";

import { type SelectHTMLAttributes, useId } from "react";
import clsx from "clsx";

import styles from "./SelectInput.module.scss";

type Option = {
  value: string | number;
  label: string;
};

interface SelectInputProps extends SelectHTMLAttributes<HTMLSelectElement> {
  error?: string;
  options: Option[];
  placeholder?: string;
  containerClassName?: string;
}

export const SelectInput = ({
  error,
  options,
  placeholder,
  className,
  containerClassName,
  ...props
}: SelectInputProps) => {
  const id = useId();

  return (
    <div className={clsx(styles.container, containerClassName)}>
      <select
        id={id}
        className={clsx(styles.select, error && styles.selectError, className)}
        {...props}
      >
        {placeholder && (
          <option value="" hidden>
            {placeholder}
          </option>
        )}
        {options.map(option => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
      {error && <p className={styles.errorText}>{error}</p>}
    </div>
  );
};
