import { ComponentProps, forwardRef } from 'react';
import { cva, VariantProps } from 'class-variance-authority';
import * as SelectPrimitives from '@radix-ui/react-select';

import { Icon } from '../iconography';

const selectTriggerStyles = cva('c-select-trigger', {
  variants: {
    size: {
      xs: 'c-select-trigger-xs',
      sm: 'c-select-trigger-sm',
      md: 'c-select-trigger-md',
      lg: 'c-select-trigger-lg',
    },
  },
  defaultVariants: {
    size: 'sm',
  },
});

export type SelectRef = HTMLButtonElement;
export type SelectProps = ComponentProps<typeof SelectPrimitives.Root> &
  VariantProps<typeof selectTriggerStyles> & {
    triggerClassName?: string;
    disabled?: boolean;
    id?: string;
    placeholder?: string;
  };

export const SelectContainer = forwardRef<SelectRef, SelectProps>(
  ({ children, id, placeholder, disabled, size, triggerClassName, ...delegated }, ref) => {
    return (
      <SelectPrimitives.Root {...delegated}>
        <SelectPrimitives.Trigger
          ref={ref}
          className={selectTriggerStyles({ size, className: triggerClassName })}
          disabled={disabled}
          id={id}
        >
          <SelectPrimitives.Value placeholder={<span className="c-select-value">{placeholder ?? 'Select...'}</span>} />
          <Icon.Arrow />
        </SelectPrimitives.Trigger>

        <SelectPrimitives.Portal>
          <SelectPrimitives.Content className="c-select-content">
            <SelectPrimitives.ScrollUpButton />
            <SelectPrimitives.Viewport className="c-select-viewport">{children}</SelectPrimitives.Viewport>
            <SelectPrimitives.ScrollDownButton />
          </SelectPrimitives.Content>
        </SelectPrimitives.Portal>
      </SelectPrimitives.Root>
    );
  },
);

SelectContainer.displayName = 'Select';
