"use client"

import * as React from "react"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"

export interface FormSelectOption {
  label: string
  value: string
}

export interface FormSelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
  label?: string
  error?: string
  helperText?: string
  options: FormSelectOption[]
  placeholder?: string
}

const FormSelect = React.forwardRef<HTMLSelectElement, FormSelectProps>(
  ({ className, label, error, helperText, id, options, placeholder, ...props }, ref) => {
    const generatedId = React.useId()
    const selectId = id || generatedId

    return (
      <div className="space-y-2">
        {label ? (
          <label htmlFor={selectId} className="text-sm font-semibold leading-none text-foreground">
            {label}
          </label>
        ) : null}
        <div className="relative">
          <select
            id={selectId}
            ref={ref}
            className={cn(
              "h-12 w-full appearance-none rounded-xl border border-border/70 bg-white px-4 pr-11 text-base text-foreground shadow-sm transition outline-none",
              "focus:border-primary focus:ring-4 focus:ring-primary/15 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
              error ? "border-destructive focus:ring-destructive/10" : "",
              className,
            )}
            {...props}
          >
            {placeholder ? <option value="">{placeholder}</option> : null}
            {options.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <ChevronDown className="pointer-events-none absolute right-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        </div>
        {error ? <p className="text-sm text-destructive">{error}</p> : null}
        {helperText && !error ? <p className="text-sm text-muted-foreground">{helperText}</p> : null}
      </div>
    )
  },
)
FormSelect.displayName = "FormSelect"

export { FormSelect }
