import React from 'react';
import {
  Select as ChakraSelect,
  FormControl,
  FormLabel,
  FormErrorMessage,
  FormHelperText,
  useColorModeValue,
} from '@chakra-ui/react';
import { ChevronDownIcon } from '@chakra-ui/icons';

export interface SelectOption {
  /**
   * Value of the option
   */
  value: string;

  /**
   * Label of the option
   */
  label: string;

  /**
   * Whether the option is disabled
   */
  isDisabled?: boolean;

  /**
   * Optional group for the option
   */
  group?: string;
}

export interface SelectProps {
  /**
   * Label for the select
   */
  label?: string;

  /**
   * Error message to display
   */
  error?: string;

  /**
   * Helper text to display below the select
   */
  helperText?: string;

  /**
   * Size of the select
   */
  size?: 'sm' | 'md' | 'lg';

  /**
   * Whether the select is required
   */
  isRequired?: boolean;

  /**
   * Options for the select
   */
  options: SelectOption[];

  /**
   * Placeholder text for the select
   */
  placeholder?: string;

  /**
   * Whether to show a clear button
   */
  isClearable?: boolean;

  /**
   * Whether to show a search input
   */
  isSearchable?: boolean;

  /**
   * Custom icon for the select
   */
  icon?: React.ReactElement;

  /**
   * ID for the select input
   */
  id?: string;
}

/**
 * Select component using Chakra UI's Select with BFUI theme customizations
 */
export const Select: React.FC<SelectProps> = ({
  label,
  error,
  helperText,
  size = 'md',
  isRequired = false,
  options,
  placeholder = 'Select an option',
  isClearable = false,
  isSearchable = false,
  icon = <ChevronDownIcon />,
  id,
  ...rest
}) => {
  const inputId = id || label?.toLowerCase().replace(/\s+/g, '-');
  const bg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');

  // Group options if any have group property
  const hasGroups = options.some(option => option.group);
  const groupedOptions = hasGroups
    ? options.reduce((acc, option) => {
        const group = option.group || 'Other';
        if (!acc[group]) {
          acc[group] = [];
        }
        (acc[group] as SelectOption[]).push(option);
        return acc;
      }, {} as Record<string, SelectOption[]>)
    : null;

  return (
    <FormControl isInvalid={!!error} isRequired={isRequired}>
      {label && <FormLabel htmlFor={inputId}>{label}</FormLabel>}
      <ChakraSelect
        id={inputId}
        size={size}
        bg={bg}
        borderColor={borderColor}
        placeholder={placeholder}
        icon={icon}
        _hover={{
          borderColor: useColorModeValue('gray.300', 'gray.500'),
        }}
        _focus={{
          borderColor: 'blue.500',
          boxShadow: 'outline',
        }}
        {...rest}
      >
        {groupedOptions
          ? Object.entries(groupedOptions).map(([group, groupOptions]) => (
              <optgroup key={group} label={group}>
                {groupOptions.map(option => (
                  <option key={option.value} value={option.value} disabled={!!option.isDisabled}>
                    {option.label}
                  </option>
                ))}
              </optgroup>
            ))
          : options.map(option => (
              <option key={option.value} value={option.value} disabled={!!option.isDisabled}>
                {option.label}
              </option>
            ))}
      </ChakraSelect>
      {error ? (
        <FormErrorMessage>{error}</FormErrorMessage>
      ) : helperText ? (
        <FormHelperText>{helperText}</FormHelperText>
      ) : null}
    </FormControl>
  );
};

export default Select;
