import { FlatList, Text, View } from "react-native";
import {
  AppContext,
  AppStyles,
  IsPlatformIos,
  ModalContainer,
} from "../../../../utils";
import { useCallback, useContext, useState } from "react";
import { useTranslation } from "react-i18next";
import Card from "../../../../Components/Card";
import MyDropdown from "../../../../Components/Dropdown";
import MyResult from "../../../../Components/Result";
import {
  MyDotsModal,
  MyPickerModalListItem,
} from "../../../../Components/Modal";
import MySlider from "../../../../Components/Slider";
import MyIcon from "../../../../Components/Icon";
import { useFocusEffect } from "@react-navigation/native";

export function EditActionAnimationsCardContent({
  disabled,
  navigation,
  deviceFirmwareVersion,
  action,
}) {
  const appContext = useContext(AppContext);
  const { t } = useTranslation();

  const selectedLightAnimationIn =
    appContext.deviceFirmwareModes.lightAnimationsIn.find(
      (animation) => animation.id === action.animationInId
    );

  const selectedLightAnimationOut =
    appContext.deviceFirmwareModes.lightAnimationsOut.find(
      (animation) => animation.id === action.animationOutId
    );

  return (
    <>
      <Card>
        <Text
          style={[
            AppStyles.typography14,
            { fontWeight: "bold", color: appContext.appTheme.text },
          ]}
        >
          {t(
            "screens.device.scenes.editActions.editActionAnimationsCardContent.animationsIn"
          )}
        </Text>

        <MyDropdown
          disabled={disabled}
          style={{ marginTop: 2 }}
          label={t(
            "screens.device.scenes.editActions.editActionAnimationsCardContent.dropdownAnimationIn.label"
          )}
          selectedItemLabel={
            selectedLightAnimationIn.name[appContext.appLanguage]
          }
          onPress={() =>
            navigation.navigate("modalEditActionAnimationInOrOutSelection", {
              animationType: "animationIn",
              deviceFirmwareVersion: deviceFirmwareVersion,
              action: action,
            })
          }
        />

        <EditActionAdjustmentsContent
          action={action}
          adjustmentType="animationIn"
          adjustment={selectedLightAnimationIn.adjustment}
        />

        <Text
          style={[
            AppStyles.typography14,
            {
              fontWeight: "bold",
              marginTop: 10,
              color: appContext.appTheme.text,
            },
          ]}
        >
          {t(
            "screens.device.scenes.editActions.editActionAnimationsCardContent.animationsOut"
          )}
        </Text>

        <MyDropdown
          disabled={disabled}
          style={{ marginTop: 2 }}
          label={t(
            "screens.device.scenes.editActions.editActionAnimationsCardContent.dropdownAnimationOut.label"
          )}
          selectedItemLabel={
            selectedLightAnimationOut.name[appContext.appLanguage]
          }
          onPress={() =>
            navigation.navigate("modalEditActionAnimationInOrOutSelection", {
              animationType: "animationOut",
              deviceFirmwareVersion: deviceFirmwareVersion,
              action: action,
            })
          }
        />

        <EditActionAdjustmentsContent
          action={action}
          adjustmentType="animationOut"
          adjustment={selectedLightAnimationOut.adjustment}
        />
      </Card>
    </>
  );
}

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

  let { animationType, deviceFirmwareVersion, action } = route.params;

  const supportedLightAnimations =
    animationType === "animationIn"
      ? appContext.deviceFirmwareModes.lightAnimationsIn.filter(
          (animation) =>
            animation.supportedFirmwareVersions.includes(
              deviceFirmwareVersion
            ) || animation.supportedFirmwareVersions.includes("*")
        )
      : appContext.deviceFirmwareModes.lightAnimationsOut.filter(
          (animation) =>
            animation.supportedFirmwareVersions.includes(
              deviceFirmwareVersion
            ) || animation.supportedFirmwareVersions.includes("*")
        );

  animationType =
    animationType === "animationIn" ? "animationInId" : "animationOutId";

  useFocusEffect(
    useCallback(() => {
      navigation.setOptions({
        title:
          animationType === "animationInId"
            ? t(
                "screens.device.scenes.editActions.modalEditActionAnimationInSelection.pageTitle"
              )
            : t(
                "screens.device.scenes.editActions.modalEditActionAnimationOutSelection.pageTitle"
              ),
      });
    }, [])
  );

  return (
    <ModalContainer withoutPadding>
      {supportedLightAnimations.length === 0 ? (
        <MyResult
          text={
            animationType === "animationInId"
              ? t(
                  "screens.device.scenes.editActions.modalEditActionAnimationInSelection.noResult"
                )
              : t(
                  "screens.device.scenes.editActions.modalEditActionAnimationOutSelection.noResult"
                )
          }
          iconName="select-search"
        />
      ) : (
        <FlatList
          data={supportedLightAnimations}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => (
            <MyPickerModalListItem
              itemName={item.name[appContext.appLanguage]}
              itemSelected={action[animationType] === item.id}
              onPress={() => {
                navigation.goBack();

                appContext.setDeviceSceneActions((arr) => {
                  const newArr = [...arr];

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

                  newArr[foundActionIndex][animationType] = item.id;

                  const type =
                    animationType === "animationInId"
                      ? "animationInAdjustment"
                      : "animationOutAdjustment";

                  newArr[foundActionIndex][type][item.adjustment.variableName] =
                    item.adjustment.defaultValue;

                  return newArr;
                });
              }}
            />
          )}
        />
      )}
    </ModalContainer>
  );
}

