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

export default function Feedback({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();
  const [value, setValue] = useState();
  const [assets, setAssets] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  //提交反馈
  const handleSubmit = async () => {
    if (!value) {
      Toast.show({
        type: "error",
        text1: "反馈内容不能为空",
        topOffset: 60,
      });
      return;
    }
    //提交数据
    setIsSubmitting(true);
    const media = await multiUpload(assets);
    const account = await get("account");
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const signature = await generateSignature({
        ...base,
        mid: account.mid,
        discription: value,
        credentials: media,
      });
      const response = await fetch(
        `${apiUrl}/api/feedback/create?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
            mid: account.mid,
            discription: value,
            credentials: media,
          }),
        }
      );
      const data = await response.json();
      if (data.ret === -1) {
        Toast.show({
          type: "error",
          text1: data.msg,
          topOffset: 60,
        });
        return;
      }
      //提交成功后显示Toast并返回上一页
      Toast.show({
        type: "success",
        text1: "反馈提交成功",
        topOffset: 60,
      });
      navigation.goBack();
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <ScrollView
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("p-4")}>
        <Text style={tailwind("text-base font-medium text-white")}>
          反馈描述
        </Text>
        <TextInput
          placeholder="请填写详细描述，以便我们更好地为您解决问题"
          placeholderTextColor="#FFFFFF80"
          underlineColorAndroid="transparent"
          multiline
          textAlignVertical="top"
          onChangeText={(value) => setValue(value)}
          value={value}
          style={tailwind(
            "h-32 bg-[#FFFFFF1A] text-white rounded-2xl mt-2 p-2"
          )}
        />
        <Text style={tailwind("text-base font-medium text-white mt-4 mb-1")}>
          截图或录屏（最多9张）
        </Text>
        <MediaPicker maxCount={9} type="mix" setAssets={setAssets} />
        <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>
      </View>
    </ScrollView>
  );
}
