import React, { useState, useEffect, useCallback, useRef } from "react";
import {
  Image,
  Keyboard,
  Platform,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
} from "react-native";
import Swiper from "react-native-swiper";
import DropDownPicker from "react-native-dropdown-picker";
import { useDispatch, useSelector } from "react-redux";
import { useFocusEffect } from "@react-navigation/native";
import { getValue, setValue } from "@src/utils/localstorage";
import {
  languageDataGet,
  settingDataGet,
  taxidosettingDataGet,
  translateDataGet,
} from "@src/api/store/actions";
import { useAppNavigation } from "@src/utils/navigation";
import { styles } from "./styles";
import { external } from "../../../styles/externalStyle";
import { appColors, windowHeight, windowWidth } from "@src/themes";
import { useValues } from "@src/utils/context/index";
import { AppDispatch } from "@src/api/store";

export function Onboarding() {
  const dispatch = useDispatch<AppDispatch>();
  const { navigate } = useAppNavigation();
  const swiperRef = useRef<Swiper | null>(null);

  const { settingData, languageData, taxidoSettingData, translateData } =
    useSelector((state: any) => state.setting);

  const { isDark, bgFullStyle, textColorStyle, setIsRTL, viewRTLStyle, isRTL } =
    useValues();
  const [open, setOpen] = useState(false);
  const [selectedLanguage, setSelectedLanguage] = useState<string | null>(null);
  const [items, setItems] = useState<
    { label: string; value: string; icon: () => JSX.Element }[]
  >([]);

  useFocusEffect(
    useCallback(() => {
      dispatch(languageDataGet());
      dispatch(settingDataGet());
      dispatch(translateDataGet());
      dispatch(taxidosettingDataGet());
    }, [dispatch])
  );

  useEffect(() => {
    const setDefaultLanguage = async () => {
      const defaultLang =
        settingData?.values?.general?.default_language?.locale;
      await setValue("defaultLanguage", defaultLang);
    };
    setDefaultLanguage();
  }, [settingData]);

  useEffect(() => {
    const loadLanguage = async () => {
      try {
        const storedLang = await getValue("selectedLanguage");
        if (storedLang) {
          setSelectedLanguage(storedLang);
          return;
        }

        const defaultLangObj = settingData?.values?.general?.default_language;
        if (!defaultLangObj?.locale) return;

        const defaultLang = defaultLangObj.locale;
        const matchingLang = languageData?.data?.find(
          (lang: any) => lang.locale === defaultLang
        );

        if (matchingLang) {
          setSelectedLanguage(matchingLang.locale);
          await setValue("selectedLanguage", matchingLang.locale);
        }
      } catch (error) {}
    };
    loadLanguage();
  }, [settingData, languageData]);

  // Format dropdown items
  useEffect(() => {
    if (languageData?.data) {
      const formattedItems = languageData.data.map((lang: any) => ({
        label: lang.name,
        value: lang.locale,
        icon: () => (
          <Image source={{ uri: lang.flag }} style={styles.flagImage} />
        ),
      }));
      setItems(formattedItems);
    }
  }, [languageData]);

  // Handle language selection
  const handleLanguageChange = async (selectedValue: string | null) => {
    if (!selectedValue) return;
    setSelectedLanguage(selectedValue);

    // Handle RTL
    setIsRTL(selectedValue === "ar");

    try {
      await setValue("selectedLanguage", selectedValue);
      dispatch(settingDataGet());
      dispatch(translateDataGet());
      dispatch(taxidosettingDataGet());
    } catch (error) {}
  };

  const handleNavigation = () => {
    navigate("SignIn");
  };

  const handleNext = (index: number) => {
    if (index < taxidoSettingData?.cabbooking_values?.onboarding?.length - 1) {
      swiperRef?.current?.scrollBy(1);
    } else {
      handleNavigation();
    }
  };

  return (
    <View style={{ flex: 1 }}>
      <View
        style={[
          styles.headerView,
          {
            backgroundColor: bgFullStyle,
          },
        ]}
      ></View>
      <View
        style={{
          position: "absolute",
          marginTop: windowHeight(15),
          marginHorizontal: windowWidth(8),
          alignSelf: isRTL ? "flex-end" : "flex-start",
        }}
      >
        <DropDownPicker
          open={open}
          value={selectedLanguage}
          items={items}
          setOpen={setOpen}
          setValue={async (callback) => {
            const selectedValue =
              callback instanceof Function
                ? callback(selectedLanguage)
                : callback;
            if (!selectedValue) return;
            handleLanguageChange(selectedValue);
          }}
          setItems={setItems}
          placeholder={selectedLanguage ? undefined : "Language"}
          dropDownContainerStyle={[
            styles.dropdownManu,
            { backgroundColor: bgFullStyle },
          ]}
          labelStyle={[styles.labelStyle, { color: textColorStyle }]}
          containerStyle={styles.dropdownContainer}
          style={styles.dropdown}
          textStyle={{ color: textColorStyle }}
          theme={isDark ? "DARK" : "LIGHT"}
          arrowIconContainerStyle={{
            justifyContent: "center",
            alignItems: "center",
            paddingTop: windowHeight(3.3),
          }}
        />
      </View>

      <Swiper
        loop={false}
        ref={swiperRef}
        activeDotStyle={[
          styles.activeStyle,
          {
            marginTop:
              Platform.OS === "ios" ? windowHeight(25) : windowHeight(45),
          },
        ]}
        removeClippedSubviews={true}
        dotColor={isDark ? appColors.dotDark : appColors.dotLight}
        dotStyle={[
          styles.dotStyles,
          {
            marginTop:
              Platform.OS === "ios" ? windowHeight(25) : windowHeight(45),
          },
        ]}
        paginationStyle={styles.paginationStyle}
      >
        {taxidoSettingData?.cabbooking_values?.onboarding?.map(
          (slide: any, index: number) => (
            <TouchableWithoutFeedback
              key={index}
              onPress={() => {
                setOpen(false);
                Keyboard.dismiss();
              }}
            >
              <View
                style={[
                  styles.slideContainer,
                  {
                    backgroundColor: isDark
                      ? appColors.bgDark
                      : appColors.lightGray,
                  },
                ]}
              >
                <View
                  style={{
                    height:
                      Platform.OS === "ios"
                        ? windowHeight(280)
                        : windowHeight(350),
                  }}
                >
                  <Image
                    style={styles.imageBackground}
                    source={{ uri: slide?.onboarding_image_url }}
                  />
                </View>
                <View
                  style={[
                    styles.imageBgView,
                    {
                      backgroundColor: isDark
                        ? appColors.bgDark
                        : appColors.lightGray,
                    },
                  ]}
                >
                  <View
                    style={[
                      styles.box,
                      {
                        backgroundColor: isDark
                          ? appColors.bgDark
                          : appColors.whiteColor,
                      },
                      {
                        paddingBottom:
                          Platform.OS == "ios"
                            ? windowHeight(22)
                            : windowHeight(15),
                      },
                    ]}
                  >
                    <View style={styles.line} />
                    <Text style={[styles.title, { color: textColorStyle }]}>
                      {slide?.title}
                    </Text>
                    <Text style={[styles.description, external.as_center]}>
                      {slide?.description}
                    </Text>

                    <View
                      style={{
                        justifyContent: "space-between",
                        alignItems: "center",
                        flexDirection: viewRTLStyle,
                        paddingHorizontal: windowWidth(25),
                      }}
                    >
                      <TouchableOpacity
                        style={[
                          styles.backArrow,
                          { backgroundColor: appColors.lightGray },
                        ]}
                        onPress={handleNavigation}
                        activeOpacity={0.7}
                      >
                        <Text
                          style={[styles.skipText, { color: textColorStyle }]}
                        >
                          {" "}
                          {translateData.skip}
                        </Text>
                      </TouchableOpacity>
                      <TouchableOpacity
                        style={styles.backArrow}
                        onPress={() => handleNext(index)}
                        activeOpacity={0.7}
                      >
                        <Text
                          style={[
                            styles.skipText,
                            { color: appColors.whiteColor },
                          ]}
                        >
                          {slide?.buttonName || "Next"}
                        </Text>
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </View>
            </TouchableWithoutFeedback>
          )
        )}
      </Swiper>
    </View>
  );
}
