import { useCallback, useContext } from "react";
import { AppContext, ModalContainer } from "../../../../../utils";
import { DeviceLivePreview } from "../../..";
import { FlatList, ScrollView } from "react-native";
import Card from "../../../../../Components/Card";
import MyDropdown from "../../../../../Components/Dropdown";
import { useTranslation } from "react-i18next";
import {
  EditActionAdjustmentsContent,
  EditActionAnimationsCardContent,
  RenderHeaderRight,
} from "..";
import { MyPickerModalListItem } from "../../../../../Components/Modal";
import { useFocusEffect } from "@react-navigation/native";

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

  const { action, deviceFirmwareVersion } = route.params;

  const supportedDeviceMotorModes =
    appContext.deviceFirmwareModes.motorModes.filter((motorMode) =>
      motorMode.supportedFirmwareVersions.includes(deviceFirmwareVersion)
    );

  // check if action exists before accessing modeId as the action could be deleted by the user
  const selectedMotorMode = supportedDeviceMotorModes.find(
    (s) => s.id === (action && action.modeId)
  );

  useFocusEffect(
    useCallback(() => {
      navigation.setOptions({
        headerRight: () => (
          <RenderHeaderRight
            navigation={navigation}
            action={action}
            appContext={appContext}
            t={t}
          />
        ),
      });
    }, [])
  );

  if (!action) return null;

  return (
    <ModalContainer withoutPadding>
      <DeviceLivePreview />

      <ScrollView>
        <Card>
          <MyDropdown
            style={{ marginBottom: 2 }}
            label={t(
              "screens.device.scenes.editActions.modalMotorEditAction.dropdownMotorModeSelection.label"
            )}
            selectedItemLabel={
              action.modeId === ""
                ? t(
                    "screens.device.scenes.editActions.modalMotorEditAction.dropdownMotorModeSelection.noMotorModeSelected"
                  )
                : selectedMotorMode.name[appContext.appLanguage]
            }
            onPress={() =>
              navigation.navigate("modalMotorEditActionMotorModeSelection", {
                supportedDeviceMotorModes: supportedDeviceMotorModes,
                action: action,
              })
            }
          />

          {action.modeId !== "" && (
            <EditActionAdjustmentsContent
              action={action}
              adjustmentType="mode"
              adjustments={selectedMotorMode.adjustments}
            />
          )}
        </Card>

        <EditActionAnimationsCardContent
          disabled={action.modeId === ""}
          navigation={navigation}
          deviceFirmwareVersion={deviceFirmwareVersion}
          action={action}
        />
      </ScrollView>
    </ModalContainer>
  );
}

export function MotorEditActionMotorModeSelectionModalContent({
  navigation,
  route,
}) {
  const appContext = useContext(AppContext);

  const { action, supportedDeviceMotorModes } = route.params;

  return (
    <ModalContainer withoutPadding>
      <FlatList
        data={supportedDeviceMotorModes}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <MyPickerModalListItem
            itemName={item.name[appContext.appLanguage]}
            itemSelected={action.modeId === item.id}
            onPress={() => {
              appContext.setDeviceSceneActions((arr) => {
                const newArr = [...arr];

                const actionIndex = newArr.findIndex(
                  (a) => a.actionId === action.actionId
                );

                if (actionIndex !== -1) {
                  newArr[actionIndex].modeId = item.id;

                  /* const lightModeDefaultColors =
                    appContext.deviceFirmwareModes.lightModes.find(
                      (lM) => lM.id === item.id
                    );

                  if (lightModeDefaultColors !== undefined) {
                    if (lightModeDefaultColors.defaults !== undefined) {
                      newArr[actionIndex].modeAdjustments.colors =
                        appContext.deviceFirmwareModes.lightModes.find(
                          (lM) => lM.id === item.id
                        ).defaults;
                    }
                  }*/

                  item.adjustments.forEach(
                    (adjustment) =>
                      (newArr[actionIndex].modeAdjustments[
                        adjustment.variableName
                      ] = adjustment.defaultValue)
                  );
                }

                return newArr;
              });

              navigation.goBack();
            }}
          />
        )}
      />
    </ModalContainer>
  );
}
