import React, { useEffect, useRef } from "react";
import i18n from "i18next";
import moment from "moment";
import { AppState } from "react-native";
import { Button } from "react-native-paper";
import { Ionicons } from "@expo/vector-icons";
import { NavigationContainer } from "@react-navigation/native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

import { logImEXEvent } from "../../firebase/firebase.analytics";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { setCameraJob, setCameraJobId } from "../../redux/app/app.actions";
import {
  checkUserSession,
  emailSignInStart,
  signOutStart,
} from "../../redux/user/user.actions";
import {
  selectBodyshop,
  selectCurrentUser,
} from "../../redux/user/user.selectors";
import { employeeSignOut } from "../../redux/employee/employee.actions";
import { selectCurrentEmployee } from "../../redux/employee/employee.selectors";

import ScreenJobDetail from "../screen-job-detail/screen-job-detail.component";
import ScreenJobList from "../screen-job-list/screen-job-list.component";
import ScreenMediaBrowser from "../screen-media-browser/screen-media-browser.component";
import ScreenSettingsComponent from "../screen-settings/screen-settings.component";
import ScreenSignIn from "../screen-sign-in/screen-sign-in.component";
import ScreenSplash from "../screen-splash/screen-splash.component";

import EmployeeSignIn from "../screen-employee-sign-in/screen-employee-sign-in.component";
import ScreenTimeTicketBrowser from "../screen-time-ticket-browser/screen-time-ticket-browser.component";
import SignOutButton from "../Buttons/employee-sign-out-button.component";
import AddTimeTicketButton from "../Buttons/create-time-ticket-button.component";
import ScreenTimeTicketCreate from "../time-ticket/screen-time-ticket-create.component";
import ScreenTimeTicketClockoffComponent from "../time-ticket/screen-time-ticket-clockoff.component";

const ActiveJobStack = createNativeStackNavigator();
const MoreStack = createNativeStackNavigator();
const BottomTabs = createBottomTabNavigator();
const MediaBrowserStack = createNativeStackNavigator();
const TimeTicketBrowserStack = createNativeStackNavigator();

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser,
});
const mapDispatchToProps = (dispatch) => ({
  checkUserSession: () => dispatch(checkUserSession()),
  emailSignInStart: (email, password) =>
    dispatch(emailSignInStart({ email, password })),
  signOutStart: () => dispatch(signOutStart()),
  setCameraJobId: (id) => dispatch(setCameraJobId(id)),
  setCameraJob: (job) => dispatch(setCameraJob(job)),
});
const mapStateToProps2 = createStructuredSelector({
  currentEmployee: selectCurrentEmployee,
});
const mapDispatchToProps2 = (dispatch) => ({
  signOut: () => dispatch(employeeSignOut()),
});

const JobsTabNavigator = connect(
  mapStateToProps,
  mapDispatchToProps
)(({ setCameraJobId, setCameraJob }) => (
  <ActiveJobStack.Navigator initialRouteName="JobList">
    <ActiveJobStack.Screen
      name="JobList"
      options={() => ({
        title: i18n.t("joblist.labels.activejobs"),
      })}
      component={ScreenJobList}
    />
    <ActiveJobStack.Screen
      name="JobDetail"
      component={ScreenJobDetail}
      options={({ navigation, route }) => ({
        title:
          (route.params && route.params.title) ||
          i18n.t("joblist.labels.detail"),
        // eslint-disable-next-line react/display-name
        headerRight: () => (
          <Button
            onPress={() => {
              logImEXEvent("imexmobile_setcamerajobid_jobheader");
              setCameraJobId(route.params.jobId);
              setCameraJob(route.params.job);
              navigation.navigate("MediaBrowserTab");
            }}
          >
            <Ionicons name="ios-add" size={32} color="dodgerblue" />
          </Button>
        ),
      })}
    />
  </ActiveJobStack.Navigator>
));

const MediaBrowserStackNavigator = () => (
  <MediaBrowserStack.Navigator initialRouteName="MediaBrowser">
    <MediaBrowserStack.Screen
      name="MediaBrowser"
      options={{ title: i18n.t("mediabrowser.titles.mediabrowsertab") }}
      component={ScreenMediaBrowser}
    />
  </MediaBrowserStack.Navigator>
);

const MoreStackNavigator = () => (
  <MoreStack.Navigator>
    <MoreStack.Screen
      name="Settings"
      options={{
        title: i18n.t("settings.titles.settings"),
      }}
      component={ScreenSettingsComponent}
    />
  </MoreStack.Navigator>
);

