'use client'
import * as React from 'react'
import * as SelectPrimitive from '@radix-ui/react-select'
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react'
import { cn } from '@/lib/utils/cn'
import { ErrorIcon } from '../icons/form-icon'

export interface CustomSelectProps {
  options: { value: string; label: string }[]
  placeholder: string
  label?: string
  containerClass?: string
  labelClass?: string
  triggerClassName?: string
  className?: string
  hasError?: boolean
  errorMessage?: string
  value?: string
  onValueChange?: (value: string) => void
  iconLeft?: React.ReactNode
  iconRight?: React.ReactNode
  hideDefaultIcon?: boolean
}

export function CustomSelect({
  options,
  placeholder,
  label,
  containerClass,
  labelClass,
  triggerClassName,
  className,
  hasError = false,
  errorMessage,
  value,
  onValueChange,
  iconLeft,
  iconRight,
  hideDefaultIcon = false,
}: CustomSelectProps) {
  const id = React.useId()

  return (
    <div className={cn(containerClass)}>
      {label && (
        <label
          htmlFor={id}
          className={cn(
            'uppercase block text-grey-50 caption-medium-medium pointer-events-none pb-2',
            labelClass,
          )}
        >
          {label}
        </label>
      )}

      <SelectPrimitive.Root value={value} onValueChange={onValueChange}>
        <div className="relative flex items-center">
          <SelectPrimitive.Trigger
            id={id}
            data-slot="select-trigger"
            className={cn(
              'group font-b2-regular placeholder:text-grey-200 text-base-white',
              'flex h-12 w-full min-w-0 rounded-md border px-4 py-3 text-base outline-none',
              'bg-neutral-700 focus:bg-neutral-700',
              'shadow-xs transition-[background-color,box-shadow]',
              'disabled:cursor-not-allowed disabled:opacity-50',
              'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
              'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
              hasError ? 'border-func-red-main dark:border-red' : 'border-[#FCFCFC33]',
              triggerClassName,
            )}
          >
            {iconLeft && <span className="mr-2 flex items-center">{iconLeft}</span>}

            <SelectPrimitive.Value placeholder={placeholder} />

            {!hideDefaultIcon && !iconRight && (
              <span className="absolute right-4 top-1/2 -translate-y-1/2 z-10 pointer-events-none">
                <SelectPrimitive.Icon asChild>
                  <ChevronDownIcon width={20} className="stroke-grey-200" />
                </SelectPrimitive.Icon>
              </span>
            )}
            {iconRight && (
              <span className="absolute right-0 top-1/2 -translate-y-1/2 z-10 pointer-events-none">
                {iconRight}
              </span>
            )}
          </SelectPrimitive.Trigger>

          <SelectPrimitive.Portal>
          <SelectPrimitive.Content
            position="popper"
            side="bottom"
            align="start"
            sideOffset={5}
            data-slot="select-content"
            avoidCollisions={false}
            style={{ width: 'var(--radix-select-trigger-width)' }}
            className={cn(
              'bg-neutral-700 text-base-white rounded-md border border-[#FCFCFC33] shadow-md overflow-auto',
              'animate-in zoom-in-95',
              'z-50',
            )}
          >
            <SelectPrimitive.ScrollUpButton className="flex items-center justify-center py-1">
              <ChevronUpIcon width={20} className="stroke-grey-200" />
            </SelectPrimitive.ScrollUpButton>

            {/* Ограниченный контейнер со скроллом */}
            <div className="max-h-[200px] overflow-y-auto">
              <SelectPrimitive.Viewport>
                {options.map((option, idx) => (
                  <SelectPrimitive.Item
                    key={idx}
                    value={option.value}
                    className="relative flex w-full cursor-default items-center gap-2 border-b border-neutral-600 py-3 pl-4 pr-8 text-sm outline-none select-none last:border-b-0 hover:bg-neutral-500 focus:bg-neutral-500 data-[state=checked]:bg-base-white data-[state=checked]:text-base-black"
                  >
                    <span className="absolute right-2 flex items-center justify-center">
                      <SelectPrimitive.ItemIndicator>
                        <CheckIcon className="size-4" />
                      </SelectPrimitive.ItemIndicator>
                    </span>
                    <SelectPrimitive.ItemText>{option.label}</SelectPrimitive.ItemText>
                  </SelectPrimitive.Item>
                ))}
              </SelectPrimitive.Viewport>
            </div>

            <SelectPrimitive.ScrollDownButton className="flex items-center justify-center py-1">
              <ChevronDownIcon width={20} className="stroke-grey-200" />
            </SelectPrimitive.ScrollDownButton>
          </SelectPrimitive.Content>
          </SelectPrimitive.Portal>
        </div>
      </SelectPrimitive.Root>
      {hasError && errorMessage && (
        <div className="flex items-center justify-start mt-2">
          <ErrorIcon width={20} height={20} className="text-func-red-main flex-shrink-0" />
          <p className={cn('label-medium-regular ml-1 text-func-red-main')}>{errorMessage}</p>
        </div>
      )}
    </div>
  )
}
