import { useContext, useEffect, useState } from "react";
import {
  AddNewDevice,
  AppContext,
  AppSelectedUserDevice,
  AppStyles,
  Constants,
  ModalContainer,
} from "../../utils";
import {
  ActivityIndicator,
  FlatList,
  ScrollView,
  Text,
  View,
} from "react-native";
import MyButton, { MyTextButton } from "../../Components/Button";
import Zeroconf from "react-native-zeroconf";
import Card from "../../Components/Card";
import MyIcon from "../../Components/Icon";
import { useTranslation } from "react-i18next";

const zeroconf = new Zeroconf();

// TODO: stop scanning on unfocs
// TODO: manual input for ip address
// TODO: link to faq?

const devFoundDevices = [
  {
    deviceModel: "Aurora",
    deviceIp: "127.0.0.1",
  },
  {
    deviceModel: "Aurora",
    deviceIp: "127.0.0.1",
  },
  {
    deviceModel: "Aurora",
    deviceIp: "127.0.0.1",
  },
  {
    deviceModel: "Aurora",
    deviceIp: "127.0.0.1",
  },
  {
    deviceModel: "Aurora",
    deviceIp: "127.0.0.1",
  },
  {
    deviceModel: "Aurora",
    deviceIp: "127.0.0.1",
  },
  {
    deviceModel: "Aurora",
    deviceIp: "127.0.0.1",
  },
];

const AppSearchState = {
  init: 0, // appears when user opens the screen
  scanning: 1,
  afterScan: 2,
};

export default function SearchForNewDevicesModalContent({ navigation }) {
  const appContext = useContext(AppContext);
  const { t } = useTranslation();

  const [searchState, setSearchState] = useState(AppSearchState.init);
  const [foundDevices, setFoundDevices] = useState([]);

  const startScanning = () => {
    //zeroconf.scan();

    setSearchState(AppSearchState.scanning);
    setFoundDevices([]);

    let chance = Math.random() < 0.5;

    if (chance) {
      // only for testing
      setTimeout(() => {
        setFoundDevices((prev) => [...prev, devFoundDevices[0]]);
      }, 2000);
    }

    setTimeout(() => stopScanning(), 4000);
  };

  const stopScanning = () => {
    console.log("stop scanning");
    setSearchState(AppSearchState.afterScan);
    // zeroconf.stop();
  };

  useEffect(() => {
    console.log("useEffect");

    startScanning();

    /*
    zeroconf.on("start", () => {
      console.log("start");
    });

    zeroconf.on("stop", () => {
      console.log("stop");
    });

    zeroconf.on("resolved", (service) => {
      console.log("resolved service", service);
    });

    zeroconf.on("error", (err) => {
      console.log("err", err);
    }); */

    setSearchState(AppSearchState.scanning);
  }, []);

  let texts = { searchDescription: "", searchButton: "" };

  switch (searchState) {
    case AppSearchState.init:
      break;
    case AppSearchState.scanning:
      texts.searchDescription = t(
        "screens.modalSearchForNewDevices.searchDescription.scanning"
      );
      texts.searchButton = t(
        "screens.modalSearchForNewDevices.searchButtonText.scanning"
      );
      break;
    case AppSearchState.afterScan:
      if (foundDevices.length > 0) {
        texts.searchDescription = t(
          "screens.modalSearchForNewDevices.searchDescription.afterScanDevicesFound"
        );
      } else {
        texts.searchDescription = t(
          "screens.modalSearchForNewDevices.searchDescription.afterScanNoDevicesFound"
        );
      }

      texts.searchButton = t(
        "screens.modalSearchForNewDevices.searchButtonText.afterScan"
      );
      break;
    default:
      console.log(`Search state ${searchState} not found`);
      break;
  }

  return (
    <ScrollView>
      <View style={{ flex: 1, marginTop: 40, alignItems: "center" }}>
        <View style={{ margin: 40 }}>
          {searchState === AppSearchState.scanning && (
            <ActivityIndicator
              style={{ marginBottom: 20 }}
              size="large"
              color={appContext.appTheme.colors.secondary}
            />
          )}

          <Text
            style={[
              { textAlign: "center", color: appContext.appTheme.text },
              AppStyles.typography14,
            ]}
          >
            {texts.searchDescription}
          </Text>
        </View>

        <MyButton
          buttonGradientColor={Constants.gradients.gray}
          style={{ width: 200 }}
          title={texts.searchButton}
          onPress={() => {
            if (searchState !== AppSearchState.scanning) {
              startScanning();
            } else if (searchState === AppSearchState.scanning) {
              stopScanning();
            }
          }}
        />

        <View style={{ width: "100%" }}>
          <FlatList
            ListHeaderComponent={
              <>
                {foundDevices.length > 0 && (
                  <View style={{ marginLeft: 20 }}>
                    <Text
                      style={[
                        AppStyles.typography16,
                        {
                          fontWeight: "bold",
                          marginTop: 20,
                          color: appContext.appTheme.text,
                        },
                      ]}
                    >
                      {t("screens.modalSearchForNewDevices.textFoundDevices")}
                    </Text>
                  </View>
                )}
              </>
            }
            ListFooterComponent={
              <View style={{ paddingBottom: 10 }}>
                {foundDevices.length > 0 && (
                  <MyTextButton
                    style={{ marginTop: 20 }}
                    title={t(
                      "screens.modalSearchForNewDevices.textButtonBackToOverview"
                    )}
                    onPress={() => navigation.goBack()}
                  />
                )}
              </View>
            }
            scrollEnabled={false}
            data={foundDevices}
            extraData={foundDevices}
            renderItem={({ item }) => (
              <FoundDevice item={item} appContext={appContext} t={t} />
            )}
          />
        </View>
      </View>
    </ScrollView>
  );
}

