import {
  View,
  Text,
  TextInput,
  ScrollView,
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
} from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import MediaPicker from "../../components/MediaPicker";
import Toast from "react-native-toast-message";
import { multiUpload } from "../../utils/upload";
import MediaGrid from "../../components/MediaGrid";
import requireAPI from "../../utils/requireAPI";
export default function EditStreamerPost({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [oldMediaAssets, setOldMediaAssets] = useState([]);
  const [mediaAssets, setMediaAssets] = useState([]);
  const [mType, setMType] = useState(1);
  const [initalData, setInitalData] = useState({});
  //价格
  const [formData, setFormData] = useState({
    content: "",
  });
  useEffect(() => {
    getData();
  }, []);
  const getData = async () => {
    const ids = [parseInt(route.params.id, 10)];
    try {
      const body = {
        ids,
      };
      const _data = await requireAPI(
        "POST",
        "/api/moment/list_by_ids_from_creater",
        {
          body,
        },
        true
      );
      if (_data.ret === -1) {
        Toast.show({
          icon: "fail",
          content: _data.msg,
          position: "top",
        });
        return;
      }
      setInitalData(_data.data.list[0]);

      const { text, media_component } = _data.data.list[0];
      setFormData({
        content: text,
      });
      setMType(media_component.images.length > 0 ? 1 : 2);
      setOldMediaAssets(
        media_component.images.length > 0
          ? media_component.images
          : media_component.videos
      );
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };
  //发布按钮
  useEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <Text
          onPress={handleSubmit}
          style={tailwind("text-[#FF669E] text-base font-medium")}
        >
          {isSubmitting ? "" : "发布"}
          {isSubmitting && <ActivityIndicator size="small" color="white" />}
        </Text>
      ),
    });
  }, [isSubmitting, handleSubmit, formData, mediaAssets, oldMediaAssets]);
  //是否正在拖动图片，用于禁用ScrollView的滚动
  const [dragging, setDragging] = useState(false);

  const handleSubmit = async () => {
    if (formData.content == "") {
      Toast.show({
        type: "error",
        text1: "动态内容不能为空",
        topOffset: 60,
      });
      return;
    }
    if (oldMediaAssets.length === 0 && mediaAssets.length === 0) {
      Toast.show({
        type: "error",
        text1: "请上传图片或视频",
        topOffset: 60,
      });
      return;
    }
    //提交数据
    if (isSubmitting) return;
    setIsSubmitting(true);
    const { content } = formData;
    const newMedia = await multiUpload(mediaAssets);
    const oldMedia = oldMediaAssets.map((item) => item.id);
    const media =
      mType === 1
        ? {
            ...newMedia,
            image_ids: [...oldMedia, ...newMedia.image_ids],
          }
        : {
            ...newMedia,
            video_ids: [...oldMedia, ...newMedia.video_ids],
          };
    try {
      const body = {
        id: parseInt(route.params.id, 10),
        text: content,
        media_component: media,
        status: 2,
      };
      const data = await requireAPI(
        "POST",
        "/api/moment/update",
        {
          body,
        },
        true,
        100000
      );
      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 (
    <KeyboardAvoidingView
      behavior={Platform.OS == "ios" ? "padding" : "height"}
      keyboardVerticalOffset={insets.bottom + 60}
      style={{
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      {/* 内容 */}
      <ScrollView scrollEnabled={!dragging}>
        <View style={tailwind("p-4")}>
          {initalData?.status === 6 && (
            <View style={tailwind("mb-4")}>
              <Text
                style={tailwind("text-base font-medium text-[#F53030] mb-2")}
              >
                违规详情
              </Text>
              <View style={tailwind("p-4 rounded-2xl bg-[#FFFFFF1A]")}>
                {initalData.text_audit_opinion && (
                  <Text style={tailwind("text-sm font-medium text-white")}>
                    <Text style={tailwind("text-[#F53030]")}>
                      文案违规原因：
                    </Text>
                    {initalData.text_audit_opinion}
                  </Text>
                )}
                {initalData.image_audit_opinion && (
                  <Text style={tailwind("text-sm font-medium text-white")}>
                    <Text style={tailwind("text-[#F53030]")}>
                      图片/视频违规原因：
                    </Text>
                    {initalData.image_audit_opinion}
                  </Text>
                )}
                {initalData.manually_review_opinion && (
                  <Text style={tailwind("text-sm font-medium text-white")}>
                    <Text style={tailwind("text-[#F53030]")}>运营追加：</Text>
                    {initalData.manually_review_opinion}
                  </Text>
                )}
              </View>
            </View>
          )}
          <Text style={tailwind("text-base font-medium text-white")}>
            动态内容
          </Text>
          <TextInput
            placeholder="请遵守平台准则，严禁发布违规内容"
            placeholderTextColor="#FFFFFF80"
            underlineColorAndroid="transparent"
            multiline
            textAlignVertical="top"
            name="content"
            value={formData.content}
            onChange={(e) => setFormData({ content: e.nativeEvent.text })}
            style={tailwind(
              "h-32 bg-[#FFFFFF1A] text-white rounded-2xl mt-2 mb-4 p-2"
            )}
          />
          <View>
            {oldMediaAssets.length > 0 && (
              <MediaGrid
                setDragging={setDragging}
                assets={oldMediaAssets}
                setAssets={setOldMediaAssets}
              />
            )}
            <MediaPicker
              setDragging={setDragging}
              maxCount={
                mType === 1
                  ? 9 - oldMediaAssets.length
                  : 1 - oldMediaAssets.length
              }
              type={mType === 1 ? "image" : "video"}
              setAssets={setMediaAssets}
            />
          </View>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}
