import * as React from "react";
import { ChevronDown, Check } from "lucide-react";
import * as Radix from "radix-ui";

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

const Select = Radix.Select.Root;

const SelectTrigger = React.forwardRef<
  React.ElementRef<typeof Radix.Select.Trigger>,
  React.ComponentPropsWithoutRef<typeof Radix.Select.Trigger>
>(({ className, children, ...props }, ref) => (
  <Radix.Select.Trigger
    ref={ref}
    className={cn(
      "flex h-8 w-full items-center justify-between gap-2 rounded-md border border-input bg-background px-2.5 text-sm text-foreground focus-visible:outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
      className,
    )}
    {...props}
  >
    {children}
    <Radix.Select.Icon asChild>
      <ChevronDown className="size-4" />
    </Radix.Select.Icon>
  </Radix.Select.Trigger>
));

SelectTrigger.displayName = "SelectTrigger";

const SelectValue = React.forwardRef<
  React.ElementRef<typeof Radix.Select.Value>,
  React.ComponentPropsWithoutRef<typeof Radix.Select.Value>
>(({ className, ...props }, ref) => (
  <Radix.Select.Value
    ref={ref}
    className={cn("text-sm", className)}
    {...props}
  />
));

SelectValue.displayName = "SelectValue";

const SelectContent = React.forwardRef<
  React.ElementRef<typeof Radix.Select.Content>,
  React.ComponentPropsWithoutRef<typeof Radix.Select.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
  <Radix.Select.Portal>
    <Radix.Select.Content
      ref={ref}
      position={position}
      className={cn(
        "z-50 w-[var(--radix-select-trigger-width)] min-w-44 rounded-md border bg-popover text-popover-foreground shadow-md outline-none",
        className,
      )}
      {...props}
    >
      <Radix.Select.Viewport className="rounded-md p-1">
        <Radix.Select.Group>{children}</Radix.Select.Group>
      </Radix.Select.Viewport>
    </Radix.Select.Content>
  </Radix.Select.Portal>
));

SelectContent.displayName = "SelectContent";

const SelectItem = React.forwardRef<
  React.ElementRef<typeof Radix.Select.Item>,
  React.ComponentPropsWithoutRef<typeof Radix.Select.Item>
>(({ className, children, ...props }, ref) => (
  <Radix.Select.Item
    ref={ref}
    className={cn(
      "relative flex w-full cursor-pointer select-none items-center rounded-sm px-2 py-1 text-sm outline-none aria-disabled:pointer-events-none aria-disabled:opacity-50 aria-selected:bg-accent aria-selected:text-accent-foreground",
      className,
    )}
    {...props}
  >
    <Radix.Select.ItemText>{children}</Radix.Select.ItemText>
    <Radix.Select.ItemIndicator className="absolute right-2 inline-flex items-center">
      <Check className="size-4" />
    </Radix.Select.ItemIndicator>
  </Radix.Select.Item>
));

SelectItem.displayName = "SelectItem";

export { Select, SelectTrigger, SelectValue, SelectContent, SelectItem };
