import {
  View,
  Text,
  FlatList,
  RefreshControl,
  Modal,
  TouchableOpacity,
  Image as NativeImage,
  Alert,
} from "react-native";
import { Image } from "expo-image";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Empty from "../../../components/Empty";
import { ListItem, Button } from "@rneui/themed";
import baseRequest from "../../../utils/baseRequest";
import Toast from "react-native-toast-message";
import * as Clipboard from "expo-clipboard";
import { generateSignature } from "../../../utils/crypto";

export default function HaveNotAddWechat({}) {
  const blurhash = "LcKUTa%gOYWBYRt6xuoJo~s8V@fk";

  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  //保存获取的订单列表
  const [orderList, setOrderList] = useState([]);
  const [offset, setOffset] = useState(0);
  const [more, setMore] = useState(1);
  //获取订单数据
  const getOrderList = async (top = false) => {
    if (!more && top === false) return;
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const signature = await generateSignature({
        tab: 1,
        offset: top ? 0 : offset,
        limit: 20,
        ...base,
      });
      const response = await fetch(
        `${apiUrl}/api/vas/get_add_wechat_list?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            tab: 1,
            offset: top ? 0 : offset, //如果是下拉刷新则更新最新数据
            limit: 20,
            ...base,
          }),
        }
      );
      const data = await response.json();
      if (data.ret === -1) {
        Toast.show({
          type: "error",
          text1: data.msg,
          topOffset: 60,
        });
        return;
      }
      setOffset(data.data.offset);
      setMore(data.data.more);
      //如果是下拉刷新则更新最新数据
      if (top) {
        setOrderList(data.data.list);
        return;
      }
      setOrderList([...orderList, ...data.data.list]);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    getOrderList();
  }, []);

  //下拉刷新
  const [refreshing, setRefreshing] = useState(false);
  const handleRefresh = async () => {
    setRefreshing(true);
    await getOrderList(true);
    setRefreshing(false);
  };

  //二次确认组件
  const [isConfirmModalVisible, setIsConfirmModalVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState({});
  const ConfirmModal = () => {
    //保存内容到剪贴板
    const copy = async (data) => {
      await Clipboard.setStringAsync(data);
      Alert.alert(null, "复制成功");
    };
    //点击我已完成添加按钮
    const handleConfirm = async () => {
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      try {
        const base = await baseRequest();
        const signature = await generateSignature({
          order_id: currentOrder.order_id,
          ...base,
        });
        const response = await fetch(
          `${apiUrl}/api/vas/confirm_add_wechat?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              order_id: currentOrder.order_id,
              ...base,
            }),
          }
        );
        const data = await response.json();
        if (data.ret === -1) {
          Toast.show({
            type: "error",
            text1: data.msg,
            topOffset: 60,
          });
          return;
        }
        setIsConfirmModalVisible(false);
        getOrderList(true);
      } catch (error) {
        console.error(error);
      }
    };
    return (
      <Modal
        visible={isConfirmModalVisible}
        transparent={true}
        statusBarTranslucent
        animationType="fade"
      >
        <TouchableOpacity
          activeOpacity={1}
          onPress={() => setIsConfirmModalVisible(false)}
          style={{
            backgroundColor: "#00000080",
            ...tailwind("flex-1 justify-center items-center"),
          }}
        >
          <TouchableOpacity
            activeOpacity={1}
            style={tailwind("p-4 rounded-2xl bg-[#1E1C29] items-center w-3/4")}
          >
            {currentOrder.consumer_wechat ? (
              <View style={tailwind("flex flex-col w-full")}>
                <View
                  style={tailwind("flex flex-row items-center justify-center")}
                >
                  <Image
                    style={tailwind("w-10 h-10 rounded-full")}
                    source={currentOrder?.account?.avatar?.images[0]?.urls[0]}
                    placeholder={blurhash}
                    contentFit="cover"
                    transition={1000}
                    cachePolicy="disk"
                  />
                  <Text style={tailwind("text-white text-lg ml-2 font-medium")}>
                    {currentOrder?.account?.name}
                  </Text>
                </View>
                <Text style={tailwind("mt-2 text-white text-base font-medium")}>
                  Ta的微信号：
                </Text>
                <View
                  style={tailwind(
                    "flex flex-row bg-[#FFFFFF1A] px-4 py-2 rounded-lg justify-between"
                  )}
                >
                  <Text style={tailwind("text-white text-base font-medium")}>
                    {currentOrder?.consumer_wechat}
                  </Text>
                  <TouchableOpacity
                    onPress={() => copy(currentOrder?.consumer_wechat)}
                    style={tailwind("flex flex-row")}
                  >
                    <NativeImage
                      source={require("../../../assets/icon/24DP/copy.png")}
                    />
                    <Text style={tailwind("text-white text-base font-medium")}>
                      复制
                    </Text>
                  </TouchableOpacity>
                </View>
                <Text style={tailwind("mt-2 text-white text-base font-medium")}>
                  添加时请备注：
                </Text>
                <View
                  style={tailwind(
                    "flex flex-row bg-[#FFFFFF1A] mb-4 px-4 py-2 rounded-lg justify-between"
                  )}
                >
                  <Text style={tailwind("text-white text-base font-medium")}>
                    {currentOrder?.consumer_note}
                  </Text>
                  <TouchableOpacity
                    onPress={() => copy(currentOrder?.consumer_note)}
                    style={tailwind("flex flex-row")}
                  >
                    <NativeImage
                      source={require("../../../assets/icon/24DP/copy.png")}
                    />
                    <Text style={tailwind("text-white text-base font-medium")}>
                      复制
                    </Text>
                  </TouchableOpacity>
                </View>
              </View>
            ) : (
              <View style={tailwind("flex flex-col")}>
                <View
                  style={tailwind("flex flex-row items-center justify-center")}
                >
                  <Image
                    style={tailwind("w-10 h-10 rounded-full")}
                    source={currentOrder.account?.avatar?.images[0]?.urls[0]}
                    placeholder={blurhash}
                    contentFit="cover"
                    transition={1000}
                    cachePolicy="disk"
                  />
                  <Text style={tailwind("text-white text-lg ml-2 font-medium")}>
                    {currentOrder.account?.name}
                  </Text>
                </View>
                <Text
                  style={tailwind(
                    "text-white text-base text-center my-2 font-medium"
                  )}
                >
                  请确认对方已主动添加您的微信，并您已经通过好友申请。
                </Text>
              </View>
            )}
            <Button
              onPress={handleConfirm}
              titleStyle={tailwind("text-sm font-medium px-2")}
              color="#FF669E"
              radius="999"
              size="md"
            >
              我已完成添加
            </Button>
          </TouchableOpacity>
        </TouchableOpacity>
      </Modal>
    );
  };

  //订单项组件
  const renderItem = ({ item }) => {
    return (
      <ListItem bottomDivider containerStyle={tailwind("p-0 bg-[#07050A]")}>
        <View style={tailwind("flex-1")}>
          <View style={tailwind("flex-row py-3 items-center")}>
            <Image
              style={tailwind("w-12 h-12 rounded-full")}
              source={item?.account?.avatar?.images[0]?.urls[0]}
              placeholder={blurhash}
              contentFit="cover"
              transition={1000}
              cachePolicy="disk"
            />
            <View style={tailwind("ml-2 justify-around flex-1")}>
              <Text
                style={tailwind("text-base text-white font-medium")}
                numberOfLines={1}
                ellipsizeMode="tail"
              >
                {item?.account?.name}
              </Text>
              <Text
                style={tailwind("text-xs text-[#FFFFFF80]")}
                numberOfLines={1}
                ellipsizeMode="tail"
              >
                请于72小时内添加对方微信
              </Text>
              <Text
                style={tailwind("text-xs text-[#FFFFFF80]")}
                numberOfLines={1}
                ellipsizeMode="tail"
              >
                付款时间:{new Date(item?.ct * 1000).toLocaleString()}
              </Text>
            </View>
            <View style={tailwind("ml-2 justify-around items-center")}>
              {item.order_status === 2 ? (
                <Text
                  style={tailwind("text-xs text-[#FFFFFF80]")}
                  numberOfLines={1}
                  ellipsizeMode="tail"
                >
                  等待用户填写微信
                </Text>
              ) : (
                <Button
                  onPress={() => {
                    setCurrentOrder(item);
                    setIsConfirmModalVisible(!isConfirmModalVisible);
                  }}
                  titleStyle={tailwind("text-sm font-medium px-2")}
                  color="#FF669E"
                  radius="999"
                  size="md"
                >
                  添加微信
                </Button>
              )}
            </View>
          </View>
        </View>
      </ListItem>
    );
  };

  return (
    <View
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("px-4 flex-1")}>
        <ConfirmModal />
        <FlatList
          data={orderList}
          renderItem={renderItem}
          initialNumToRender={20}
          refreshControl={
            <RefreshControl
              colors={["#FF669E"]}
              tintColor="white"
              refreshing={refreshing}
              onRefresh={() => handleRefresh()}
            />
          }
          onEndReached={() => getOrderList()}
          ListEmptyComponent={<Empty type="nodata" />}
        />
      </View>
    </View>
  );
}
