import {
  ActivityIndicator,
  BackHandler,
  Image,
  Platform,
  SafeAreaView,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import React, { useCallback, useEffect, useState } from "react";
import { Button, HeaderContainer, HeaderTab } from "@src/commonComponent";
import { commonStyles } from "../../../../styles/commonStyle";
import { RideStatus } from "../rideStatus/index";
import { styles } from "./styles";
import Images from "@src/utils/images";
import { appColors, windowHeight } from "@src/themes";
import { clearValue, getValue } from "@src/utils/localstorage";
import { useDispatch, useSelector } from "react-redux";
import { resetState } from "@src/api/store/reducers";
import {
  allRides,
  homeScreenPrimary,
  settingDataGet,
} from "@src/api/store/actions";
import { useAppNavigation } from "@src/utils/navigation";
import { useFocusEffect, useNavigation } from "@react-navigation/native";
import { useValues } from "@src/utils/context/index";
import { Notification } from "@src/utils/icons";
import { AppDispatch } from "@src/api/store";

export function RideScreen() {
  const { bgFullStyle, isRTL, setIsRTL, setIsDark, isDark, viewRTLStyle } =
    useValues();
  const dispatch = useDispatch<AppDispatch>();
  const { translateData } = useSelector((state) => state.setting);
  const { reset } = useAppNavigation();
  const [token, setToken] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const navigation = useNavigation<any>();

  useFocusEffect(
    useCallback(() => {
      const backAction = () => {
        if (navigation.canGoBack()) {
          navigation.navigate("HomeScreen");
          return true;
        }
        return false;
      };

      const backHandler = BackHandler.addEventListener(
        "hardwareBackPress",
        backAction
      );

      return () => backHandler.remove();
    }, [navigation])
  );

  useFocusEffect(
    useCallback(() => {
      dispatch(allRides());
    }, [dispatch])
  );

  useEffect(() => {
    getValue("token").then((value) => {
      setToken(value);
      setLoading(false);
    });
  }, []);

  const gotoSignIn = async () => {
    clearValue();
    dispatch(resetState());
    setIsRTL();
    setIsDark();
    dispatch(settingDataGet());
    await dispatch(homeScreenPrimary());

    reset({
      index: 0,
      routes: [{ name: "SignIn" }],
    });
  };

  const { self } = useSelector((state: any) => state.account);
  useFocusEffect(
    useCallback(() => {
      const backAction = () => {
        if (navigation.canGoBack()) {
          navigation.navigate("HomeScreen");
          return true;
        }
        return false;
      };

      const backHandler = BackHandler.addEventListener(
        "hardwareBackPress",
        backAction
      );

      return () => backHandler.remove();
    }, [navigation])
  );

  const [localImageUri, setLocalImageUri] = useState<string | null>(null);

  useFocusEffect(
    useCallback(() => {
      const fetchStoredImage = async () => {
        const storedImageUri = await getValue("profile_image_uri");
        setLocalImageUri(storedImageUri);
      };
      fetchStoredImage();
    }, [])
  );

  useFocusEffect(
    useCallback(() => {
      const fetchStoredImage = async () => {
        const storedImageUri = await getValue("profile_image_uri");
        setLocalImageUri(storedImageUri);
        setTimeout(() => {
          setLoading(false);
        }, 3000);
      };
      fetchStoredImage();
    }, [])
  );
  const char = self?.name ? self.name.charAt(0) : "";

  const handleImagePress = async () => {
    const token = await getValue("token");
    if (token) {
      navigation.navigate("EditProfile");
    }
  };

  const handelNavigation = async () => {
    const token = await getValue("token");
    if (token) {
      navigation.navigate("Notifications");
    } else {
      navigation.navigate("SignIn");
    }
  };
  return (
    <SafeAreaView
      style={[
        styles.safeAreaContainer,
        {
          backgroundColor: isDark ? appColors.solidBorder : appColors.lightGray,
        },
      ]}
    >
      <HeaderContainer
        value={translateData?.rideTitle}
        lastIcon={
          <View
            style={[
              styles.box,
              {
                backgroundColor: isDark
                  ? appColors.darkHeader
                  : appColors.lightGray,
                flexDirection: viewRTLStyle,
                marginHorizontal: isRTL
                  ? Platform.OS === "ios"
                    ? windowHeight(35)
                    : windowHeight(65)
                  : Platform.OS === "ios"
                  ? windowHeight(30)
                  : windowHeight(55),
              },
            ]}
          >
            <TouchableOpacity
              style={styles.round}
              activeOpacity={0.7}
              onPress={handelNavigation}
            >
              <Notification
                colors={isDark ? appColors.whiteColor : appColors.blackColor}
              />
            </TouchableOpacity>
            <View
              style={[
                styles.divider,
                {
                  backgroundColor: isDark
                    ? appColors.gray
                    : appColors.iconColor,
                },
              ]}
            />
            <TouchableOpacity
              style={styles.imageView}
              activeOpacity={0.7}
              onPress={handleImagePress}
            >
              {self?.profile_image_url ? (
                <Image
                  style={styles.imageStyle}
                  source={{ uri: self.profile_image_url }}
                />
              ) : localImageUri ? (
                <Image
                  style={styles.imageStyle}
                  source={{ uri: localImageUri }}
                />
              ) : (
                <View
                  style={[
                    styles.textView,
                    {
                      backgroundColor: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                >
                  {loading ? (
                    <ActivityIndicator
                      size="small"
                      color={
                        isDark ? appColors.blackColor : appColors.whiteColor
                      }
                    />
                  ) : (
                    <Text
                      style={[
                        styles.charText,
                        {
                          color: isDark
                            ? appColors.blackColor
                            : appColors.whiteColor,
                        },
                      ]}
                    >
                      {char || "G"}
                    </Text>
                  )}
                </View>
              )}
            </TouchableOpacity>
          </View>
        }
      />

      <View
        style={[
          commonStyles.flexContainer,
          {
            backgroundColor: isDark
              ? appColors.solidBorder
              : appColors.lightGray,
          },
        ]}
      >
        {loading ? null : token ? (
          <RideStatus />
        ) : (
          <View style={[styles.mainView, { marginTop: windowHeight(32) }]}>
            <Image source={Images.noSignin} style={styles.imag} />
            <Text style={styles.signInText}>{translateData.signIn}</Text>
            <Text style={styles.accountText}>{translateData.signInNote}</Text>
            <View style={styles.buttonMainView}>
              <View style={styles.buttonView}>
                <Button
                  title={translateData.signIn}
                  textColor={
                    isDark ? appColors.blackColor : appColors.whiteColor
                  }
                  backgroundColor={
                    isDark ? appColors.whiteColor : appColors.blackColor
                  }
                  onPress={gotoSignIn}
                />
              </View>
            </View>
          </View>
        )}
      </View>
    </SafeAreaView>
  );
}
