import * as React from "react"
import { ChevronDownIcon } from "lucide-react"

import { cn } from "@/lib/utils"

function NativeSelect({
  className,
  size = "default",
  ...props
}: Omit<React.ComponentProps<"select">, "size"> & { size?: "sm" | "default" }) {
  return (
    <div
      className="group/native-select relative w-fit has-[select:disabled]:opacity-50"
      data-slot="native-select-wrapper"
    >
      <select
        data-slot="native-select"
        data-size={size}
        className={cn(
          "h-[var(--control-height-md)] w-full min-w-0 appearance-none rounded-md border border-border-tertiary bg-transparent px-[var(--control-padding-x-md)] py-[var(--control-padding-y-md)] pr-[var(--control-icon-size-md)] text-[length:var(--control-font-size-md)] leading-[var(--control-line-height-md)] shadow-sm transition-[color,box-shadow] outline-none selection:bg-primary selection:text-text-on-primary placeholder:text-text-tertiary disabled:pointer-events-none disabled:cursor-not-allowed data-[size=sm]:h-[var(--control-height-sm)] data-[size=sm]:py-[var(--control-padding-y-sm)] data-[size=sm]:text-[length:var(--control-font-size-sm)] data-[size=sm]:leading-[var(--control-line-height-sm)] dark:bg-input/30 dark:hover:bg-input/50",
          "focus-visible:border-border-secondary focus-visible:ring-0",
          "aria-invalid:border-error aria-invalid:ring-error/20 dark:aria-invalid:ring-error/40",
          className
        )}
        {...props}
      />
      <ChevronDownIcon
        className="pointer-events-none absolute top-1/2 right-3.5 size-4 -translate-y-1/2 text-text-tertiary opacity-50 select-none"
        aria-hidden="true"
        data-slot="native-select-icon"
      />
    </div>
  )
}

function NativeSelectOption({
  className,
  ...props
}: React.ComponentProps<"option">) {
  return (
    <option
      data-slot="native-select-option"
      className={cn("bg-[Canvas] text-[CanvasText]", className)}
      {...props}
    />
  )
}

function NativeSelectOptGroup({
  className,
  ...props
}: React.ComponentProps<"optgroup">) {
  return (
    <optgroup
      data-slot="native-select-optgroup"
      className={cn("bg-[Canvas] text-[CanvasText]", className)}
      {...props}
    />
  )
}

export { NativeSelect, NativeSelectOptGroup, NativeSelectOption }
