import { checkUserSession } from "@/redux/user/user.actions";
import { selectBodyshop, selectCurrentUser } from "@/redux/user/user.selectors";
import { ApolloProvider } from "@apollo/client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import {
  DarkTheme,
  DefaultTheme,
  ThemeProvider,
} from "@react-navigation/native";
import { Stack } from "expo-router";
import {
  Icon,
  Label,
  NativeTabs,
  VectorIcon,
} from "expo-router/unstable-native-tabs";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { ActivityIndicator, Platform, View } from "react-native";
import { Provider as PaperProvider } from "react-native-paper";
import { connect, Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { createStructuredSelector } from "reselect";
import { client } from "../graphql/client";
import { useTheme as usePaperTheme } from "../hooks/useTheme";
import { persistor, store } from "../redux/store";
import "../translations/i18n";

function AuthenticatedLayout() {
  const { t } = useTranslation();
  const paperTheme = usePaperTheme();
  return (
    <ThemeProvider
      value={paperTheme.theme === "dark" ? DarkTheme : DefaultTheme}
    >
      <NativeTabs
        minimizeBehavior="onScrollDown"
        disableTransparentOnScrollEdge
        {...(paperTheme.theme === "dark"
          ? {
              backgroundColor: DarkTheme.colors.background,
              tintColor: DarkTheme.colors.text,
              indicatorColor: DarkTheme.colors.border,
            }
          : {})}
      >
        <NativeTabs.Trigger name="jobs">
          <Label>{t("joblist.labels.activejobs")}</Label>

          {Platform.select({
            ios: <Icon sf="checklist" drawable="custom_android_drawable" />,
            android: (
              <Icon
                src={<VectorIcon family={MaterialIcons} name="checklist" />}
              />
            ),
          })}
        </NativeTabs.Trigger>
        <NativeTabs.Trigger name="settings">
          {Platform.select({
            ios: <Icon sf="gear" drawable="custom_android_drawable" />,
            android: (
              <Icon
                src={<VectorIcon family={MaterialIcons} name="settings" />}
              />
            ),
          })}
          <Label>{t("settings.titles.settings")}</Label>
        </NativeTabs.Trigger>
        <NativeTabs.Trigger name="search" role="search">
          {Platform.select({
            //ios: <Icon sf="checklist" drawable="custom_android_drawable" />,
            android: (
              <Icon src={<VectorIcon family={MaterialIcons} name="search" />} />
            ),
          })}
          <Label>Search</Label>
        </NativeTabs.Trigger>
      </NativeTabs>
    </ThemeProvider>
  );
}

function UnauthenticatedLayout() {
  return (
    <Stack>
      <Stack.Screen name="sign-in" options={{ headerShown: false }} />
    </Stack>
  );
}

function LoadingLayout() {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <ActivityIndicator size="large" />
    </View>
  );
}

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser,
});
const mapDispatchToProps = (dispatch: any) => ({
  checkUserSession: () => dispatch(checkUserSession()),
});
function AppContent({ currentUser, checkUserSession, bodyshop }: any) {
  useEffect(() => {
    checkUserSession();
  }, [checkUserSession]);

  if (currentUser.authorized === null) {
    return (
      <ThemedLayout>
        <LoadingLayout />
      </ThemedLayout>
    );
  }
  if (currentUser.authorized) {
    return (
      <ThemedLayout>
        <AuthenticatedLayout />
      </ThemedLayout>
    );
  }
  return (
    <ThemedLayout>
      <UnauthenticatedLayout />
    </ThemedLayout>
  );
}

function ThemedLayout({ children }: { children: React.ReactNode }) {
  const themeToApply = usePaperTheme();
  return <PaperProvider theme={themeToApply}>{children}</PaperProvider>;
}
const ConnectedAppContent = connect(
  mapStateToProps,
  mapDispatchToProps
)(AppContent);

export default function AppLayout() {
  return (
    <Provider store={store}>
      <PersistGate persistor={persistor}>
        <ApolloProvider client={client}>
          <ConnectedAppContent />
        </ApolloProvider>
      </PersistGate>
    </Provider>
  );
}