export function EditActionAdjustmentsContent({
  action,
  adjustmentType,
  adjustment,
  adjustments,
}) {
  if (adjustments === undefined && Object.keys(adjustment).length === 0)
    return <></>;

  if (adjustments !== undefined) {
    return (
      <FlatList
        data={adjustments}
        scrollEnabled={false}
        renderItem={({ item }) => {
          if (item.type === "slider") {
            return (
              <EditActionSliderAdjustment
                action={action}
                adjustmentType={adjustmentType}
                adjustment={item}
              />
            );
          }

          console.log("EditActionAdjustmentsContent item type not found");
          return <Text>Item type not found</Text>;
        }}
      />
    );
  }

  return (
    <EditActionSliderAdjustment
      action={action}
      adjustmentType={adjustmentType}
      adjustment={adjustment}
    />
  );
}

function EditActionSliderAdjustment({ action, adjustmentType, adjustment }) {
  const appContext = useContext(AppContext);

  const type =
    adjustmentType === "mode"
      ? "modeAdjustments"
      : adjustmentType === "animationIn"
      ? "animationInAdjustment"
      : "animationOutAdjustment";

  const [sliderValue, setSliderValue] = useState(
    action[type][adjustment.variableName]
  );

  return (
    <>
      <Text
        style={[AppStyles.typography14, { color: appContext.appTheme.text }]}
      >
        {adjustment.name[appContext.appLanguage]}
      </Text>

      <View style={{ flexDirection: "row", alignItems: "center" }}>
        <MyIcon name={adjustment.iconName} size={24} />

        <MySlider
          style={[{ flex: 1 }, IsPlatformIos() && { marginLeft: 6 }]}
          minimumValue={adjustment.min}
          maximumValue={adjustment.max}
          onValueChange={(v) => setSliderValue(v)}
          value={sliderValue}
          onSlidingComplete={(v) =>
            appContext.setDeviceSceneActions((arr) => {
              const newArr = [...arr];

              const foundActionIndex = arr.findIndex(
                (a) => a.actionId === action.actionId
              );

              if (foundActionIndex !== -1) {
                newArr[foundActionIndex][type][adjustment.variableName] = v;
              }

              return newArr;
            })
          }
        />

        <View style={{ width: 32, alignItems: "center" }}>
          <Text style={{ color: appContext.appTheme.text }}>
            {sliderValue}
            {adjustment.unitOfMeasurement[appContext.appLanguage]}
          </Text>
        </View>
      </View>
    </>
  );
}

export function RenderHeaderRight({ navigation, appContext, t, action }) {
  return (
    <MyDotsModal
      modalData={[
        /*{
                TODO: Fix it
                  bug: Duplicated item as references to the old action -> if the color is changed it will apply on both actions
  
                  icon: "content-duplicate",
                  label: t(
                    "screens.device.scenes.modalDotsEditAction.duplicateAction"
                  ),
                  onPress: () => {
                    const currentSelectedAction =
                      appContext.deviceSceneActions.find(
                        (a) => a.actionId === actionId
                      );
  
                    appContext.setDeviceSceneActions((arr) => {
                      const duplicatedAction = {
                        ...currentSelectedAction,
                        actionId: GetUuid(),
                      };
  
                      return [...arr, duplicatedAction];
                    });
  
                    navigation.goBack();
                  },
                },*/
        {
          icon: "trash-can",
          label: t(
            "screens.device.scenes.editActions.modalDotsEditAction.deleteAction"
          ),
          onPress: () => {
            appContext.setDeviceSceneActions((actions) =>
              actions.filter((a) => a.actionId !== action.actionId)
            );

            navigation.goBack();
          },
        },
      ]}
    />
  );
}
