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

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

  const deviceSceneAction = appContext.deviceSceneActions.find(
    (action) => action.actionId === actionId
  );

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

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

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

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

        {selectedLightAnimationIn.adjustments.length > 0 &&
          selectedLightAnimationIn.adjustments.map((adjustment, index) => (
            <EditActionAdjustmentContent
              key={index}
              adjustment={adjustment}
              appLanguage={appContext.appLanguage}
              appThemeText={appContext.appTheme.text}
            />
          ))}

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

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

        {selectedLightAnimationOut.adjustments.length > 0 &&
          selectedLightAnimationOut.adjustments.map((adjustment, index) => (
            <EditActionAdjustmentContent
              key={index}
              adjustment={adjustment}
              appLanguage={appContext.appLanguage}
              appThemeText={appContext.appTheme.text}
            />
          ))}
      </Card>
    </>
  );
}

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

  let { animationType, deviceFirmwareVersion, actionId } = 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("*")
        );

  const deviceSceneAction = appContext.deviceSceneActions.find(
    (action) => action.actionId === actionId
  );

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

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

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

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

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

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

export function EditActionAdjustmentContent({
  adjustment,
  appThemeText,
  appLanguage,
}) {
  const [sliderValue, setSliderValue] = useState(0);

  if (adjustment.type === "slider") {
    return (
      <>
        <Text style={[AppStyles.typography14, { color: appThemeText }]}>
          {adjustment.name[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) => {
              console.log(`change ${adjustment.variableName}`, v);
              setSliderValue(v);
            }}
            value={sliderValue}
          />

          <View style={{ width: 32, alignItems: "center" }}>
            <Text style={{ color: appThemeText }}>
              {sliderValue}
              {adjustment.unitOfMeasurement}
            </Text>
          </View>
        </View>
      </>
    );
  }

  return <></>;
}
