import {
  ActivityIndicator,
  BackHandler,
  Image,
  Platform,
  SafeAreaView,
  ScrollView,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import React, { useCallback, useState } from "react";
import { external } from "../../../../styles/externalStyle";
import { commonStyles } from "../../../../styles/commonStyle";
import { HeaderContainer } from "@src/commonComponent";
import { CategoryDetail } from "../categoryDetail/index";
import { useValues } from "@src/utils/context/index";
import { appColors, windowHeight } from "@src/themes";
import { useFocusEffect } from "@react-navigation/native";
import { useSelector } from "react-redux";
import { useAppNavigation } from "@src/utils/navigation";
import { Notification } from "@src/utils/icons";
import styles from "./styles";
import { getValue } from "@src/utils/localstorage";

export function CategoryScreen() {
  const { isDark, viewRTLStyle, isRTL } = useValues();
  const navigation = useAppNavigation();
  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 { translateData } = useSelector((state: any) => state.setting);

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

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

  const [loading, setLoading] = useState(true);

  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={[
        external.fx_1,
        {
          backgroundColor: isDark ? appColors.solidBorder : appColors.lightGray,
        },
      ]}
    >
      <HeaderContainer
        value={translateData?.services}
        lastIcon={
          <View
            style={[
              styles.box,
              {
                backgroundColor: isDark
                  ? appColors.darkHeader
                  : appColors.lightGray,
                flexDirection: viewRTLStyle,
                marginHorizontal: isRTL
                  ? Platform.OS === "ios"
                    ? windowHeight(35)
                    : windowHeight(62)
                  : 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>
        }
      />

      <ScrollView
        contentContainerStyle={[external.Pb_10]}
        showsVerticalScrollIndicator={false}
        style={[
          commonStyles.flexContainer,
          { paddingTop: windowHeight(10) },
          {
            backgroundColor: isDark
              ? appColors.solidBorder
              : appColors.lightGray,
          },
        ]}
      >
        <CategoryDetail />
      </ScrollView>
    </SafeAreaView>
  );
}
