import { useContext, useState } from "react";
import { Text, TouchableHighlight, View } from "react-native";
import MyButton from "../../../../../Components/Button";
import { useTranslation } from "react-i18next";
import {
  AppContext,
  AppSelectedUserDevice,
  Constants,
  GetDevice,
  ModalContainer,
  NewAction,
} from "../../../../../utils";

function Layer({ number, selected, onPress }) {
  return (
    <TouchableHighlight onPress={onPress} style={{ borderRadius: 10 }}>
      <View
        style={[
          {
            height: 150,
            width: 150,
            backgroundColor: "gray",
            borderRadius: 10,
          },
          selected && { borderColor: "#9b59b6", borderWidth: 6 },
        ]}
      >
        <View style={{ alignItems: "flex-end" }}>
          <View
            style={{
              marginTop: 6,
              marginRight: 6,
              backgroundColor: "#e67e22",
              paddingLeft: 6,
              paddingRight: 6,
              borderRadius: 10,
            }}
          >
            <Text>{number}</Text>
          </View>
        </View>
      </View>
    </TouchableHighlight>
  );
}

export default function LayerSelectionModalContent({ navigation, route }) {
  const appContext = useContext(AppContext);
  const { t } = useTranslation();
  const [selectedLayer, setSelectedLayer] = useState([]);

  const handleSelectLayerClick = (layerNumber) => {
    if (selectedLayer.includes(layerNumber)) {
      setSelectedLayer((sLayer) =>
        sLayer.filter((item) => item != layerNumber)
      );
    } else {
      setSelectedLayer((sLayer) => [...sLayer, layerNumber]);
    }
  };

  return (
    <ModalContainer>
      <View
        style={{
          flexDirection: "row",
          flexWrap: "wrap",
          gap: 14,
          justifyContent: "center",
        }}
      >
        {Array.from({ length: 4 }).map((_, i) => (
          <Layer
            key={i}
            number={i + 1}
            selected={selectedLayer.includes(i + 1)}
            onPress={() => handleSelectLayerClick(i + 1)}
          />
        ))}
      </View>

      <View style={{ alignItems: "center" }}>
        <MyButton
          title={t("screens.device.scenes.buttonAddAction")}
          style={{ marginTop: 20, width: 180 }}
          disabled={selectedLayer.length === 0}
          onPress={() => {
            const newAction = NewAction(
              GetDevice(appContext.devices).selectedScene,
              Constants.actionType.layers,
              { layers: selectedLayer }
            );

            appContext.setDeviceSceneActions((arr) => [...arr, newAction]);

            route.params["action"] = newAction;

            navigation.navigate(AppSelectedUserDevice.current.routeName);
            navigation.navigate("modalLightsEditAction", {
              ...route.params,
              actionType: Constants.actionType.layers,
            });
          }}
        />
      </View>
    </ModalContainer>
  );
}
