import { useContext } from "react";
import {
  AppContext,
  AppSelectedUserDevice,
  Constants,
} from "../../../../utils";
import { useTranslation } from "react-i18next";
import { MyTextInputModalContent } from "../../../../Components/Modal";

export default function SettingsChangeDeviceDisplayNameModalContent({
  navigation,
  route,
}) {
  const appContext = useContext(AppContext);
  const { t } = useTranslation();

  const updateDeviceDisplayName = (newDeviceDisplayName) => {
    appContext.setDevices((arr) => {
      let newArr = [...arr];

      const foundIndex = newArr.findIndex((d) => d.id === route.params.id);

      if (foundIndex !== -1) {
        newArr[foundIndex].displayName = newDeviceDisplayName;

        AppSelectedUserDevice.current.routeName = newDeviceDisplayName;

        // this timeout is needed as the app will navigate to the first device in appContext.devices without to navigate back to the updated device
        setTimeout(() => navigation.navigate(newDeviceDisplayName), 50);
      }

      return newArr;
    });
  };

  return (
    <MyTextInputModalContent
      navigation={navigation}
      textMaxLength={Constants.globals.max_device_name_length}
      defaultValue={route.params.displayName}
      onCheckIconPress={(newDeviceDisplayName) => {
        updateDeviceDisplayName(newDeviceDisplayName);
      }}
      textOnSubmitEditing={(e) => updateDeviceDisplayName(e.nativeEvent.text)}
      textInputTitle={t(
        "screens.device.settings.modalSettingsChangeDeviceDisplayName.textTitle"
      )}
      textInputDescription={t(
        "screens.device.settings.modalSettingsChangeDeviceDisplayName.textDescription"
      )}
    />
  );
}
