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; // must be string for Select2
  name: string;
  checked?: boolean;
}

interface InvolvedPerson {
  involvedPersonName: string;
  phoneNumber: string;
  address: string;
  involvedUserRole: string[]; // always string[]
  user: string[];
  Nationality: string[];
}

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

const InvolvedPeople: React.FC<InvolvedPeopleProps> = ({
  name,
  value,
  index,
  setFieldValue,
  involvedUserRolesOptions,
  usersOptions,
  nationalityOptions,
  contractor_emails,
  arrayHelpers,
}) => {
  const { involvedPeople } = value;
  const person = involvedPeople[index];

  // 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 [userRoleOptions, setUserRoleOptions] = useState<Option[]>([]);
  const [usersOptionCopy, setUsersOptionCopy] = useState<Option[]>([]);
  const [nationalityOptionsCopy, setNationalityOptionsCopy] = useState<Option[]>([]);
  const [contractorEmailsCopy, setContractorEmailsCopy] = useState<Option[]>([]);

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

  const personRoleType = userRoleOptions.find(
    (r) => r.id === person.involvedUserRole[0]
  )?.name || '';

  const handleSelect = useCallback(
    (fieldKey: keyof InvolvedPerson, selected: string[]) => {
      // Create a new person object with the updated field
      const updatedPerson = { ...person, [fieldKey]: selected };
      const updatedPeople = [...involvedPeople];
      updatedPeople[index] = updatedPerson;
      setFieldValue(name, updatedPeople);
    },
    [involvedPeople, name, person, setFieldValue, index]
  );

  const handleTextChange = useCallback(
    (fieldKey: 'involvedPersonName' | 'phoneNumber' | 'address', text: string) => {
      // Create a new person object with the updated field
      const updatedPerson = { ...person, [fieldKey]: text };
      const updatedPeople = [...involvedPeople];
      updatedPeople[index] = updatedPerson;
      setFieldValue(name, updatedPeople);
    },
    [involvedPeople, name, person, setFieldValue, index]
  );

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

      {/* Role Select */}
      <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={userRoleOptions}
        onSelect={(data: string[]) => handleSelect('involvedUserRole', data)}
        onRemoveItem={() => {}}
      />

      {(personRoleType === '' || personRoleType === 'Staff' || personRoleType === 'Contractor') && (
        <>
          {(personRoleType === 'Staff' || personRoleType === 'Contractor') ? (
            <Select2
              isSelectSingle
              style={CommonStyles.incidentField as ViewStyle}
              title="User Email"
              colorTheme="#b69b30"
              popupTitle="Select User"
              cancelButtonText="Cancel"
              selectButtonText="OK"
              selectedTitleStyle={{ color: Colors.selectedColorSelect2 }}
              selectedPlaceholderTextColor={{ color: Colors.colorPlaceholder }}
              searchPlaceHolderText="Search..."
              listEmptyTitle="Options Empty"
              data={personRoleType === 'Contractor' ? contractorEmailsCopy : usersOptionCopy}
              onSelect={(data: string[]) => handleSelect('user', data)}
              onRemoveItem={() => {}}
            />
          ) : (
            <>
              <TextInput
                style={CommonStyles.incidentField}
                placeholder="Involved Person Name"
                placeholderTextColor={Colors.colorPlaceholder}
                value={person.involvedPersonName}
                onChangeText={(text: string) => handleTextChange('involvedPersonName', text)}
              />
              <TextInput
                style={CommonStyles.incidentField}
                placeholder="Phone Number"
                keyboardType="numeric"
                placeholderTextColor={Colors.colorPlaceholder}
                value={person.phoneNumber}
                onChangeText={(text: string) => handleTextChange('phoneNumber', text)}
              />
              <Select2
                isSelectSingle
                style={CommonStyles.incidentField as ViewStyle}
                title="Nationality"
                colorTheme="#b69b30"
                popupTitle="Nationality"
                cancelButtonText="Cancel"
                selectButtonText="OK"
                selectedTitleStyle={{ color: Colors.selectedColorSelect2 }}
                selectedPlaceholderTextColor={{ color: Colors.colorPlaceholder }}
                searchPlaceHolderText="Search..."
                listEmptyTitle="Options Empty"
                data={nationalityOptionsCopy}
                onSelect={(data: string[]) => handleSelect('Nationality', data)}
                onRemoveItem={() => {}}
              />
              <TextInput
                style={[CommonStyles.incidentField, styles.textArea]}
                placeholder="Address"
                placeholderTextColor={Colors.colorPlaceholder}
                value={person.address}
                onChangeText={(text: string) => handleTextChange('address', text)}
                multiline
                numberOfLines={4}
                textAlignVertical="top"
              />
            </>
          )}
        </>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  itemContainer: {
    borderRadius: 5,
    backgroundColor: Colors.appBackgroundColor,
    borderWidth: 1,
    padding: 8,
    marginVertical: 5,
    borderColor: 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: 80,
    paddingTop: 10,
  },
});

export { InvolvedPeople };
