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 CreatePost({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();
  const [content, setContent] = useState();
  const [imageAssets, setImageAssets] = useState([]);
  const [videoAssets, setVideoAssets] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  //提交反馈
  const handleSubmit = async () => {
    if (!content) {
      Toast.show({
        type: "error",
        text1: "动态内容不能为空",
        topOffset: 60,
      });
      return;
    }
    if (imageAssets.length === 0 && videoAssets.length === 0) {
      Toast.show({
        type: "error",
        text1: "请上传图片或视频",
        topOffset: 60,
      });
      return;
    }
    if (imageAssets.length !== 0 && videoAssets.length !== 0) {
      Toast.show({
        type: "error",
        text1: "不可同时添加图片与视频",
        topOffset: 60,
      });
      return;
    }
    //提交数据
    setIsSubmitting(true);
    const media = await multiUpload(
      imageAssets.length === 0 ? videoAssets : imageAssets
    );
    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,
        status: 2,
        text: content,
        media_component: media,
      });
      const response = await fetch(
        `${apiUrl}/api/moment/create?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
            mid: account.mid,
            status: 2,
            text: content,
            media_component: 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) => setContent(value)}
          value={content}
          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")}>
          图片
          <Text style={tailwind("text-[#FFFFFF80] text-sm")}>
            （添加图片后不可添加视频）
          </Text>
        </Text>
        <MediaPicker maxCount={9} type="image" setAssets={setImageAssets} />
        <Text style={tailwind("text-base font-medium text-white mt-4 mb-1")}>
          视频
          <Text style={tailwind("text-[#FFFFFF80] text-sm")}>
            （添加视频后不可添加图片）
          </Text>
        </Text>
        <MediaPicker maxCount={1} type="video" setAssets={setVideoAssets} />
        <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>
  );
}
