import {
  FlatList,
  ScrollView,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { ColorPickerRef } from "reanimated-color-picker"; // used
import {
  AppContext,
  AppStyles,
  Constants,
  ModalContainer,
} from "../../../../../utils";
import Animated, {
  useAnimatedStyle,
  useSharedValue,
} from "react-native-reanimated";
import { useFocusEffect } from "@react-navigation/native";
import { DeviceLivePreview } from "../../..";
import {
  MyDeviceTabButton,
  MyDeviceTabButtonContainer,
} from "../../../deviceTabButton";
import Card from "../../../../../Components/Card";
import MyDropdown from "../../../../../Components/Dropdown";
import { MyIconButton } from "../../../../../Components/Button";
import { MyColorPickerV2 } from "../../../../../Components/ColorPicker";
import {
  EditActionAdjustmentsContent,
  EditActionAnimationsCardContent,
  RenderHeaderRight,
} from "..";
import { MyPickerModalListItem } from "../../../../../Components/Modal";

// This component is used by layers and ambilight
export default function LightsEditActionModalContent({ navigation, route }) {
  const appContext = useContext(AppContext);

  const sharedLightModeDefaultColors = useSharedValue([]);
  const [selectedDefaultLightModeColor, setSelectedDefaultLightModeColor] =
    useState(0);
  const colorPickerRef = useRef(ColorPickerRef);
  const { t } = useTranslation();

  const { actionType, deviceFirmwareVersion, action } = route.params;

  useFocusEffect(
    useCallback(() => {
      navigation.setOptions({
        title:
          actionType === Constants.actionType.layers
            ? t(
                "screens.device.scenes.editActions.modalLightsEditAction.layersPageTitle"
              )
            : t(
                "screens.device.scenes.editActions.modalLightsEditAction.ambilightPageTitle"
              ),
        headerRight: () => (
          <RenderHeaderRight
            action={action}
            appContext={appContext}
            navigation={navigation}
            t={t}
          />
        ),
      });
    }, [])
  );

  const supportedDeviceLightModes =
    appContext.deviceFirmwareModes.lightModes.filter((lightMode) =>
      lightMode.supportedFirmwareVersions.includes(deviceFirmwareVersion)
    );

  const [lightModeDefaultColors, setLightModeDefaultColors] = useState([]);

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

  useEffect(() => {
    if (colorPickerRef.current && selectedLightMode.defaults.length > 0) {
      colorPickerRef.current.setColor(action.modeAdjustments.colors[0]);
    }
  }, [lightModeDefaultColors]);

  useEffect(() => {
    if (selectedLightMode !== undefined) {
      sharedLightModeDefaultColors.value = action.modeAdjustments.colors;
      setLightModeDefaultColors(action.modeAdjustments.colors);
      setSelectedDefaultLightModeColor(0);
    }
  }, [action?.modeId]);

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

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

      if (foundSceneActionIndex !== -1) {
        newArr[foundSceneActionIndex].modeAdjustments.colors =
          sharedLightModeDefaultColors.value;
      }

      return newArr;
    });
  };

  if (!action) return null;

  return (
    <ModalContainer withoutPadding>
      <DeviceLivePreview />

      <MyDeviceTabButtonContainer>
        <MyDeviceTabButton
          iconName="play-network-outline"
          onPress={() => console.log("pressed")}
        />
        <MyDeviceTabButton
          iconName="play-box-multiple-outline"
          onPress={() => console.log("pressed2")}
        />
      </MyDeviceTabButtonContainer>

      <ScrollView>
        <Card>
          <MyDropdown
            style={{ marginBottom: 2 }}
            label={t(
              "screens.device.scenes.editActions.modalLightsEditAction.dropdownColorModeSelection.label"
            )}
            selectedItemLabel={
              action.modeId === ""
                ? t(
                    "screens.device.scenes.editActions.modalLightsEditAction.dropdownColorModeSelection.noColorModeSelected"
                  )
                : selectedLightMode.name[appContext.appLanguage]
            }
            onPress={() =>
              navigation.navigate("modalLightsEditActionColorModeSelection", {
                supportedDeviceLightModes: supportedDeviceLightModes,
                action: action,
              })
            }
          />

          {action.modeId !== "" && (
            <>
              {lightModeDefaultColors.length > 0 && (
                <>
                  <View
                    style={{
                      flexDirection: "row",
                      justifyContent: "space-between",
                      alignItems: "center",
                      marginTop: 2,
                    }}
                  >
                    <Text
                      style={[
                        AppStyles.typography14,
                        {
                          marginTop: 4,
                          marginBottom: 4,
                          color: appContext.appTheme.text,
                        },
                      ]}
                    >
                      {t(
                        "screens.device.scenes.editActions.modalLightsEditAction.modeSpecificColors"
                      )}
                    </Text>

                    <MyIconButton iconName="restore" iconSize={24} />
                  </View>

                  <View
                    style={{
                      flexDirection: "row",
                      gap: 10,
                      flexWrap: "wrap",
                      justifyContent: "center",
                    }}
                  >
                    {lightModeDefaultColors.map((_, index) => (
                      <TouchableOpacity
                        key={index}
                        onPress={() => {
                          setSelectedDefaultLightModeColor(index);

                          colorPickerRef.current.setColor(
                            sharedLightModeDefaultColors.value[index]
                          );
                        }}
                      >
                        <LightModeDefaultColor
                          sharedColor={sharedLightModeDefaultColors}
                          index={index}
                          backgroundColor={appContext.appTheme.backgroundColor}
                          selected={selectedDefaultLightModeColor === index}
                        />
                      </TouchableOpacity>
                    ))}
                  </View>

                  <MyColorPickerV2
                    pickerRef={colorPickerRef}
                    style={{ marginTop: 10 }}
                    appThemeText={appContext.appTheme.text}
                    isUserExpertModeEnabled={appContext.isUserExpertModeEnabled}
                    disabled={selectedDefaultLightModeColor === undefined}
                    onColorPickerChange={(color) => {
                      if (selectedDefaultLightModeColor !== undefined) {
                        let newColors = sharedLightModeDefaultColors.value;

                        newColors[selectedDefaultLightModeColor] = color;

                        sharedLightModeDefaultColors.value = newColors;
                      }
                    }}
                    onColorPickerComplete={() => saveColorsToModeAdjustments()}
                    onColorSwatchPress={() => saveColorsToModeAdjustments()}
                  />
                </>
              )}

              <EditActionAdjustmentsContent
                action={action}
                adjustmentType="mode"
                adjustments={selectedLightMode.adjustments}
              />
            </>
          )}
        </Card>

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

function LightModeDefaultColor({
  sharedColor,
  index,
  backgroundColor,
  selected,
}) {
  const backgroundColorStyle = useAnimatedStyle(() => {
    return {
      backgroundColor: sharedColor.value[index],
    };
  });

  return (
    <Animated.View
      style={[
        {
          width: 32,
          height: 32,
          borderRadius: 10,
          justifyContent: "center",
          alignItems: "center",
        },
        backgroundColorStyle,
      ]}
    >
      <Animated.View
        style={[
          {
            width: 28,
            height: 28,
            borderRadius: 8,
          },
          backgroundColorStyle,
          selected && { borderWidth: 2, borderColor: backgroundColor },
        ]}
      />
    </Animated.View>
  );
}

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

  const { action, supportedDeviceLightModes } = route.params;

  return (
    <ModalContainer withoutPadding>
      <FlatList
        data={supportedDeviceLightModes}
        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>
  );
}
