import {
  View,
  ScrollView,
  Text,
  TextInput,
  KeyboardAvoidingView,
  ActivityIndicator,
} from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Toast from "react-native-toast-message";
import MyDivider from "../../../components/MyDivider";
import { Button } from "@rneui/themed";
import baseRequest from "../../../utils/baseRequest";
import { generateSignature } from "../../../utils/crypto";

export default function SpaceRefund({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  //页面数据
  const [data, setData] = useState();

  //联系人
  const [name, setName] = useState();

  //联系方式
  const [contact, setContact] = useState();

  //备注
  const [remark, setRemark] = useState();

  //提交中
  const [isSubmitting, setIsSubmitting] = useState(false);

  //提交退款
  const handleSubmit = async () => {
    if (!name || !contact || !remark) {
      Toast.show({
        type: "error",
        text1: "请完善信息后提交",
        topOffset: 60,
      });
      return;
    }
    if (remark.length < 15) {
      Toast.show({
        type: "error",
        text1: "请填写15字以上退款原因",
        topOffset: 60,
      });
      return;
    }
    //提交数据
    if (isSubmitting) return;
    setIsSubmitting(true);
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    const base = await baseRequest();
    try {
      const body = {
        zid: route.params.data.id,
        contact_name: name,
        contact_phone: contact,
        note: remark,
        ...base,
      };
      const signature = await generateSignature(body);
      const _response = await fetch(
        `${apiUrl}/api/zone/refund?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      Toast.show({
        type: "success",
        text1: "提交成功，请关注原支付渠道通知",
        topOffset: 60,
      });
      navigation.replace("HomeTab");
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  //获取页面数据
  useEffect(() => {
    const getData = async () => {
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      try {
        const base = await baseRequest();
        const body = {
          zid: route.params.data.id,
          ...base,
        };
        const signature = await generateSignature(body);
        const _response = await fetch(
          `${apiUrl}/api/zone/refund_page?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(body),
          }
        );
        const _data = await _response.json();
        if (_data.ret === -1) {
          Toast.show({
            type: "error",
            text1: _data.msg,
            topOffset: 60,
          });
          return;
        }
        setData(_data.data);
      } catch (error) {
        console.error(error);
      }
    };
    getData();
  }, []);

  return (
    <ScrollView
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <KeyboardAvoidingView style={tailwind("p-4")} behavior="position">
        <View style={tailwind("flex-row justify-between items-center")}>
          <Text style={tailwind("text-base text-white font-medium")}>
            <Text style={tailwind("text-[#F53030]")}>*</Text>
            退款商品
          </Text>
          <Text style={tailwind("text-base text-white font-medium")}>
            {data?.name}
          </Text>
        </View>
        <MyDivider style={tailwind("my-2")} />
        <View style={tailwind("flex-row justify-between items-center")}>
          <Text style={tailwind("text-base text-white font-medium")}>
            <Text style={tailwind("text-[#F53030]")}>*</Text>
            退款价格
          </Text>
          <Text style={tailwind("text-base text-white font-medium")}>
            ¥{data?.price / 100}
          </Text>
        </View>
        <MyDivider style={tailwind("my-2")} />
        <View style={tailwind("flex-row justify-between items-center")}>
          <Text style={tailwind("text-base text-white font-medium")}>
            <Text style={tailwind("text-[#F53030]")}>*</Text>
            联系人
          </Text>
          <TextInput
            placeholder="请输入联系人姓名"
            placeholderTextColor="#FFFFFF80"
            style={tailwind("text-white flex-1")}
            underlineColorAndroid="transparent"
            textAlign="right"
            maxLength={20}
            onChangeText={(value) => setName(value)}
            value={name}
          />
        </View>
        <MyDivider style={tailwind("my-2")} />
        <View style={tailwind("flex-row justify-between items-center")}>
          <Text style={tailwind("text-base text-white font-medium")}>
            <Text style={tailwind("text-[#F53030]")}>*</Text>
            联系方式
          </Text>
          <TextInput
            placeholder="请输入联系方式"
            placeholderTextColor="#FFFFFF80"
            style={tailwind("text-white flex-1")}
            underlineColorAndroid="transparent"
            textAlign="right"
            maxLength={20}
            onChangeText={(value) => setContact(value)}
            value={contact}
          />
        </View>
        <MyDivider style={tailwind("my-2")} />
        <View style={tailwind("flex-col")}>
          <Text style={tailwind("text-base text-white font-medium")}>
            <Text style={tailwind("text-[#F53030]")}>*</Text>
            退款原因
          </Text>
          <View style={tailwind("flex-row items-center")}>
            <TextInput
              multiline
              scrollEnabled={false}
              placeholder="请输入退款原因"
              placeholderTextColor="#FFFFFF80"
              style={tailwind("text-white flex-1")}
              underlineColorAndroid="transparent"
              textAlign="top"
              onChangeText={(value) => setRemark(value)}
              value={remark}
            />
          </View>
        </View>
        <MyDivider style={tailwind("my-2")} />
        <Text style={tailwind("text-[#F53030] text-base font-medium")}>
          退款须知
        </Text>
        <Text style={tailwind("text-[#FFFFFF80] text-sm font-medium")}>
          1、当前退款内容为本空间的成员身份，退款后您将无法再次加入本空间；
        </Text>
        <Text style={tailwind("text-[#FFFFFF80] text-sm font-medium")}>
          2、平台将在24小时内处理您的退款申请，为了退款进程的顺利，请您详细填写您的退款原因；
        </Text>
        <Text style={tailwind("text-[#FFFFFF80] text-sm font-medium")}>
          3、一旦退款成功，退款金额将原路返回您的支付账户，请确保您的支付账户可正常接受款项；
        </Text>
        <Text style={tailwind("text-[#FFFFFF80] text-sm font-medium")}>
          4、您在12小时内只能进行一次自助退款，请合理利用权利；
        </Text>
        <Text style={tailwind("text-[#FFFFFF80] text-sm font-medium")}>
          5、本条款最终解释权归平台所有。
        </Text>
        <Button
          color="#FF669E"
          radius="999"
          size="md"
          disabled={isSubmitting}
          disabledStyle={tailwind("bg-[#FFFFFF80]")}
          disabledTitleStyle={tailwind("text-white")}
          onPress={handleSubmit}
          titleStyle={tailwind("text-base")}
          containerStyle={tailwind("mt-16")}
        >
          {isSubmitting && <ActivityIndicator size="small" color="white" />}
          {isSubmitting ? "正在提交..." : "提交退款"}
        </Button>
      </KeyboardAvoidingView>
    </ScrollView>
  );
}
