import React, { memo, useCallback } from 'react';
import { FlatList, StyleSheet, Text, TouchableOpacity, ViewStyle } from 'react-native';

interface RadioOption {
  label: string;
  value: string | number;
  color?: string;
}

interface FormikQuestionAnswersProps {
  field: { name: string; value?: string | number };
  setFieldValue: (field: string, value: any) => void;
  radioButtonOptions: RadioOption[];
  style?: ViewStyle;
  value?: string | number;
}

const FormikQuestionAnswers: React.FC<FormikQuestionAnswersProps> = memo(
  ({ field, setFieldValue, radioButtonOptions, style, value }) => {
    const selectedIndex = radioButtonOptions.findIndex((item) => item.value === value);

    const setFieldValues = useCallback(
      (val: string | number) => {
        setFieldValue(field.name, val);
      },
      [field.name, setFieldValue]
    );

    const renderAnswers = ({ item }: { item: RadioOption }) => (
      <TouchableOpacity
        style={[
          styles.optionButton,
          { backgroundColor: item.color || '#ccc' },
          value === item.value && styles.selectedOption,
        ]}
        onPress={() => setFieldValues(item.value)}
      >
        <Text style={styles.optionLabel}>{item.label}</Text>
      </TouchableOpacity>
    );

    return (
      <FlatList
        style={style}
        keyExtractor={(item) => `${item.value}`}
        data={radioButtonOptions}
        renderItem={renderAnswers}
        horizontal
        showsHorizontalScrollIndicator={false}
      />
    );
  },
  (prevProps, nextProps) => prevProps.value === nextProps.value
);

const styles = StyleSheet.create({
  optionButton: {
    height: 40,
    width: 40,
    marginHorizontal: 4,
    borderRadius: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  selectedOption: {
    borderWidth: 2,
    borderColor: '#000',
  },
  optionLabel: {
    color: '#fff',
    fontSize: 12,
    textAlign: 'center',
  },
});

export { FormikQuestionAnswers };
