import { ScrollView, Text, View } from "react-native";
import Card from "../../Components/Card";
import { useContext, useEffect, useState } from "react";
import {
  AppContext,
  AppSelectedUserDevice,
  AppSelectedUserDeviceDefaultData,
  AppStyles,
  Constants,
  GetDevice,
} from "../../utils";
import { Divider } from "../../Components/Divider";
import { useTranslation } from "react-i18next";
import MySwitch from "../../Components/Switch";
import MyButton, { MyIconButton } from "../../Components/Button";
import { MyBottomSheetModal } from "../../Components/Modal";

export default function SettingsView({ navigation }) {
  const appContext = useContext(AppContext);
  const { t } = useTranslation();
  const [switchState, setSwitchState] = useState(false);
  const [textDeviceIdHidden, setTextDeviceIdHidden] = useState(true);
  const [textDeviceMacAddressHidden, setTextDeviceMacAddressHidden] =
    useState(true);
  const [
    isBottomSheetModalCloseConnectionOpen,
    setIsBottomSheetModalCloseConnectionOpen,
  ] = useState(false);
  const [
    isBottomSheetModalResetToFactorySettingsOpen,
    setIsBottomSheetModalResetToFactorySettingsOpen,
  ] = useState(false);

  const device = GetDevice(appContext.devices);

  const SettingsText = ({ containerStyle, title, description, hidden }) => {
    return (
      <View style={[containerStyle]}>
        <View>
          <Text
            style={
              ([AppStyles.typography16], { color: appContext.appTheme.text })
            }
          >
            {title}
          </Text>

          <Text
            selectable
            style={
              ([AppStyles.typography14],
              { color: appContext.appTheme.textSecondary })
            }
          >
            {hidden ? "************" : description}
          </Text>
        </View>
      </View>
    );
  };

  useEffect(() => {
    navigation.setOptions({
      headerRight: null,
    });
  }, []);

  const deleteDeviceFromApp = () => {
    appContext.setDevices((devices) =>
      devices.filter((d) => d.id !== device.id)
    );

    appContext.setDeviceScenes((scenes) =>
      scenes.filter((s) => s.deviceId !== device.id)
    );

    appContext.setDeviceSceneActions((actions) =>
      actions.filter((a) => a.deviceId !== device.id)
    );

    // show no devices connected screen if there are no devices left
    if (appContext.devices.length < 2) {
      navigation.navigate("_noDevicesConnected");
      AppSelectedUserDevice.current = AppSelectedUserDeviceDefaultData;
    }

    // TODO: remove device from app async storage if it is not already handled by appContext
  };

  return (
    <ScrollView>
      <Card
        cardTopicText={t("screens.device.settings.settingsTitle")}
        disablePaddingBottom
      >
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <SettingsText
            containerStyle={{ width: "80%" }}
            title={t("screens.device.settings.wifiStandByTitle")}
            description={t("screens.device.settings.wifiStandByDescription")}
          />

          <MySwitch
            value={switchState}
            onValueChange={(e) => setSwitchState(e)}
          />
        </View>
      </Card>

      <Card
        cardTopicText={t("screens.device.settings.deviceInformationText")}
        disablePaddingBottom
      >
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <SettingsText
            title={t("screens.device.settings.deviceNameText")}
            description={device.displayName}
          />

          <MyIconButton
            onPress={() =>
              navigation.navigate("modalSettingsChangeDeviceDisplayName", {
                id: device.id,
                displayName: device.displayName,
              })
            }
            iconName="pencil"
            iconSize={18}
            style={{ padding: 4 }}
          />
        </View>

        <Divider />

        <SettingsText
          title={t("screens.device.settings.deviceModelText")}
          description={device.deviceModel}
        />

        <Divider />

        <SettingsText
          title={t("screens.device.settings.deviceFirmwareVersionText")}
          description={device.firmware.version}
        />

        <Divider />

        <SettingsText
          title={t("screens.device.settings.deviceLastUpdatedText")}
          description={device.firmware.lastUpdated}
        />

        <Divider />

        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <SettingsText
            title={t("screens.device.settings.deviceMacAddressText")}
            description={device.deviceMacAddress}
            hidden={textDeviceMacAddressHidden}
          />

          <MyIconButton
            onPress={() =>
              setTextDeviceMacAddressHidden(!textDeviceMacAddressHidden)
            }
            iconName={textDeviceMacAddressHidden ? "eye-off" : "eye"}
            iconSize={18}
            style={{ padding: 4 }}
          />
        </View>

        <Divider />

        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <SettingsText
            title={t("screens.device.settings.deviceIPAddressText")}
            description={device.deviceIp}
            hidden={textDeviceIdHidden}
          />

          <MyIconButton
            onPress={() => setTextDeviceIdHidden(!textDeviceIdHidden)}
            iconName={textDeviceIdHidden ? "eye-off" : "eye"}
            iconSize={18}
            style={{ padding: 4 }}
          />
        </View>
      </Card>

      <Card cardTopicText={"Geräteverwaltung"}>
        <SettingsText
          title={t("screens.device.settings.closeConnectionTitle")}
          description={t("screens.device.settings.closeConnectionDescription")}
        />

        <View style={{ alignItems: "center", marginTop: 6 }}>
          <MyButton
            title={t("screens.device.settings.closeConnectionButton")}
            style={{
              width: "80%",
            }}
            onPress={() => setIsBottomSheetModalCloseConnectionOpen(true)}
          />
        </View>

        <MyBottomSheetModal
          isOpen={isBottomSheetModalCloseConnectionOpen}
          closeModal={() => setIsBottomSheetModalCloseConnectionOpen(false)}
          headerTitle={t(
            "screens.device.settings.bottomSheetModalCloseConnection.headerTitle"
          )}
          modalHeight={172}
        >
          <View style={{ paddingLeft: 20, paddingRight: 20 }}>
            <Text
              style={[
                { color: appContext.appTheme.text },
                AppStyles.typography14,
              ]}
            >
              {t(
                "screens.device.settings.bottomSheetModalCloseConnection.description"
              )}
            </Text>

            <View
              style={{
                flexDirection: "row",
                gap: 10,
                justifyContent: "center",
                marginTop: 10,
              }}
            >
              <MyButton
                title={t(
                  "screens.device.settings.bottomSheetModalCloseConnection.cancelButton"
                )}
                style={{ width: 100 }}
                buttonBackgroundColor={appContext.appTheme.buttonSecondary}
                onPress={() => setIsBottomSheetModalCloseConnectionOpen(false)}
                buttonGradientColor={Constants.gradients.gray}
              />
              <MyButton
                title={t(
                  "screens.device.settings.bottomSheetModalCloseConnection.confirmButton"
                )}
                style={{ width: 160 }}
                onPress={() => {
                  // TODO: is a request needed to the esp? or is it enough to just remove the device from the app?
                  console.log("close connection to device", device.id);

                  deleteDeviceFromApp();
                }}
              />
            </View>
          </View>
        </MyBottomSheetModal>

        <Divider />

        <SettingsText
          title={t("screens.device.settings.resetToFactorySettingsTitle")}
          description={t(
            "screens.device.settings.resetToFactorySettingsDescription"
          )}
        />

        <View style={{ alignItems: "center", marginTop: 6 }}>
          <MyButton
            title={t("screens.device.settings.resetToFactorySettingsButton")}
            style={{ width: "80%" }}
            onPress={() =>
              setIsBottomSheetModalResetToFactorySettingsOpen(true)
            }
          />
        </View>

        <MyBottomSheetModal
          isOpen={isBottomSheetModalResetToFactorySettingsOpen}
          closeModal={() =>
            setIsBottomSheetModalResetToFactorySettingsOpen(false)
          }
          headerTitle={t(
            "screens.device.settings.bottomSheetModalResetToFactorySettings.headerTitle"
          )}
          modalHeight={appContext.appLanguage === "en" ? 152 : 172}
        >
          <View style={{ paddingLeft: 20, paddingRight: 20 }}>
            <Text
              style={[
                { color: appContext.appTheme.text },
                AppStyles.typography14,
              ]}
            >
              {t(
                "screens.device.settings.bottomSheetModalResetToFactorySettings.description"
              )}
            </Text>

            <View
              style={{
                flexDirection: "row",
                gap: 10,
                justifyContent: "center",
                marginTop: 10,
              }}
            >
              <MyButton
                title={t(
                  "screens.device.settings.bottomSheetModalResetToFactorySettings.cancelButton"
                )}
                style={{ width: 100 }}
                buttonBackgroundColor={appContext.appTheme.buttonSecondary}
                onPress={() =>
                  setIsBottomSheetModalResetToFactorySettingsOpen(false)
                }
                buttonGradientColor={Constants.gradients.gray}
              />
              <MyButton
                title={t(
                  "screens.device.settings.bottomSheetModalResetToFactorySettings.confirmButton"
                )}
                style={{ width: 160 }}
                onPress={() => {
                  // TODO: API request to esp for reset to factory settings
                  console.log("reseting esp and closing connection", device.id);

                  deleteDeviceFromApp();
                }}
              />
            </View>
          </View>
        </MyBottomSheetModal>
      </Card>
    </ScrollView>
  );
}
