import {
  View,
  Text,
  ScrollView,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
} from "react-native";
import { Button, CheckBox } from "@rneui/themed";
import React, { useState, useCallback } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Divider } from "@rneui/themed";
import baseRequest from "../../../utils/baseRequest";
import Toast from "react-native-toast-message";
import { generateSignature } from "../../../utils/crypto";
import { useFocusEffect } from "@react-navigation/native";
import dayjs from "dayjs";
export default function RefundDetail({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();
  const [data, setData] = useState(null);
  const [dragging, setDragging] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedIndex, setIndex] = useState(2);
  const [checkAble, setCheckAble] = useState(true);
  //每次focus都更新一次数据
  useFocusEffect(
    useCallback(() => {
      const getData = async () => {
        //获取环境变量
        const apiUrl = process.env.EXPO_PUBLIC_API_URL;
        const base = await baseRequest();
        const signature = await generateSignature({
          ...base,
          audit_id: route.params.id,
        });
        try {
          const refundResponse = await fetch(
            `${apiUrl}/api/zone/refund_info?signature=${signature}`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                ...base,
                audit_id: route.params.id,
              }),
            }
          );
          const refundData = await refundResponse.json();
          if (refundData.ret === -1) {
            Toast.show({
              type: "error",
              text1: refundData.msg,
              topOffset: 60,
            });
            return;
          }
          setData(refundData.data);
          setIndex(refundData.data.refunds_status);
          setCheckAble(refundData.data.refunds_status === 1);
        } catch (error) {
          console.error(error);
        }
      };
      getData();
    }, [])
  );
  const handleSubmit = async (values) => {
    setIsSubmitting(true);
    //获取环境变量
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;

    //上传表单
    const base = await baseRequest();
    const body = {
      audit_id: route.params.id,
      refunds_status: selectedIndex,
      ...base,
    };

    const signature = await generateSignature(body);
    try {
      const response = await fetch(
        `${apiUrl}/api/zone/refund_audit?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const responseData = await response.json();
      if (responseData.ret === -1) {
        Toast.show({
          type: "error",
          text1: responseData.msg,
          topOffset: 60,
        });
        return;
      }
      setCheckAble(false);
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };
  return (
    <KeyboardAvoidingView
      behavior={Platform.OS == "ios" ? "padding" : "height"}
      keyboardVerticalOffset={insets.bottom + 60}
      style={{
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <ScrollView scrollEnabled={!dragging} style={tailwind("px-4")}>
        <View style={tailwind("my-2")}>
          <View style={tailwind("bg-[#FFFFFF1A] px-4 py-2 my-2 rounded-2xl")}>
            <View
              style={tailwind("flex-row justify-between items-center py-2")}
            >
              <Text style={tailwind("text-base text-white font-medium")}>
                退款价格
              </Text>
              <View
                style={tailwind("flex-row flex-1 justify-end items-center")}
              >
                <Text style={tailwind("text-white")}>
                  ¥ {data ? data?.price / 100 : "0"}
                </Text>
              </View>
            </View>
            <Divider style={tailwind("my-2")} />
            <View
              style={tailwind("flex-row justify-between items-center py-2")}
            >
              <Text style={tailwind("text-base text-white font-medium")}>
                退款用户
              </Text>
              <View
                style={tailwind("flex-row flex-1 justify-end items-center")}
              >
                <Text style={tailwind("text-white")}>{data?.nike_name}</Text>
              </View>
            </View>
            <Divider style={tailwind("my-2")} />
            <View
              style={tailwind("flex-row justify-between items-center py-2")}
            >
              <Text style={tailwind("text-base text-white font-medium")}>
                购买时间
              </Text>
              <View
                style={tailwind("flex-row flex-1 justify-end items-center")}
              >
                <Text style={tailwind("text-white")}>
                  {dayjs(data?.ct * 1000).format("YYYY-MM-DD HH:mm:ss")}
                </Text>
              </View>
            </View>
            <Divider style={tailwind("my-2")} />
            <View
              style={tailwind("flex-row justify-between items-center py-2")}
            >
              <Text style={tailwind("text-base text-white font-medium")}>
                退款时间
              </Text>
              <View
                style={tailwind("flex-row flex-1 justify-end items-center")}
              >
                <Text style={tailwind("text-white")}>
                  {dayjs(data?.refund_t * 1000).format("YYYY-MM-DD HH:mm:ss")}
                </Text>
              </View>
            </View>
            <Divider style={tailwind("my-2")} />
            <View
              style={tailwind("flex-row justify-between items-center py-2")}
            >
              <Text style={tailwind("text-base text-white font-medium")}>
                退款联系人
              </Text>
              <View
                style={tailwind("flex-row flex-1 justify-end items-center")}
              >
                <Text style={tailwind("text-white")}>{data?.contact_name}</Text>
              </View>
            </View>
            <Divider style={tailwind("my-2")} />
            <View
              style={tailwind("flex-row justify-between items-center py-2")}
            >
              <Text style={tailwind("text-base text-white font-medium")}>
                退款联系方式
              </Text>
              <View
                style={tailwind("flex-row flex-1 justify-end items-center")}
              >
                <Text style={tailwind("text-white")}>
                  {data?.contact_phone}
                </Text>
              </View>
            </View>
            <Divider style={tailwind("my-2")} />
            <View style={tailwind("flex-col  py-2")}>
              <Text style={tailwind("text-base text-white font-medium")}>
                退款备注
              </Text>
              <View style={tailwind("p-2")}>
                <Text style={tailwind("text-white")}>{data?.note}</Text>
              </View>
            </View>
          </View>
          <View style={tailwind("flex-col justify-between mt-4")}>
            <Text style={tailwind("text-base text-white font-medium")}>
              是否同意当前退款
            </Text>
            <View style={tailwind("flex-col")}>
              <View style={tailwind("flex-row items-start mt-4 pr-6")}>
                <CheckBox
                  disabled={!checkAble}
                  checked={
                    (data && [2, 3, 4].includes(data?.refunds_status)) ||
                    selectedIndex == 2
                  }
                  // data && data?.refunds_status === 4 ? 2 : selectedIndex

                  onPress={() => setIndex(2)}
                  checkedIcon="dot-circle-o"
                  uncheckedIcon="circle-o"
                  checkedColor={checkAble ? "#FF669E" : "#FFFFFF80"}
                  containerStyle={tailwind("bg-transparent p-0 m-0")}
                  wrapperStyle={tailwind("items-center")}
                  title={
                    <View style={tailwind("ml-4")}>
                      <Text
                        style={{
                          ...tailwind("text-xl mb-1 font-bold"),
                          color: !checkAble
                            ? "#FFFFFF80"
                            : selectedIndex === 2
                            ? "#FF669E"
                            : "#FFFFFF",
                        }}
                      >
                        同意退款
                      </Text>
                      <Text
                        style={{
                          color: !checkAble
                            ? "#FFFFFF80"
                            : selectedIndex === 2
                            ? "#FF669E"
                            : "#FFFFFF",
                        }}
                      >
                        同意退回用户的[空间成员]费用，同时自动禁止用户再次购买此商品。
                        {data && data?.refunds_status}
                      </Text>
                    </View>
                  }
                />
              </View>
              <View style={tailwind("flex-row items-start mt-4 pr-6")}>
                <CheckBox
                  disabled={!checkAble}
                  // checked={selectedIndex === -1}
                  checked={
                    (data && data?.refunds_status == -1) || selectedIndex == -1
                  }
                  onPress={() => setIndex(-1)}
                  checkedIcon="dot-circle-o"
                  uncheckedIcon="circle-o"
                  checkedColor={checkAble ? "#FF669E" : "#FFFFFF80"}
                  containerStyle={tailwind("bg-transparent p-0 m-0")}
                  wrapperStyle={tailwind("items-center")}
                  title={
                    <View style={tailwind("ml-4")}>
                      <Text
                        style={{
                          ...tailwind("text-xl mb-1 font-bold"),
                          color: !checkAble
                            ? "#FFFFFF80"
                            : selectedIndex === -1
                            ? "#FF669E"
                            : "#FFFFFF",
                        }}
                      >
                        拒绝退款
                      </Text>
                      <Text
                        style={{
                          color: !checkAble
                            ? "#FFFFFF80"
                            : selectedIndex === -1
                            ? "#FF669E"
                            : "#FFFFFF",
                        }}
                      >
                        拒绝退回用户的[空间成员]费用。
                      </Text>
                    </View>
                  }
                />
              </View>
            </View>
          </View>

          <Button
            color="#FF669E"
            radius="999"
            size="md"
            disabled={isSubmitting || !checkAble}
            disabledStyle={tailwind("bg-[#FFFFFF80]")}
            disabledTitleStyle={tailwind("text-white")}
            onPress={(e) => {
              handleSubmit(e);
            }}
            titleStyle={tailwind("text-base")}
            containerStyle={{
              marginBottom: insets.bottom + 60,
              ...tailwind("mt-4"),
            }}
          >
            {isSubmitting && <ActivityIndicator size="small" color="white" />}
            {data && data?.refunds_status === 4
              ? "系统已自动提交"
              : !checkAble
              ? "您已提交"
              : isSubmitting
              ? "正在提交..."
              : "提交"}
          </Button>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}