const TimeTicketBrowserStackNavigator = connect(
  mapStateToProps2,
  mapDispatchToProps2
)(({ currentEmployee, signOut }) => {
  const appState = useRef(AppState.currentState);
  useEffect(() => {
    const subscription = AppState.addEventListener("change", (nextAppState) => {
      // console.log("oldAppState", appState.current);
      // console.log("nextAppState", nextAppState);
      // if ( appState.current.match(/inactive|background/) && nextAppState === "active"
      // ) { console.log("App has come to the foreground"); //signOut(); }
      // if (appState.current.match(/active/) && nextAppState === "inactive") {
      //   console.log("App is about to be inactive");
      // }
      if (
        appState.current.match(/active|inactive/) &&
        nextAppState === "background"
      ) {
        // console.log("App is about to be background");
        signOut();
      }
      // if ( appState.current.match(/inactive/)) { console.log("App has come to the inactive"); }
      // if (appState.current.match(/background/)) { console.log("App has come to the background");}
      appState.current = nextAppState;
    });
    return () => {
      subscription.remove();
    };
  }, []);

  return (
    <TimeTicketBrowserStack.Navigator>
      {currentEmployee === null ? (
        <TimeTicketBrowserStack.Screen
          name="EmployeeSignIn"
          options={() => ({ title: i18n.t("employeesignin.titles.signin") })}
          component={EmployeeSignIn}
        />
      ) : currentEmployee.authorized ? (
        <>
          <TimeTicketBrowserStack.Screen
            name="TimeTicketBrowser"
            options={{
              title: i18n.t("timeticketbrowser.titles.timeticketbrowsertab"),
              headerRight: () => (
                <>
                  <AddTimeTicketButton />
                  <SignOutButton />
                </>
              ),
            }}
            component={ScreenTimeTicketBrowser}
          />
          <TimeTicketBrowserStack.Screen
            name="CreateTimeTicket"
            options={() => ({
              title: i18n.t("createtimeticket.titles.createtimeticket"),
            })}
            component={ScreenTimeTicketCreate}
          />
          <TimeTicketBrowserStack.Screen
            name="TimeTicketClockOff"
            options={() => ({
              title: i18n.t("timeticketclockoff.titles.clockoff"),
            })}
            component={ScreenTimeTicketClockoffComponent}
          />
        </>
      ) : (
        <TimeTicketBrowserStack.Screen
          name="EmployeeSignIn"
          options={() => ({
            title: i18n.t("employeesignin.titles.signin"),
          })}
          component={EmployeeSignIn}
        />
      )}
    </TimeTicketBrowserStack.Navigator>
  );
});

const BottomTabsNavigator = () => (
  <BottomTabs.Navigator
    screenOptions={({ route }) => ({
      // eslint-disable-next-line react/display-name
      tabBarIcon: ({ color, size }) => {
        let iconName;
        if (route.name === "JobTab") {
          iconName = "ios-list";
        } else if (route.name === "MoreTab") {
          iconName = "ios-settings";
        } else if (route.name === "MediaBrowserTab") {
          iconName = "ios-camera";
        } else if (route.name === "TimeTicketBrowserTab") {
          iconName = "ios-stopwatch-outline";
        } else {
          //iconName = "customerservice";
        }

        return <Ionicons name={iconName} size={size} color={color} />;
      },
    })}
  >
    <BottomTabs.Screen
      name="JobTab"
      options={{
        title: i18n.t("joblist.titles.jobtab"),
        headerShown: false,
      }}
      component={JobsTabNavigator}
    />
    <BottomTabs.Screen
      name="MediaBrowserTab"
      options={{
        title: i18n.t("mediabrowser.titles.mediabrowsertab"),
        headerShown: false,
      }}
      component={MediaBrowserStackNavigator}
    />
    <BottomTabs.Screen
      name="TimeTicketBrowserTab"
      options={{
        title: i18n.t("timeticketbrowser.titles.timeticketbrowsertab"),
        headerShown: false,
      }}
      component={TimeTicketBrowserStackNavigator}
    />
    <BottomTabs.Screen
      name="MoreTab"
      options={{ title: i18n.t("more.titles.moretab"), headerShown: false }}
      component={MoreStackNavigator}
    />
  </BottomTabs.Navigator>
);

export function ScreenMainComponent({
  checkUserSession,
  currentUser,
  bodyshop,
}) {
  useEffect(() => {
    checkUserSession();
  }, [checkUserSession]);

  return (
    <NavigationContainer>
      {currentUser.authorized === null ? (
        <ScreenSplash />
      ) : currentUser.authorized ? (
        bodyshop ? (
          HasAccess(bodyshop) ? (
            <BottomTabsNavigator />
          ) : (
            <ScreenSplash noAccess />
          )
        ) : (
          <ScreenSplash />
        )
      ) : (
        <ScreenSignIn />
      )}
    </NavigationContainer>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ScreenMainComponent);

function HasAccess({ features }) {
  if (features.mobile === undefined || features.mobile === true) return true;
  if (features.mobile === false) return false;
  const d = moment(moment(features.mobile));
  if (d.isValid()) return d.isAfter(moment());
}