const FoundDeviceState = {
  notConnected: 0,
  connecting: 1,
  connected: 2,
};

function FoundDevice({ item, appContext, t }) {
  const [connectingState, setConnectingState] = useState(
    FoundDeviceState.notConnected
  );
  // TODO: loading the image of the new found device

  return (
    <Card disablePaddingBottom>
      <View
        style={{
          flexDirection: "row",

          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <View style={{ flexDirection: "row", gap: 10 }}>
          <View style={{ height: 60, width: 60, backgroundColor: "gray" }} />

          <View>
            <Text
              style={{
                fontWeight: "bold",
                color: appContext.appTheme.text,
              }}
            >
              New Device
            </Text>
            <Text style={{ color: appContext.appTheme.textSecondary }}>
              {item.deviceModel}
            </Text>
            <Text style={{ color: appContext.appTheme.textSecondary }}>
              {item.deviceIp}
            </Text>
          </View>
        </View>

        <View>
          <MyButton
            title={
              connectingState === FoundDeviceState.connecting
                ? t(
                    "screens.modalSearchForNewDevices.foundDeviceConnectButton.connecting"
                  )
                : connectingState === FoundDeviceState.connected
                ? t(
                    "screens.modalSearchForNewDevices.foundDeviceConnectButton.connected"
                  )
                : t(
                    "screens.modalSearchForNewDevices.foundDeviceConnectButton.connect"
                  )
            }
            disabled={connectingState !== FoundDeviceState.notConnected}
            onPress={() => {
              console.log("connect");
              // TODO: connect with esp api
              setConnectingState(FoundDeviceState.connecting);

              setTimeout(() => {
                setConnectingState(FoundDeviceState.connected);

                // TODO: other way for this
                // generate random two digit number code
                let code = Math.floor(Math.random() * 100);

                const newDevice = AddNewDevice(
                  "New Device " + code,
                  item.deviceModel,
                  item.deviceIp
                );

                // TODO: add device to app storage and fill up with information provided by the esp
                appContext.setDevices((prev) => [...prev, newDevice]);
                /*
                AppSelectedUserDevice.current = {
                  id: newDevice.id,
                  routeName: newDevice.displayName,
                }; */

                console.log(
                  "appS",
                  newDevice.id,
                  AppSelectedUserDevice.current
                );
              }, 2000);
            }}
            buttonLeftComponent={
              connectingState === FoundDeviceState.connecting ? (
                <ActivityIndicator
                  size="small"
                  color={appContext.appTheme.colors.gray}
                  style={{ marginRight: 6 }}
                />
              ) : connectingState === FoundDeviceState.connected ? (
                <MyIcon
                  name="check"
                  size={12}
                  style={{ marginRight: 6 }}
                  color={"#fff"}
                />
              ) : null
            }
          />
        </View>
      </View>
    </Card>
  );
}
