import { View, Text, StyleSheet, TouchableOpacity, Image, SafeAreaView, StatusBar, Platform } from "react-native";
import BackIcon from "../../components/BackIcon";
import fontSize from "../../utils/fontsizeUtils";
import { useNavigation, useRoute, RouteProp } from "@react-navigation/native";
import { NativeStackNavigationProp } from "@react-navigation/native-stack";
import { RootStackParamList } from "../../navigation/types";
import { useState, useEffect } from "react";
import { settingApi, Country } from "../../services/api/setting";
import { FlatList } from "react-native";
import flagMap from "../../utils/flagMap";
import CheckIcon from "../../components/CheckIcon";
import Toast from "react-native-toast-message";
import { eventBus } from "../../utils/eventBus";
import { changeLanguage } from "../../i18n";
import { useTranslation } from "react-i18next";

// Define CountryList type to match API response
type CountryList = {
  country: number;
  currency: string;
  language: string;
  name: string;
  name_en: string;
  timezone: string;
  user_count: number;
  valid_digits: number[];
};

export const CountrySetting = () => {
  const { t } = useTranslation();
  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const route = useRoute<RouteProp<RootStackParamList, "CountrySetting">>();
  const [changeType, setChangeType] = useState<string>("country");
  const [countryList, setCountryList] = useState<CountryList[]>([]);
  const [currencyList, setCurrencyList] = useState<string[]>([]);
  const [languageList, setLanguageList] = useState<string[]>([]);
  const [country, setCountry] = useState<number>(0);
  const [currency, setCurrency] = useState<string>("");
  const [language, setLanguage] = useState<string>("");
  const getCountry = async () => {
    const res = await settingApi.getCountryList();
    setCountryList(res);    
    setCountry(route.params?.mySetting?.country || 0);
  };

  const getCurrency = async () => {
    const res = await settingApi.getCurrencyList();
    setCurrencyList(res);
    setCurrency(route.params?.mySetting?.currency || "");
  };

  const getLanguage = async () => {
    const res = await settingApi.getLanguageList();
    setLanguageList(res);
    setLanguage(route.params?.mySetting?.language || "");
  };

  useEffect(() => {
    getCountry();
    getCurrency();
    getLanguage();
  }, []);

  const putSettinghandel = async () => {
    // Only include the property that corresponds to the active tab
    let data = {};
    
    if (changeType === "country") {
      data = { country: country };
    } else if (changeType === "currency") {
      data = { currency: currency };
    } else if (changeType === "language") {
      data = { language: language };
    }
    
    Toast.show({
      text1: t('setting.success'),
      type: "success",
      visibilityTime: 1000,
    });
    await settingApi.putSetting(data);
    if (changeType === "language" && language) {
      await changeLanguage(language);
    }
    eventBus.emit("refreshSetting");
  };
  return (
    <SafeAreaView style={styles.safeArea}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />
      <View style={styles.safeAreaContent}>
        <View style={styles.header}>
          <TouchableOpacity
            onPress={() => navigation.goBack()}
            style={styles.backButton}
          >
            <BackIcon size={fontSize(24)} />
          </TouchableOpacity>
          <Text style={styles.title}>{t('setting.title')}</Text>
          <View style={styles.placeholder} />
        </View>
        <View style={styles.changeType}>
          <TouchableOpacity
            style={[
              styles.changeTypeText,
              changeType === "country" && styles.changeTypeTextActive,
            ]}
            onPress={() => setChangeType("country")}
          >
            <Text style={styles.changeTypeTextTitle}>{t('setting.country')}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              styles.changeTypeText,
              changeType === "currency" && styles.changeTypeTextActive,
            ]}
            onPress={() => setChangeType("currency")}
          >
            <Text style={styles.changeTypeTextTitle}>{t('setting.currency')}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              styles.changeTypeText,
              changeType === "language" && styles.changeTypeTextActive,
            ]}
            onPress={() => setChangeType("language")}
          >
            <Text style={styles.changeTypeTextTitle}>{t('setting.language')}</Text>
          </TouchableOpacity>
        </View>
        {changeType === "country" && (
          <View style={styles.countryList}>
            <FlatList
              keyExtractor={(item) => String(item.name)}
              data={countryList}
              showsVerticalScrollIndicator={false}
              showsHorizontalScrollIndicator={false}
              renderItem={({ item }) => (
                <TouchableOpacity
                  key={item.country}
                  style={styles.countryItem}
                  onPress={() => {
                    setCountry(item.country);
                  }}
                >
                  <View style={styles.countryItemContent}>
                    <Image
                      source={flagMap.get(item.name_en)}
                      style={styles.countryFlag}
                    />
                    <Text>{item.name_en} {item.country}</Text>
                  </View>
                  <View>
                    {country === item.country && (
                      <CheckIcon size={fontSize(24)} color="#ff611a" />
                    )}
                  </View>
                </TouchableOpacity>
              )}
            />
          </View>
        )}
        {changeType === "currency" && (
          <View style={styles.countryList}>
            <FlatList
              keyExtractor={(item) => item}
              showsVerticalScrollIndicator={false}
              showsHorizontalScrollIndicator={false}
              data={currencyList}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={styles.countryItem}
                  onPress={() => setCurrency(item)}
                >
                  <View style={styles.countryItemContent}>
                    <View>
                      <Text>{item}</Text>
                    </View>
                  </View>
                  <View>
                    {currency === item && (
                      <CheckIcon size={fontSize(24)} color="#ff611a" />
                    )}
                  </View>
                </TouchableOpacity>
              )}
            />
          </View>
        )}
        {changeType === "language" && (
          <View style={styles.countryList}>
            <FlatList
              keyExtractor={(item) => item}
              showsVerticalScrollIndicator={false}
              showsHorizontalScrollIndicator={false}
              data={languageList}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={styles.countryItem}
                  onPress={() => setLanguage(item)}
                >
                  <View style={styles.countryItemContent}>
                    <Text>{item}</Text>
                  </View>
                  <View>
                    {language === item && (
                      <CheckIcon size={fontSize(24)} color="#ff611a" />
                    )}
                  </View>
                </TouchableOpacity>
              )}
            />
          </View>
        )}
        <TouchableOpacity style={styles.bottomButton} onPress={putSettinghandel}>
          <Text style={styles.buttonText}>{t('setting.confirm')}</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#fff',
  },
  safeAreaContent: {
    flex: 1,
    paddingTop: 0,
  },
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  header: {
    paddingInline: 20,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    backgroundColor: "white",
    width: "100%",
    paddingVertical: 15,
    borderBottomWidth: 1,
    borderBottomColor: "#e9ecef",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  backButton: {
    width: fontSize(24),
  },
  title: {
    fontSize: fontSize(20),
    fontWeight: "600",
    flex: 1,
    textAlign: "center",
  },
  placeholder: {
    width: fontSize(24),
  },
  changeType: {
    backgroundColor: "white",
    width: "100%",
    marginBottom: 20,
    flexDirection: "row",
    alignItems: "center",
  },
  changeTypeText: {
    width: "33%",
    paddingVertical: 15,
  },
  changeTypeTextTitle: {
    fontSize: fontSize(16),
    color: "#343a40",
    fontFamily: "PingFangSC-Medium",
    textAlign: "center",
    fontWeight: "600",
  },
  changeTypeTextActive: {
    borderBottomWidth: 2,
    borderBottomColor: "#ff611a",
    color: "#ff611a",
  },
  countryList: {
    backgroundColor: "white",
    borderRadius: 10,
    marginHorizontal: 20,
    marginBottom: 70,
  },
  countryItem: {
    paddingVertical: 12,
    borderBottomWidth: 1,
    paddingHorizontal: 10,
    borderBottomColor: "#e9ecef",
    fontSize: fontSize(16),
    fontFamily: "PingFangSC-Medium",
    fontWeight: "600",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  countryFlag: {
    width: 24,
    height: 24,
    marginRight: 10,
    borderRadius: 12,
  },
  countryItemContent: {
    flexDirection: "row",
    alignItems: "center",
  },
  bottomButton: {
    position: "absolute",
    bottom: 0,
    left: 0,
    right: 0,
    height: 60,
    backgroundColor: "#ffff",
    justifyContent: "center",
    alignItems: "center",
    padding: 10,
    borderTopWidth: 1,
    borderTopColor: "#e9ecef",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: -2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 5,
  },
  buttonText: {
    fontSize: fontSize(18),
    fontWeight: "600",
    width: "90%",
    backgroundColor: "#ff611a",
    color: "white",
    textAlign: "center",
    paddingVertical: 10,
    borderRadius: 10,
  },
});
