import { FieldInputProps, FormikErrors } from 'formik';
import React, { useState } from 'react';
import {
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import Select2 from '../../components/common/Select2';
import Colors from '../../constants/colors';

interface Option {
  id: string;
  name: string;
  checked?: boolean;
}

interface UserEmail {
  id: string;
  name: string;
  checked?: boolean;
}

interface FormikActionsProps {
  userEmails: UserEmail[];
  value: Record<string, any>;
  field: FieldInputProps<any>;
  setFieldValue: (field: string, value: any) => void;
  mode?: 'date' | 'time' | 'datetime';
  placeholder?: string;
  validationErrors: FormikErrors<any>;
}

const FormikActions: React.FC<FormikActionsProps> = ({
  userEmails,
  value = {},
  field,
  setFieldValue,
  mode = 'date',
  placeholder = 'Enter text',
  validationErrors,
}) => {
  const {
    body = '',
    field_critical_to_safety = '',
    close_immediately = '0',
    field_responsible_person = '',
  } = value;

  const [isDatePickerVisible, setIsDatePickerVisible] = useState(false);
  const [date, setDate] = useState<string>('');

  const criticalToSafetyOptions: Option[] = [
    { id: '1', name: 'Yes' },
    { id: '0', name: 'No' },
  ].map((item) => ({
    ...item,
    checked: item.id === field_critical_to_safety,
  }));

  const closeImmediatelyOptions: Option[] = [
    { id: '0', name: 'No' },
    { id: '1', name: 'Yes' },
  ].map((item) => ({
    ...item,
    checked: item.id === close_immediately,
  }));

  const responsiblePersonOptions: UserEmail[] = userEmails.map((item) => ({
    ...item,
    checked: item.id === field_responsible_person,
  }));

  return (
    <>
      {/* Action Plan */}
      <View style={styles.viewContainer}>
        <Text style={[styles.text, { fontWeight: 'bold' }]}>Action Plan</Text>
        <Text style={styles.text}>
          Corrective Action{' '}
          {validationErrors.body && <Text style={styles.errorTextStyle}>*</Text>}
        </Text>
        <TextInput
          placeholder={placeholder}
          placeholderTextColor={Colors.colorGray}
          value={body}
          onChangeText={(text) =>
            setFieldValue(field.name, { ...value, body: text })
          }
          style={[
            styles.textInput,
            { borderColor: validationErrors.body ? 'red' : '#ECECEC' },
          ]}
        />
      </View>

      {/* Critical To Safety */}
      <View style={styles.viewContainer}>
        <Text style={styles.text}>
          Select Critical To Safety{' '}
          {validationErrors.field_critical_to_safety && (
            <Text style={styles.errorTextStyle}>*</Text>
          )}
        </Text>
        <Select2
          isSelectSingle
          title="Select Critical To Safety"
          colorTheme="#b69b30"
          showSearchBox={false}
        style={StyleSheet.flatten([
    styles.textInput,
    { borderColor: validationErrors.field_critical_to_safety ? 'red' : '#ECECEC' },
  ])}
          popupTitle="Select Critical To Safety"
          cancelButtonText="Cancel"
          selectButtonText="OK"
          buttonTextStyle={{ fontSize: 11 }}
          selectedTitleStyle={{
            color:
              field_critical_to_safety === ''
                ? Colors.colorGray
                : field_critical_to_safety === '0'
                ? 'green'
                : 'red',
          }}
          data={criticalToSafetyOptions}
          onSelect={(data: string[]) => {
            setFieldValue(
              field.name,
              data && data[0]
                ? { ...value, field_critical_to_safety: data[0] }
                : { ...value, field_critical_to_safety: '' }
            );
          }}
          onRemoveItem={() => {}}
        />
      </View>

      {/* Close Immediately */}
      <View style={styles.viewContainer}>
        <Text style={styles.text}>
          Select Close Immediately{' '}
          {validationErrors.close_immediately && (
            <Text style={styles.errorTextStyle}>*</Text>
          )}
        </Text>
        <Select2
          isSelectSingle
          title="Select Close Immediately"
          colorTheme="#b69b30"
          showSearchBox={false}
          popupTitle="Select Close Immediately"
          cancelButtonText="Cancel"
          selectButtonText="OK"
          style={StyleSheet.flatten([
    styles.textInput,
    {
      borderColor: validationErrors.close_immediately ? 'red' : '#ECECEC',
    },
  ])}
          buttonTextStyle={{ fontSize: 11 }}
          
          selectedTitleStyle={{
            color:
              close_immediately === ''
                ? Colors.colorGray
                : close_immediately === '1'
                ? 'green'
                : 'red',
          }}
          data={closeImmediatelyOptions}
          onSelect={(data: string[]) => {
            setFieldValue(
              field.name,
              data && data[0]
                ? { ...value, close_immediately: data[0] }
                : { ...value, close_immediately: '' }
            );
          }}
          onRemoveItem={() => {}}
        />
      </View>

      {/* Responsible Person & Target Date */}
      {close_immediately === '0' && (
        <>
          {/* Responsible Person */}
          <View style={styles.viewContainer}>
            <Text style={styles.text}>
              Select Responsible Person{' '}
              {validationErrors.field_responsible_person && (
                <Text style={styles.errorTextStyle}>*</Text>
              )}
            </Text>
            <Select2
              isSelectSingle
              title="Select Responsible Person"
              colorTheme="#b69b30"
              popupTitle="Select Responsible Person"
              cancelButtonText="Cancel"
              selectButtonText="OK"
              buttonTextStyle={{ fontSize: 11 }}
              style={StyleSheet.flatten([
    styles.textInput,
    { borderColor: validationErrors.field_critical_to_safety ? 'red' : '#ECECEC' },
  ])}
              selectedTitleStyle={{ color: Colors.textColor }}
              data={responsiblePersonOptions}
              onSelect={(data: string[]) => {
                setFieldValue(
                  field.name,
                  data && data[0]
                    ? { ...value, field_responsible_person: data[0] }
                    : { ...value, field_responsible_person: '' }
                );
              }}
              onRemoveItem={() => {}}
            />
          </View>

          {/* Target Date */}
          <TouchableOpacity
            onPress={() => setIsDatePickerVisible(true)}
            style={styles.viewContainer}
          >
            <Text style={styles.text}>
              Target Date{' '}
              {validationErrors.field_target_date && (
                <Text style={styles.errorTextStyle}>*</Text>
              )}
            </Text>
            <TextInput
              editable={false}
              placeholderTextColor={Colors.textColor}
              pointerEvents="none"
              style={[
                styles.textInput,
                {
                  borderColor: validationErrors.field_target_date
                    ? 'red'
                    : '#ECECEC',
                },
              ]}
              placeholder="Target Date"
              value={date}
            />
          </TouchableOpacity>
          <DateTimePickerModal
            isVisible={isDatePickerVisible}
            textColor={Colors.textColor}
            mode={mode}
            minimumDate={new Date()}
            onConfirm={(pickedDate: Date) => {
              setIsDatePickerVisible(false);
              const formatted = `${pickedDate.getFullYear()}-${pickedDate.getMonth() + 1}-${pickedDate.getDate()}`;
              setDate(
                `${pickedDate.getDate()}-${pickedDate.getMonth() + 1}-${pickedDate.getFullYear()}`
              );
              setFieldValue(field.name, { ...value, field_target_date: formatted });
            }}
            onCancel={() => setIsDatePickerVisible(false)}
          />
        </>
      )}
    </>
  );
};

const styles = StyleSheet.create({
  textInput: {
    borderColor: '#ECECEC',
    borderWidth: 1,
    borderRadius: 20,
    paddingLeft: 15,
    marginRight: 1,
    marginTop: 8,
    height: 40,
    fontSize: 12,
    width: '100%',
    backgroundColor: '#ECECEC',
    color: Colors.textColor,
  },
  viewContainer: {
    justifyContent: 'center',
    margin: 4,
  },
  text: {
    marginRight: 10,
    marginLeft: 5,
    color: '#9B9B9B',
  },
  errorTextStyle: {
    fontSize: 15,
    alignSelf: 'center',
    color: 'red',
    marginVertical: 1,
  },
});

export { FormikActions };
