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

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 LightsEditActionModalContent({ navigation, route }) {
  const appContext = useContext(AppContext);
  const [lightModeDefaultColors, setLightModeDefaultColors] = useState([]);
  const sharedLightModeDefaultColors = useSharedValue([]);
  const [selectedDefaultLightModeColor, setSelectedDefaultLightModeColor] =
    useState(0);
  const colorPickerRef = useRef(ColorPickerRef);
  const { t } = useTranslation();

  const { actionId, deviceFirmwareVersion } = route.params;

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

  const selectedSceneActionModeId = appContext.deviceSceneActions.find(
    (a) => a.actionId === actionId
  ).modeId;

  const selectedLightMode = supportedDeviceLightModes.find(
    (s) => s.id === selectedSceneActionModeId
  );

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

  useEffect(() => {
    if (selectedLightMode !== undefined) {
      sharedLightModeDefaultColors.value = selectedLightMode.defaults;
      setLightModeDefaultColors(selectedLightMode.defaults);
      setSelectedDefaultLightModeColor(0);
    }
  }, [selectedSceneActionModeId]);

  return (
    <View
      style={{
        backgroundColor: appContext.appTheme.backgroundColor,
        height: "100%",
      }}
    >
      {appContext.isUserDeveloperModeEnabled ? (
        <Image
          source={require("../../../../../../assets/device.png")}
          style={{ width: "100%", height: 200 }}
          resizeMode="contain"
        />
      ) : (
        <View
          style={[
            {
              width: "100%",
              height: 200,
            },
            { backgroundColor: "#ddd" },
          ]}
        />
      )}

      <MyDeviceTabButton iconName="play-network-outline" top={topFirst + 10} />
      <MyDeviceTabButton
        iconName="play-box-multiple-outline"
        top={topSecond + 15}
      />

      <ScrollView>
        <Card>
          <MyDropdown
            style={{ marginBottom: 2 }}
            label={t(
              "screens.device.scenes.modalLayersEditAction.dropdownColorModeSelection.label"
            )}
            selectedItemLabel={
              selectedSceneActionModeId === ""
                ? t(
                    "screens.device.scenes.modalLayersEditAction.dropdownColorModeSelection.noColorModeSelected"
                  )
                : selectedLightMode.name[appContext.appLanguage]
            }
            onPress={() =>
              navigation.navigate("modalLayersEditActionColorModeSelection", {
                supportedDeviceLightModes: supportedDeviceLightModes,
                selectedSceneActionModeId: selectedSceneActionModeId,
                actionId: route.params.actionId,
              })
            }
          />

          {selectedSceneActionModeId !== "" && (
            <>
              {lightModeDefaultColors.length > 0 && (
                <>
                  <View
                    style={{
                      flexDirection: "row",
                      justifyContent: "space-between",
                      alignItems: "center",
                    }}
                  >
                    <Text
                      style={[
                        AppStyles.typography14,
                        {
                          marginTop: 4,
                          marginBottom: 4,
                          color: appContext.appTheme.text,
                        },
                      ]}
                    >
                      {t(
                        "screens.device.scenes.modalLayersEditAction.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={() => {
                          /*const newSelection =
                            selectedDefaultLightModeColor !== index
                              ? index
                              : undefined;

                          setSelectedDefaultLightModeColor(newSelection);

                          if (newSelection !== undefined) {
                            colorPickerRef.current.setColor(
                              sharedLightModeDefaultColors.value[index]
                            );
                          }*/

                          setSelectedDefaultLightModeColor(index);

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

                  <Divider />

                  <MyColorPickerV2
                    pickerRef={colorPickerRef}
                    style={[
                      selectedSceneActionModeId === "" && { 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;
                      }
                    }}
                  />
                </>
              )}

              {selectedLightMode.adjustments.length > 0 && (
                <View style={{ marginTop: 2 }}>
                  {selectedLightMode.adjustments.map((adjustment, index) => (
                    <EditActionAdjustmentContent
                      key={index}
                      adjustment={adjustment}
                      appThemeText={appContext.appTheme.text}
                      appLanguage={appContext.appLanguage}
                    />
                  ))}
                </View>
              )}
            </>
          )}
        </Card>

        <EditActionAnimationsCardContent
          disabled={selectedSceneActionModeId === ""}
          navigation={navigation}
          deviceFirmwareVersion={deviceFirmwareVersion}
          actionId={actionId}
        />
      </ScrollView>
    </View>
  );
}

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

  return (
    <ModalContainer>
      <FlatList
        data={route.params.supportedDeviceLightModes}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <MyPickerModalListItem
            itemName={item.name[appContext.appLanguage]}
            itemSelected={route.params.selectedSceneActionModeId === item.id}
            onPress={() => {
              appContext.setDeviceSceneActions((arr) => {
                const newArr = [...arr];

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

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

                return newArr;
              });

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