import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  ScrollView,
  Image,
  Alert,
  Linking,
} from "react-native";
import BackIcon from "../../components/BackIcon";
import MassageIcon from "../../components/MassageIcon";
import fontSize from "../../utils/fontsizeUtils";
import { useNavigation } from "@react-navigation/native";
import { NativeStackNavigationProp } from "@react-navigation/native-stack";
import { useRoute, RouteProp } from "@react-navigation/native";
import { ordersApi, OrderDetailsType } from "../../services/api/orders";
import OrderIcon from "../../components/OrderIcon";
import InfoIcon from "../../components/InfoIcon";
import Progress from "./Progress";
import AddressIcon from "../../components/AddressIcon";
import EditIcon from "../../components/ColorfulEditIcon";
import BrightnessIcon from "../../components/BrightnessIcon";
import PhoneIcon from "../../components/PhoneIcon";
import WatchAppIcon from "../../components/watchAppIcon";
import ShoppingBagIcon from "../../components/ShoppingBagIcon";
import PowerIcon from "../../components/PowerIcon";
import CardIcon from "../../components/ShoppingCartIcon";
import { useOrderListStore } from "../../store/orderList";
export const OrderDetails = () => {
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const route = useRoute<
    RouteProp<
      {
        OrderDetails: {
          orderId: string;
        };
      },
      "OrderDetails"
    >
  >();
  const [orderDetails, setOrderDetails] = useState<OrderDetailsType>();
  const [isLoading, setIsLoading] = useState(true);
  const { deleteOrder, changeOrder,updateOrderShippingInfo } = useOrderListStore();
  const getOrderDetails = async () => {
    try {
      setIsLoading(true);
      const response = await ordersApi.getOrderDetails(route.params.orderId);
      setOrderDetails(response);
    } catch (error) {
      console.error("Error fetching order details:", error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    getOrderDetails();
  }, []);
  //拨打电话
  const callPhone = async (phoneNumber: string) => {
    const url = `tel:${phoneNumber}`;

    try {
      await Linking.openURL(url); // 直接尝试打开拨号界面
    } catch (error) {
      Alert.alert("错误", "无法打开拨号界面");
      console.error("拨号失败:", error);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <BackIcon />
        </TouchableOpacity>
        <Text style={styles.title}>订单详情</Text>
        <MassageIcon size={22} />
      </View>
      {isLoading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#f77f3a" />
        </View>
      ) : orderDetails ? (
        <View style={styles.container}>
          <ScrollView
            showsVerticalScrollIndicator={false}
            style={{ flex: 1 }}
            contentContainerStyle={{ paddingBottom: 70 }}
          >
            <View style={styles.orderStatus}>
              <View style={styles.orderStatusContent}>
                <View style={styles.orderStatusTitle}>
                  <OrderIcon size={20} color="#3D3D3D" />
                  <Text style={styles.orderStatusTitleText}>订单状态</Text>
                </View>

                <View style={styles.orderStatusContentPreview}>
                  <Progress
                    statuses={orderDetails.order_status}
                    labels={["待付款", "待发货", "运送中", "待收货", "已完成"]}
                  />
                </View>
              </View>
            </View>
            {/* 订单信息 */}
            <View style={styles.orderStatus}>
              <View style={styles.orderStatusContent}>
                <View style={styles.orderStatusTitle}>
                  <InfoIcon size={20} color="#3D3D3D" />
                  <Text style={styles.orderStatusTitleText}>订单信息</Text>
                </View>
                <View style={styles.orderStatusContentPreview}>
                  <View style={styles.orderId}>
                    <Text style={styles.orderIdText}>Order ID</Text>
                    <Text style={styles.orderIdText1}>
                      {orderDetails.order_id}
                    </Text>
                  </View>
                  <View style={styles.orderId}>
                    <Text style={styles.orderIdText}>Order Date</Text>
                    <Text style={styles.orderIdText1}>
                      {orderDetails.create_time}
                    </Text>
                  </View>
                  <View style={styles.orderId}>
                    <Text style={styles.orderIdText}>Shipping Method</Text>
                    <Text style={styles.orderIdText1}>
                      {orderDetails.shipping_fee}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
            {/* 配送信息 */}
            <View style={styles.orderStatus}>
              <View style={styles.orderStatusContent}>
                <View style={styles.orderStatusTitle}>
                  <AddressIcon size={22} color={"#3D3D3D"} />
                  <Text style={styles.orderStatusTitleText}>配送信息</Text>
                </View>
                <View style={styles.orderStatusContentPreview}>
                  <View style={styles.orderStatusContentPreviewInformation}>
                    <View style={styles.warehouse}>
                      <View style={styles.recipientTitle}>
                        <Text
                          style={
                            styles.orderStatusContentPreviewInformationText
                          }
                        >
                          Warehouse
                        </Text>
                      </View>
                      <View style={styles.recipientTitle}>
                        <EditIcon size={22} />
                      </View>
                      <View style={styles.recipientTitle}>
                        <Text>{orderDetails.receiver_address}</Text>
                      </View>
                      <View style={styles.recipientTitle}>
                        <View style={styles.warehousePhone}>
                          <View style={styles.warehousePhoneTextContainer}>
                            <BrightnessIcon size={16} color="#3D3D3D" />
                          </View>
                          <View style={styles.warehousePhoneTextContainer}>
                            <Text style={styles.warehousePhoneText}>
                              付款后联系方式
                            </Text>
                          </View>
                        </View>
                      </View>
                    </View>

                    <View style={styles.recipient}>
                      <View style={styles.recipientTitle}>
                        <Text
                          style={
                            styles.orderStatusContentPreviewInformationText
                          }
                        >
                          Recipient
                        </Text>
                      </View>
                      <View style={styles.recipientTitle}>
                        <EditIcon size={22} />
                      </View>
                      {/* 姓名 */}
                      <View style={styles.recipientTitle}>
                        <Text style={styles.recipientName}>
                          {orderDetails.receiver_name}
                        </Text>
                      </View>

                      {/* 电话 */}
                      <View style={styles.recipientTitle}>
                        <View style={styles.recipientPhoneContainer}>
                          <PhoneIcon size={16} color="#3D3D3D" />
                          <Text style={styles.recipientPhone}>
                            {orderDetails.receiver_phone}
                          </Text>
                        </View>
                      </View>
                      {/* watchApp */}
                      <View style={styles.recipientTitle}>
                        <View style={styles.recipientPhoneContainer}>
                          <WatchAppIcon size={16} />
                          <Text style={styles.recipientPhone}>WhatsApp:</Text>
                          <Text style={styles.recipientPhone}>
                            {orderDetails.receiver_phone}
                          </Text>
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            </View>
            {/* 商品信息 */}
            <View style={styles.orderStatus}>
              <View style={styles.orderStatusContent}>
                <View style={styles.orderStatusTitle}>
                  <ShoppingBagIcon size={16} color="#3D3D3D" />
                  <Text style={styles.orderStatusTitleText}>
                    商品信息 ({orderDetails.items.length})
                  </Text>
                </View>
                <View style={styles.orderStatusContentPreview}>
                  {orderDetails.items.map((item, index) => (
                    <View style={styles.productItem} key={index}>
                      <View style={styles.productItemImage}>
                        <Image
                          source={{ uri: item.product_image }}
                          style={{ width: "100%", height: "100%" }}
                        />
                      </View>
                      <View style={styles.productItemInfo}>
                        <View style={styles.productItemInfoName}>
                          <Text style={styles.productItemInfoNameText}>
                            {item.product_name}
                          </Text>
                        </View>
                        <View style={styles.productItemInfoSku}>
                          {item.sku_attributes.map((sku, index) => (
                            <Text
                              key={index}
                              style={styles.productItemInfoSkuText}
                            >
                              {sku.attribute_name}:{sku.attribute_value}
                            </Text>
                          ))}
                          {/* <text>{item.product_name}</text> */}
                        </View>
                        <View style={styles.productItemInfoPrice}>
                          <Text
                            style={{
                              color: "#f77f3a",
                              fontSize: fontSize(16),
                              fontWeight: "600",
                            }}
                          >
                            {item.total_price}
                          </Text>
                        </View>
                      </View>
                      <View style={styles.productItemNum}>
                        <Text style={styles.productItemNumText}>
                          x{item.quantity}
                        </Text>
                      </View>
                    </View>
                  ))}
                </View>
                <View style={styles.dottedLine}></View>

                <View style={styles.orderStatusContentPreview}>
                  <TouchableOpacity style={styles.addCard}>
                    <View style={styles.addCardBox}>
                      <CardIcon size={16} color="#0098ef" />
                      <Text style={styles.addCardText}>Add All to Card</Text>
                    </View>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
            {/* 价格信息 */}
            <View style={styles.orderStatus}>
              <View style={styles.orderStatusContent}>
                <View style={styles.orderStatusTitle}>
                  <PowerIcon size={20} color="#3D3D3D" />
                  <Text style={styles.orderStatusTitleText}>价格详情</Text>
                </View>
                <View style={styles.orderStatusContentPreview}>
                  <View style={styles.orderId}>
                    <Text style={styles.orderIdText}>Subtotal</Text>
                    <Text style={styles.orderIdText1}>
                      {orderDetails.total_amount}
                    </Text>
                  </View>
                  <View style={styles.orderId}>
                    <Text style={styles.orderIdText}>
                      Platform Shipping Fee
                    </Text>
                    <Text style={styles.orderIdText1}>
                      {orderDetails.shipping_fee}
                    </Text>
                  </View>
                  <View style={styles.orderId}>
                    <Text style={styles.orderIdText}>
                      International Shipping Fee
                    </Text>
                    <Text style={styles.orderIdText1}>
                      {orderDetails.shipping_fee}
                    </Text>
                  </View>
                  <View style={styles.dottedLine}></View>
                  <View style={styles.orderId}>
                    <Text style={styles.TotalText}>Total</Text>
                    <Text style={styles.TotalPrice}>
                      {orderDetails.total_amount}
                    </Text>
                  </View>
                  <View>
                    <Text style={styles.orderRemakeText}>
                      + ${orderDetails.shipping_fee} estimated international fee
                      (COD)
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          </ScrollView>
          {/* 代付款 */}
          {orderDetails.order_status === 0 && (
            <View style={styles.bottomButtons}>
              <TouchableOpacity
                style={styles.bottomButton1}
                onPress={() => {
                  deleteOrder(route.params.orderId);
                }}
              >
                <Text style={styles.bottomButtonText1}>取消订单</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.bottomButton}
                onPress={() => {
                  navigation.navigate("Pay", {
                    order_id: route.params.orderId,
                  });
                }}
              >
                <Text style={styles.bottomButtonText}>付款</Text>
              </TouchableOpacity>
            </View>
          )}
          {/* 待发货 */}
          {orderDetails.order_status === 1 && (
            <View style={styles.bottomButtons}>
              <TouchableOpacity
                style={styles.bottomButton1}
                onPress={() => {
                  callPhone("15903995548");
                }}
              >
                <Text style={styles.bottomButtonText1}>联系货代中心</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.bottomButton}
                onPress={() => {
                  changeOrder(route.params.orderId, 2);
                  navigation.goBack();
                }}
              >
                <Text style={styles.bottomButtonText}>取消订单</Text>
              </TouchableOpacity>
            </View>
          )}
          {/* 代收货 */}
          {orderDetails.order_status === 2 && (
            <View style={styles.bottomButtons}>
              <TouchableOpacity style={styles.bottomButton1} onPress={() => {}}>
                <Text style={styles.bottomButtonText1}>查询物流</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.bottomButton}
                onPress={() => {
                  updateOrderShippingInfo(route.params.orderId,{
                    shipping_status: 0,
                    shipping_info: {
                      shipping_company: "string",
                      shipping_no: "string",
                      shipping_info: {}
                    }
                  }); 
                  navigation.goBack();
                }}
              >
                <Text style={styles.bottomButtonText}>确认收货</Text>
              </TouchableOpacity>
            </View>
          )}
          {/* 已完成 */}
          {orderDetails.order_status === 3 && (
            <View style={styles.bottomButtons}>
              <TouchableOpacity
                style={styles.bottomButton1}
                onPress={() => {
                  deleteOrder(route.params.orderId);
                  navigation.goBack();
                }}
              >
                <Text style={styles.bottomButtonText1}>Cancel Order</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.bottomButton}>
                <Text style={styles.bottomButtonText}>Pay Now</Text>
              </TouchableOpacity>
            </View>
          )}
          {/* 已取消 */}
          {orderDetails.order_status === 4 && (
            <View style={styles.bottomButtons}>
              <TouchableOpacity style={styles.bottomButton1} onPress={() => {}}>
                <Text style={styles.bottomButtonText1}>添加到购物车</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.bottomButton}>
                <Text style={styles.bottomButtonText}>重新下单</Text>
              </TouchableOpacity>
            </View>
          )}
        </View>
      ) : (
        <Text>无法加载订单状态</Text>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f8f9fa",
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 16,
    backgroundColor: "#fff",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 3,
  },
  title: {
    fontSize: fontSize(16),
    fontWeight: "600",
  },
  orderStatus: {
    paddingInline: 16,
    marginTop: 10,
  },
  orderStatusContent: {
    backgroundColor: "#fff",
    borderRadius: 16,
  },
  orderStatusTitle: {
    flexDirection: "row",
    alignItems: "center",
    borderBottomWidth: 1,
    borderColor: "#f5f5f5",
    padding: 10,
  },
  orderStatusTitleText: {
    fontSize: fontSize(16),
    fontWeight: "600",
    marginLeft: 10,
  },
  orderStatusContentPreview: {
    padding: 10,
    justifyContent: "center",
  },
  productItem: {
    flexDirection: "row",
    width: "100%",
    borderBottomWidth: 1,
    borderColor: "#f5f5f5",
    padding: 10,
  },
  productItemImage: {
    width: "15%",
    height: 50,
    borderRadius: 10,
  },
  productItemInfo: {
    width: "75%",
    justifyContent: "space-between",
    paddingLeft: 10,
  },
  productItemNum: {
    width: "10%",
    alignItems: "center",
    justifyContent: "flex-end",
  },
  productItemNumText: {
    fontSize: fontSize(16),
    color: "#999",
  },
  productItemInfoName: {
    width: "100%",
    paddingVertical: 5,
  },
  productItemInfoNameText: {
    fontSize: fontSize(13),
    fontWeight: "600",
  },
  productItemInfoSkuText: {
    fontSize: fontSize(13),
    color: "#999",
  },
  productItemInfoSku: {
    width: "100%",
    paddingVertical: 5,
  },
  productItemInfoPrice: {
    width: "100%",
    paddingVertical: 5,
  },
  orderStatusContentPreviewInformation: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: "100%",
  },

  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  orderId: {
    flexDirection: "row",
    justifyContent: "space-between",
    paddingVertical: 10,
    width: "100%",
  },
  orderIdText: {
    color: "#999",
    width: "50%",
  },
  orderIdText1: {
    width: "50%",
    textAlign: "right",
  },
  TotalText: {
    color: "#f77f3a",
    fontSize: fontSize(18),
    fontWeight: "600",
    width: "50%",
  },
  TotalPrice: {
    color: "#f77f3a",
    fontSize: fontSize(18),
    fontWeight: "600",
    width: "50%",
    textAlign: "right",
  },
  warehouse: {
    width: "50%",
  },
  recipientTitle: {
    paddingVertical: 5,
  },
  recipientPhoneContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  recipient: {
    width: "50%",
  },
  orderStatusContentPreviewInformationText: {
    fontSize: fontSize(16),
    fontWeight: "600",
  },
  warehousePhone: {
    padding: 5,
    backgroundColor: "#f9f9f9",
    borderRadius: 10,
    width: "90%",
    flexDirection: "row",
    alignItems: "center",
  },
  warehousePhoneText: {
    fontSize: fontSize(14),
    fontWeight: "400",
    color: "#3D3D3D",
  },
  warehousePhoneTextContainer: {
    paddingRight: 5,
  },
  recipientName: {
    fontSize: fontSize(16),
    fontWeight: "600",
  },
  recipientPhone: {
    fontSize: fontSize(14),
    fontWeight: "400",
    color: "#3D3D3D",
  },
  dottedLine: {
    width: "100%",
    borderBottomWidth: 2,
    borderColor: "#f5f5f5",
    borderStyle: "dashed",
  },
  orderRemakeText: {
    fontSize: fontSize(14),
    fontWeight: "400",
    color: "#999",
  },
  addCard: {
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
  },
  addCardBox: {
    padding: 10,
    borderWidth: 1,
    borderColor: "#0098ef",
    borderRadius: 10,
    backgroundColor: "#e2f2fd",
    opacity: 0.5,
    flexDirection: "row",
    alignItems: "center",
  },
  addCardText: {
    fontSize: fontSize(16),
    fontWeight: "600",
    color: "#0098ef",
    marginLeft: 5,
  },
  bottomButtons: {
    position: "absolute",
    bottom: 0,
    width: "100%",
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    padding: 10,
    backgroundColor: "#fff",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: -4,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 3,
  },
  bottomButton1: {
    padding: 10,
    marginHorizontal: 10,
    alignItems: "center",
    backgroundColor: "#f0f0f0",
    borderRadius: 5,
    flex: 1,
  },
  bottomButton: {
    padding: 10,
    marginHorizontal: 10,
    alignItems: "center",
    backgroundColor: "#fe7f42",
    borderRadius: 5,
    flex: 1,
  },
  bottomButtonText: {
    fontSize: fontSize(18),
    fontWeight: "600",
    color: "#fff",
  },
  bottomButtonText1: {
    fontSize: fontSize(18),
    fontWeight: "600",
    color: "#999",
  },
});
