import { forwardRef } from 'react';
import { SelectProps } from '@theme/components/types';
import clsx from 'clsx';
import { Icon } from './icon';
import { twMerge } from 'tailwind-merge';

interface ExtendedSelectProps extends SelectProps {
  /** Custom SVG icon content */
  customIcon?: string;
}

const Select = forwardRef<HTMLSelectElement, ExtendedSelectProps>(
  (props, ref) => {
    const {
      className,
      options,
      borderless = false,
      icon,
      iconSize,
      customIcon,
      error,
      label,
      required = false,
      labelClassName,
      ...rest
    } = props;

    // Check if customIcon is SVG content
    const hasCustomSvgIcon =
      customIcon &&
      typeof customIcon === 'string' &&
      customIcon.includes('<svg');

    return (
      <label
        className={twMerge(
          clsx('flex flex-col relative text-xs text-gray-800', {
            'pl-7': icon || hasCustomSvgIcon
          }),
          labelClassName
        )}
      >
        {hasCustomSvgIcon ? (
          <div
            className="absolute left-0 top-1/2 transform -translate-y-1/2 flex items-center justify-center"
            style={{ width: iconSize ?? 20, height: iconSize ?? 20 }}
            dangerouslySetInnerHTML={{ __html: customIcon }}
          />
        ) : icon ? (
          <Icon
            name={icon}
            size={iconSize ?? 20}
            className="absolute left-0 top-1/2 transform -translate-y-1/2"
          />
        ) : null}

        {label && (
          <span className={twMerge('mb-1', labelClassName)}>
            {label} {required && <span className="text-secondary">*</span>}
          </span>
        )}
        <div className="relative">
          <select
            {...rest}
            ref={ref}
            className={twMerge(
              clsx(
                'cursor-pointer truncate h-10 w-40 px-2.5 shrink-0 outline-none',
                !borderless &&
                  'border border-gray-200 transition-all duration-150 hover:border-primary focus:border-primary',
                'appearance-none bg-transparent'
              ),
              className
            )}
          >
            {options?.map((option) => (
              <option
                key={option.value}
                value={option.value}
                className={option.class}
              >
                {option.label}
              </option>
            ))}
          </select>
          <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
            <svg className="h-4 w-4 fill-current" viewBox="0 0 20 20">
              <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" />
            </svg>
          </div>
        </div>
        {error && (
          <span className="mt-1 text-sm text-error">{error.message}</span>
        )}
      </label>
    );
  }
);

Select.displayName = 'Select';

export { Select };
