import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  TextInput,
  ScrollView,
  Alert,
  ActivityIndicator,
  Platform,
  StatusBar,
  SafeAreaView
} from "react-native";
import useCreateOrderStore from "../../store/createOrder";
import BackIcon from "../../components/BackIcon";
import { useNavigation, useRoute, RouteProp } from "@react-navigation/native";
import { NativeStackNavigationProp } from "@react-navigation/native-stack";
import { useState, useEffect } from "react";
import useUserStore from "../../store/user";
import { Order } from "../../services/api/orders";
import { payApi } from "../../services/api/payApi";

// Define the param list for navigation
type RootStackParamList = {
  PreviewOrder: {
    data: Order;
    payMethod: string;
    currency: string;
    amount: number;
  };
  Pay: { payUrl: string };
};

export const PreviewOrder = () => {
  const { orderData, setOrderData } = useCreateOrderStore();
  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const [phoneNumber, setPhoneNumber] = useState("");
  const [showPhoneInput, setShowPhoneInput] = useState(false);
  const route = useRoute<RouteProp<RootStackParamList, "PreviewOrder">>();
  const [loading, setLoading] = useState(false);
  const { user } = useUserStore();

  useEffect(() => {
    if (!user.user_id) {
      return Alert.alert("检查您未登录");
    }
    if (route.params.payMethod === "Brainnel Pay(Mobile Money)") {
      setShowPhoneInput(true);
    } else {
      setShowPhoneInput(false);
    }
  }, [route.params.payMethod, user.user_id]);

  const handleSubmit = () => {
    if (showPhoneInput && !phoneNumber) {
      // Show error or alert if needed
      console.log("Phone number is required for Mobile Money");
      return;
    }

    console.log(route.params.currency);

    const data = {
      order_id: route.params.data.order_id,
      method: route.params.payMethod,
      currency: route.params.currency
        ? route.params.currency
        : route.params.data.currency,
      amount: route.params.data.actual_amount,
    };
    setLoading(true);

    payApi
      .getPayInfo(data)
      .then((res) => {
        if (res.success) {
          ``;
          navigation.navigate("Pay", {
            payUrl: res.payment_url,
          });
        }
      })
      .catch((err) => {
        setLoading(false);
        Alert.alert("支付失败");
      })
      .finally(() => {
        setLoading(false);
      });

    // navigation.navigate('Pay', {
    //   orderId: user.user_id,
    //   payMethod: route.params.payMethod,

    // })
  };

  return (
    <SafeAreaView style={[styles.safeArea]}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />
      <View style={styles.safeAreaContent}>
        <View style={styles.container}>
          <View style={styles.titleContainer}>
            <View style={styles.backIconContainer}>
              <TouchableOpacity onPress={() => navigation.goBack()}>
                <BackIcon size={20} />
              </TouchableOpacity>
            </View>

            <Text style={styles.titleHeading}>立即支付</Text>
          </View>

          <ScrollView style={styles.scrollContainer}>
            <View style={styles.mainContent}>
              {/* Payment Method Section */}
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>支付方式</Text>
                <View style={styles.paymentMethodContainer}>
                  <Text style={styles.paymentMethodText}>
                    {route.params.payMethod}
                  </Text>
                </View>

                {showPhoneInput && (
                  <View style={styles.phoneInputContainer}>
                    <Text style={styles.phoneInputLabel}>请输入手机号码</Text>
                    <TextInput
                      style={styles.phoneInput}
                      value={phoneNumber}
                      onChangeText={setPhoneNumber}
                      placeholder="输入手机号码"
                      keyboardType="phone-pad"
                    />
                  </View>
                )}
              </View>

              {/* Order Info Section */}
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>支付信息</Text>

                <View style={styles.infoRow}>
                  <Text style={styles.infoLabel}>姓名</Text>
                  <Text style={styles.infoValue}>
                    {route.params?.data.receiver_name || "N/A"}
                  </Text>
                </View>

                <View style={styles.infoRow}>
                  <Text style={styles.infoLabel}>手机号</Text>
                  <Text style={styles.infoValue}>
                    {route.params?.data.receiver_phone || "N/A"}
                  </Text>
                </View>

                {route.params.data?.whatsapp_number && (
                  <View style={styles.infoRow}>
                    <Text style={styles.infoLabel}>WhatsApp</Text>
                    <Text style={styles.infoValue}>
                      {route.params.data?.whatsapp_number}
                    </Text>
                  </View>
                )}

                <View style={styles.infoRow}>
                  <Text style={styles.infoLabel}>国家</Text>
                  <Text style={styles.infoValue}>
                    {route.params?.data.receiver_country || "N/A"}
                  </Text>
                </View>

                <View style={styles.infoRow}>
                  <Text style={styles.infoLabel}>收货地址</Text>
                  <Text style={styles.infoValue}>
                    {route.params?.data.receiver_address || "N/A"}
                  </Text>
                </View>

                <View style={styles.infoRow}>
                  <Text style={styles.infoLabel}>订单金额</Text>
                  <Text style={styles.infoValue}>
                    {route.params.data.actual_amount || "N/A"} {user.currency}
                  </Text>
                </View>

                <View style={styles.infoRow}>
                  <Text style={styles.infoLabel}>运费</Text>
                  <Text style={styles.infoValue}>
                    {(
                      route.params.data.domestic_shipping_fee +
                      route.params.data.shipping_fee
                    ).toFixed(2) || "N/A"}{" "}
                    {user.currency}
                  </Text>
                </View>
              </View>

              {/* Order Summary Section */}
              <View style={styles.section}>
                <Text style={styles.sectionTitle}>订单总额</Text>
                <View style={styles.totalRow}>
                  <Text style={styles.totalLabel}>总金额</Text>
                  <Text style={styles.totalValue}>
                    {route.params.amount} {route.params.currency}
                  </Text>
                </View>
              </View>
            </View>
          </ScrollView>

          <View style={styles.submitButtonContainer}>
            <TouchableOpacity
              style={[
                styles.primaryButtonStyle,
                (!showPhoneInput || (showPhoneInput && phoneNumber)) && !loading
                  ? {}
                  : styles.disabledButtonStyle,
              ]}
              onPress={handleSubmit}
              disabled={(showPhoneInput && !phoneNumber) || loading}
            >
              {loading ? (
                <ActivityIndicator size="small" color="#ffffff" />
              ) : (
                <Text style={styles.buttonText}>确认支付</Text>
              )}
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#fff',
  },
  safeAreaContent: {
    flex: 1,
    paddingTop: Platform.OS === 'android' ? 10 : 0,
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  scrollContainer: {
    flex: 1,
  },
  mainContent: {
    padding: 16,
  },
  submitButtonContainer: {
    paddingHorizontal: 16,
    paddingVertical: 20,
    backgroundColor: "white",
    borderTopWidth: 1,
    borderTopColor: "#eaeaea",
  },
  primaryButtonStyle: {
    width: "100%",
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#002fa7",
    borderRadius: 25,
    shadowColor: "#002fa7",
    shadowOffset: { width: 0, height: 3 },
    shadowOpacity: 0.2,
    shadowRadius: 5,
    elevation: 5,
  },
  buttonText: {
    color: "white",
    fontWeight: "600",
    fontSize: 16,
    fontFamily: "PingFang SC",
  },
  disabledButtonStyle: {
    backgroundColor: "#c0c0c0",
    shadowOpacity: 0,
  },
  titleContainer: {
    width: "100%",
    padding: 16,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
    backgroundColor: "#fff",
    borderBottomWidth: 1,
    borderBottomColor: "#eaeaea",
  },
  backIconContainer: {
    position: "absolute",
    left: 16,
  },
  titleHeading: {
    fontWeight: "600",
    fontSize: 18,
    color: "#333",
    fontFamily: "PingFang SC",
  },
  section: {
    backgroundColor: "#fff",
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 2,
    elevation: 2,
  },
  sectionTitle: {
    fontSize: 17,
    fontWeight: "600",
    color: "#333",
    marginBottom: 16,
    fontFamily: "PingFang SC",
  },
  paymentMethodContainer: {
    backgroundColor: "#f8f8f8",
    padding: 12,
    borderRadius: 8,
    borderLeftWidth: 4,
    borderLeftColor: "#002fa7",
  },
  paymentMethodText: {
    fontSize: 15,
    color: "#333",
    fontFamily: "PingFang SC",
  },
  phoneInputContainer: {
    marginTop: 16,
  },
  phoneInputLabel: {
    fontSize: 15,
    color: "#666",
    marginBottom: 8,
    fontFamily: "PingFang SC",
  },
  phoneInput: {
    borderWidth: 1,
    borderColor: "#ddd",
    borderRadius: 8,
    padding: 12,
    fontSize: 15,
    backgroundColor: "#fff",
    fontFamily: "PingFang SC",
  },
  infoRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: "#f0f0f0",
  },
  infoLabel: {
    fontSize: 15,
    color: "#666",
    fontFamily: "PingFang SC",
  },
  infoValue: {
    fontSize: 15,
    color: "#333",
    textAlign: "right",
    maxWidth: "60%",
    fontFamily: "PingFang SC",
  },
  totalRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 12,
  },
  totalLabel: {
    fontSize: 16,
    fontWeight: "600",
    color: "#333",
    fontFamily: "PingFang SC",
  },
  totalValue: {
    fontSize: 20,
    fontWeight: "700",
    color: "#002fa7",
    fontFamily: "PingFang SC",
  },
});
