import React, { useEffect, useState } from 'react';
import { StyleSheet, ViewStyle } from 'react-native';
import Select2 from '../../components/common/Select2';
import Colors from '../../constants/colors';
import CommonStyles from '../../constants/CommonStyles';

interface SelectOption {
  id: string | number;
  name: string;
}

interface FormikSelectProps {
  field: { name: string; value?: any };
  setFieldValue: (field: string, value: any) => void;
  data: SelectOption[];
  title?: string;
  colorTheme?: string;
  popupTitle?: string;
  cancelButtonText?: string;
  selectButtonText?: string;
  searchPlaceHolderText?: string;
  isSelectSingle?: boolean;
  marginTop?: number;
}

const FormikSelect: React.FC<FormikSelectProps> = ({
  field,
  setFieldValue,
  data,
  title = 'Select an option',
  colorTheme = Colors.primaryColor,
  popupTitle = 'Select',
  cancelButtonText = 'Cancel',
  selectButtonText = 'Select',
  searchPlaceHolderText = 'Search...',
  isSelectSingle = true,
  marginTop = 12,
}) => {
  const [dataCopy, setDataCopy] = useState<{ id: string; name: string }[]>([]);

  useEffect(() => {
    const sortedData = [...data]
      .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
      .map(item => ({ ...item, id: String(item.id) })); // Convert id to string
    setDataCopy(sortedData);
  }, [data]);

  // Combine styles into a single object for Select2
  const selectStyle: ViewStyle = {
    ...CommonStyles.textInput,
    marginTop,
  };

  return (
    
    <Select2
      listEmptyTitle="No options available"
      isSelectSingle={isSelectSingle}
      title={title}
      colorTheme={colorTheme}
      popupTitle={popupTitle}
      cancelButtonText={cancelButtonText}
      selectButtonText={selectButtonText}
      searchPlaceHolderText={searchPlaceHolderText}
      selectedTitleStyle={{ color: Colors.selectedColorSelect2 }}
      selectedPlaceholderTextColor={{ color: Colors.colorPlaceholder }}
      data={dataCopy}
      onSelect={(selected: any) => setFieldValue(field.name, selected)}
      onRemoveItem={(removed: any) => setFieldValue(field.name, removed)}
      style={selectStyle}
    />
  );
};

const styles = StyleSheet.create({
  item: {
    marginVertical: 10,
    paddingLeft: 15,
  },
});

export { FormikSelect };
