import * as React from 'react'
import * as SelectPrimitive from '@radix-ui/react-select'
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/lib/utils'
import { ArrowDownSLine, ArrowUpSLine, CheckLine } from './icons-inline'
import { getThemeFromDocument } from './theme-from-document'

/** 取消 outline/ring，避免与全局 *:focus-visible 冲突产生偶现 focus 环；用 !important 压过全局 */
const FOCUS_RESET =
  'outline-none focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0 focus-visible:!outline-none focus-visible:!ring-0 focus-visible:outline-offset-0 focus-visible:!outline-offset-0 focus-visible:ring-offset-0 focus-visible:!ring-offset-0'

const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value

const selectTriggerVariants = cva(
  [
    'flex w-full items-center justify-between gap-2 whitespace-nowrap rounded-lg border border-border-tertiary bg-bg-container text-text placeholder:text-muted-foreground transition-colors disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
    'focus:border-border-secondary focus-visible:border-border-secondary data-[state=open]:border-border-secondary',
  ].join(' '),
  {
    variants: {
      size: {
        sm: 'h-[var(--control-height-sm)] px-[var(--control-padding-x-sm)] py-[var(--control-padding-y-sm)] text-[length:var(--control-font-size-sm)] leading-[var(--control-line-height-sm)]',
        md: 'h-[var(--control-height-md)] px-[var(--control-padding-x-md)] py-[var(--control-padding-y-md)] text-[length:var(--control-font-size-md)] leading-[var(--control-line-height-md)]',
        lg: 'h-[var(--control-height-lg)] px-[var(--control-padding-x-lg)] py-[var(--control-padding-y-lg)] text-[length:var(--control-font-size-lg)] leading-[var(--control-line-height-lg)]',
      },
    },
    defaultVariants: { size: 'md' },
  }
)

export interface SelectTriggerProps
  extends Omit<React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>, 'size'>,
    VariantProps<typeof selectTriggerVariants> {
  triggerIcon?: React.ReactNode
  size?: 'sm' | 'md' | 'lg'
}

const SelectTrigger = React.forwardRef<
  React.ElementRef<typeof SelectPrimitive.Trigger>,
  SelectTriggerProps
>(({ className, children, disabled, triggerIcon, size = 'md', ...props }, ref) => (
  <SelectPrimitive.Trigger
    ref={ref}
    disabled={disabled}
    className={cn(
      selectTriggerVariants({ size }),
      FOCUS_RESET,
      className
    )}
    {...props}
  >
    {children}
    <SelectPrimitive.Icon asChild>
      <span className="pointer-events-none flex shrink-0 text-current [&>svg]:text-current">
        {triggerIcon ?? <ArrowDownSLine className="h-[1em] w-[1em] shrink-0" />}
      </span>
    </SelectPrimitive.Icon>
  </SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName

const SelectScrollUpButton = React.forwardRef<
  React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
  React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton> & { scrollUpIcon?: React.ReactNode }
>(({ className, scrollUpIcon, ...rest }, ref) => (
  <SelectPrimitive.ScrollUpButton
    ref={ref}
    className={cn('flex cursor-default items-center justify-center py-1', FOCUS_RESET, className)}
    {...rest}
  >
    {scrollUpIcon ?? <ArrowUpSLine className="h-[1em] w-[1em]" />}
  </SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName

const SelectScrollDownButton = React.forwardRef<
  React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
  React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton> & { scrollDownIcon?: React.ReactNode }
>(({ className, scrollDownIcon, ...rest }, ref) => (
  <SelectPrimitive.ScrollDownButton
    ref={ref}
    className={cn('flex cursor-default items-center justify-center py-1', FOCUS_RESET, className)}
    {...rest}
  >
    {scrollDownIcon ?? <ArrowDownSLine className="h-[1em] w-[1em]" />}
  </SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName

const SelectContent = React.forwardRef<
  React.ElementRef<typeof SelectPrimitive.Content>,
  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> & {
    /** When provided (e.g. from ThemeStyleProvider), used for portal wrapper */
    dataStyle?: string
    dataTheme?: string
  }
>(({ className, children, position = 'popper', sideOffset = 4, dataStyle, dataTheme, ...props }, ref) => {
  const fromDoc = getThemeFromDocument()
  const dataProps =
    dataStyle !== undefined
      ? { 'data-style': dataStyle, 'data-theme': dataTheme ?? fromDoc['data-theme'] ?? '' }
      : fromDoc
  return (
    <SelectPrimitive.Portal>
      <SelectPrimitive.Content
        ref={ref}
        className={cn(
          'relative z-[60] max-h-96 min-w-32 overflow-hidden rounded-lg border border-border-tertiary bg-bg-container p-1 text-text shadow-lg',
          FOCUS_RESET,
          'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
          className
        )}
        position={position}
        sideOffset={sideOffset}
        {...dataProps}
        {...props}
      >
          <SelectScrollUpButton />
          <SelectPrimitive.Viewport
            className={cn(
              FOCUS_RESET,
              position === 'popper' &&
                'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]'
            )}
          >
            {children}
          </SelectPrimitive.Viewport>
          <SelectScrollDownButton />
        </SelectPrimitive.Content>
    </SelectPrimitive.Portal>
  )
})
SelectContent.displayName = SelectPrimitive.Content.displayName

const SelectLabel = React.forwardRef<
  React.ElementRef<typeof SelectPrimitive.Label>,
  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
  <SelectPrimitive.Label
    ref={ref}
    className={cn('flex h-[var(--select-item-height)] items-center px-[var(--select-item-padding-x)] text-[length:var(--control-font-size-md)] leading-[var(--control-line-height-md)] font-semibold text-text-secondary', className)}
    {...props}
  />
))
SelectLabel.displayName = SelectPrimitive.Label.displayName

const SelectItem = React.forwardRef<
  React.ElementRef<typeof SelectPrimitive.Item>,
  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> & { itemIndicatorIcon?: React.ReactNode }
>(({ className, children, itemIndicatorIcon, ...rest }, ref) => (
  <SelectPrimitive.Item
    ref={ref}
    className={cn(
      'relative flex h-[var(--select-item-height)] w-full min-w-0 cursor-pointer select-none items-center gap-2 rounded-sm pl-[var(--select-item-padding-x)] pr-8 text-[length:var(--control-font-size-md)] leading-[var(--control-line-height-md)] transition-colors',
      FOCUS_RESET,
      'hover:bg-fill-secondary data-[highlighted]:bg-fill-secondary data-[highlighted]:text-text data-[state=checked]:bg-fill-secondary data-[state=checked]:text-text',
      'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
      className
    )}
    {...rest}
  >
    <span className="absolute right-3 flex h-[1em] w-[1em] items-center justify-center">
      <SelectPrimitive.ItemIndicator>
        {itemIndicatorIcon ?? <CheckLine className="h-[1em] w-[1em]" />}
      </SelectPrimitive.ItemIndicator>
    </span>
    <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
  </SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName

const SelectSeparator = React.forwardRef<
  React.ElementRef<typeof SelectPrimitive.Separator>,
  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
  <SelectPrimitive.Separator
    ref={ref}
    className={cn('my-1 mx-1 h-px bg-border-tertiary', className)}
    {...props}
  />
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName

export {
  Select,
  SelectGroup,
  SelectValue,
  SelectTrigger,
  SelectContent,
  SelectLabel,
  SelectItem,
  SelectSeparator,
  SelectScrollUpButton,
  SelectScrollDownButton,
  selectTriggerVariants,
}
