import React, { memo, useCallback } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import Colors from '../../constants/colors';

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

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

const FormikRadioButtons: React.FC<FormikRadioButtonsProps> = memo(
  ({ field, setFieldValue, radioButtonOptions, value, label }) => {
    const selectedValue = value ?? field.value;

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

    return (
      <View style={styles.container}>
        {label && <Text style={styles.label}>{label}</Text>}
        <View style={styles.radioGroup}>
          {radioButtonOptions.map((option) => {
            const isSelected = option.value === selectedValue;
            return (
              <Pressable
                key={option.value}
                style={styles.radioButtonContainer}
                onPress={() => onSelect(option.value)}
              >
                <View
                  style={[
                    styles.radioButtonOuter,
                    { borderColor: Colors.radioButtonColor },
                  ]}
                >
                  {isSelected && (
                    <View
                      style={[
                        styles.radioButtonInner,
                        { backgroundColor: Colors.radioButtonColor },
                      ]}
                    />
                  )}
                </View>
                <Text
                  style={[
                    styles.radioLabel,
                    { color: isSelected ? Colors.radioButtonColor : '#000' },
                  ]}
                >
                  {option.label}
                </Text>
              </Pressable>
            );
          })}
        </View>
      </View>
    );
  },
  (prevProps, nextProps) => prevProps.value === nextProps.value
);

const styles = StyleSheet.create({
  container: {
    flexDirection: 'column',
    marginVertical: 4,
  },
  label: {
    marginBottom: 4,
    color: Colors.radioButtonColor,
    fontSize: 14,
  },
  radioGroup: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  radioButtonContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 12,
    marginBottom: 4,
  },
  radioButtonOuter: {
    width: 18,
    height: 18,
    borderRadius: 9,
    borderWidth: 2,
    justifyContent: 'center',
    alignItems: 'center',
  },
  radioButtonInner: {
    width: 10,
    height: 10,
    borderRadius: 5,
  },
  radioLabel: {
    marginLeft: 4,
    fontSize: 14,
  },
});

export { FormikRadioButtons };
