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

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

interface Witness {
  involvedPersonName: string;
  phoneNumber: string;
  address: string;
  involvedUserRole: string[];
  user: string[];
  Nationality: string[];
}

interface WitnessesProps {
  name: string;
  value: { witnesses: Witness[] };
  index: number;
  setFieldValue: (field: string, value: any) => void;
  involvedUserRolesOptions: Option[];
  usersOptions: Option[];
  nationalityOptions: Option[];
  contractor_emails: Option[];
  arrayHelpers: { remove: (index: number) => void };
}

const Witnesses: React.FC<WitnessesProps> = ({
  name,
  value,
  index,
  setFieldValue,
  involvedUserRolesOptions,
  usersOptions,
  nationalityOptions,
  contractor_emails,
  arrayHelpers,
}) => {
  // Normalize options to string id for Select2
  const normalizeOptions = (
    options: (Option | { id: string | number; name: string })[]
  ): Option[] => options.map((o) => ({ id: o.id.toString(), name: o.name }));

  const [usersOptionsCopy, setUsersOptionsCopy] = useState<Option[]>([]);
  const [contractorEmailsCopy, setContractorEmailsCopy] = useState<Option[]>([]);
  const [nationalityOptionsCopy, setNationalityOptionsCopy] = useState<Option[]>([]);
  const [involvedUserRolesOptionsCopy, setInvolvedUserRolesOptionsCopy] = useState<Option[]>([]);
  const [personRoleType, setPersonRoleType] = useState('');

  useEffect(() => {
    setInvolvedUserRolesOptionsCopy(normalizeOptions(involvedUserRolesOptions));
    setContractorEmailsCopy(normalizeOptions(contractor_emails));
    setUsersOptionsCopy(normalizeOptions(usersOptions));
    setNationalityOptionsCopy(normalizeOptions(nationalityOptions));
  }, [involvedUserRolesOptions, usersOptions, nationalityOptions, contractor_emails]);

  const { witnesses } = value;
  const thisWitness = witnesses[index];

  const handleRoleSelect = useCallback(
    (data: string[]) => {
      const result = involvedUserRolesOptionsCopy.find((item) => item.id === data[0]);
      setPersonRoleType(result?.name || '');
      
      const updatedWitness = { ...thisWitness, involvedUserRole: data };
      const updatedWitnesses = [...witnesses];
      updatedWitnesses[index] = updatedWitness;
      setFieldValue(name, updatedWitnesses);
    },
    [involvedUserRolesOptionsCopy, thisWitness, witnesses, index, name, setFieldValue]
  );

  const handleSelect = useCallback(
    (fieldKey: keyof Witness, selected: string[]) => {
      const updatedWitness = { ...thisWitness, [fieldKey]: selected };
      const updatedWitnesses = [...witnesses];
      updatedWitnesses[index] = updatedWitness;
      setFieldValue(name, updatedWitnesses);
    },
    [thisWitness, witnesses, index, name, setFieldValue]
  );

  const handleTextChange = useCallback(
    (fieldKey: 'involvedPersonName' | 'phoneNumber' | 'address', text: string) => {
      const updatedWitness = { ...thisWitness, [fieldKey]: text };
      const updatedWitnesses = [...witnesses];
      updatedWitnesses[index] = updatedWitness;
      setFieldValue(name, updatedWitnesses);
    },
    [thisWitness, witnesses, index, name, setFieldValue]
  );

  return (
    <View key={index} style={styles.itemContainer}>
      <View style={styles.headerRow}>
        <Text style={styles.headerText}>Witness #{index + 1}</Text>
        {index > 0 && (
          <Text style={styles.removeText} onPress={() => arrayHelpers.remove(index)}>
            Remove
          </Text>
        )}
      </View>

      <Select2
        isSelectSingle
        style={CommonStyles.incidentField as ViewStyle}
        title="Select Person Role Type"
        colorTheme="#b69b30"
        popupTitle="Select Person Role Type"
        cancelButtonText="Cancel"
        selectButtonText="OK"
        selectedTitleStyle={{ color: Colors.selectedColorSelect2 }}
        selectedPlaceholderTextColor={{ color: Colors.colorPlaceholder }}
        searchPlaceHolderText="Search..."
        listEmptyTitle="Options Empty"
        data={involvedUserRolesOptionsCopy}
        onSelect={handleRoleSelect}
        onRemoveItem={() => {}}
      />

      {personRoleType !== '' && (
        <>
          {personRoleType === '' || personRoleType === 'Staff' || personRoleType === 'Contractor' ? (
            <Select2
              isSelectSingle
              style={CommonStyles.incidentField as ViewStyle}
              title="User Email"
              colorTheme="#b69b30"
              popupTitle="Select User"
              cancelButtonText="Cancel"
              selectButtonText="OK"
              listEmptyTitle="Options Empty"
              searchPlaceHolderText="Search..."
              selectedTitleStyle={{ color: Colors.selectedColorSelect2 }}
              selectedPlaceholderTextColor={{ color: Colors.colorPlaceholder }}
              data={personRoleType === 'Contractor' ? contractorEmailsCopy : usersOptionsCopy}
              onSelect={(data: string[]) => handleSelect('user', data)}
              onRemoveItem={() => {}}
            />
          ) : (
            <>
              <TextInput
                style={CommonStyles.incidentField}
                placeholder="Involved Person Name"
                placeholderTextColor={Colors.colorPlaceholder}
                onChangeText={(text: string) => handleTextChange('involvedPersonName', text)}
                value={thisWitness.involvedPersonName}
              />

              <TextInput
                keyboardType="numeric"
                style={CommonStyles.incidentField}
                placeholder="Phone Number"
                placeholderTextColor={Colors.colorPlaceholder}
                onChangeText={(text: string) => handleTextChange('phoneNumber', text)}
                value={thisWitness.phoneNumber}
              />

              <Select2
                isSelectSingle
                style={CommonStyles.incidentField as ViewStyle}
                title="Nationality"
                colorTheme="#b69b30"
                popupTitle="Nationality"
                cancelButtonText="Cancel"
                selectButtonText="OK"
                listEmptyTitle="Options Empty"
                searchPlaceHolderText="Search..."
                selectedTitleStyle={{ color: Colors.selectedColorSelect2 }}
                selectedPlaceholderTextColor={{ color: Colors.colorPlaceholder }}
                data={nationalityOptionsCopy}
                onSelect={(data: string[]) => handleSelect('Nationality', data)}
                onRemoveItem={() => {}}
              />

              <TextInput
                style={[CommonStyles.incidentField, styles.textArea]}
                placeholder="Address"
                placeholderTextColor={Colors.colorPlaceholder}
                onChangeText={(text: string) => handleTextChange('address', text)}
                value={thisWitness.address}
                multiline
                numberOfLines={5}
                textAlignVertical="top"
              />
            </>
          )}
        </>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  itemContainer: {
    borderColor: '#ddd',
    borderRadius: 5,
    padding: 8,
    paddingVertical: 12,
    marginVertical: 5,
    backgroundColor: Colors.appBackgroundColor,
  },
  headerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    marginHorizontal: 5,
  },
  headerText: {
    color: '#606060',
    fontSize: 14,
    margin: 4,
    flex: 2,
  },
  removeText: {
    marginLeft: 5,
    color: '#C1AD84',
  },
  textArea: {
    minHeight: 100,
    paddingTop: 10,
  },
});

export { Witnesses };
