import {
  Form,
  Image,
  TextArea,
  Uploader,
  Grid,
  GridItem,
} from "@nutui/nutui-react-taro";
import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState } from "react";

const Publish = () => {
  const [uploadedFiles, setUploadedFiles] = useState<any[]>([]);

  // 获取 Authorization token
  const getAuthToken = () => {
    const token = Taro.getStorageSync("Authorization");
    return token ? `Bearer ${token}` : "";
  };

  // 处理上传成功
  const handleUploadSuccess = (param: {
    responseText: string;
    option: any;
    files: any[];
  }) => {
    // 从 responseText 中解析响应数据
    let responseData: any = null;
    try {
      // responseText 是一个对象，实际数据在 data 字段中
      const responseString =
        (param.responseText as any).data || param.responseText;
      responseData =
        typeof responseString === "string"
          ? JSON.parse(responseString)
          : responseString;
    } catch (error) {
      console.error("解析 responseText 失败:", error);
    }

    if (responseData && responseData.code === 200 && responseData.data) {
      const newFile = {
        name: responseData.data.origin_name || "未命名图片",
        url: responseData.data.media_url,
        status: "success",
        message: "上传成功",
      };

      // 添加到现有文件列表
      // setUploadedFiles((prevFiles) => {
      //   const updatedFiles = [...prevFiles, newFile];
      //   console.log("添加新文件:", newFile);
      //   console.log("更新后的文件列表:", updatedFiles);
      //   return updatedFiles;
      // });
      console.log("添加新文件:", newFile);
      console.log("更新后的文件列表:", [...uploadedFiles, newFile]);
      setUploadedFiles([...uploadedFiles, newFile]);
    }
  };

  // 处理删除图片
  const handleDeleteImage = (index: number) => {
    setUploadedFiles((prevFiles) => {
      const updatedFiles = prevFiles.filter((_, i) => i !== index);
      return updatedFiles;
    });
  };

  return (
    <View className="p-[10px] bg-[#f7f8fa] min-h-screen">
      <Form>
        <Form.Item name="content">
          <TextArea placeholder="这一刻的想法..." rows={10} />
        </Form.Item>
        {/* 已上传的图片显示区域 */}
        {uploadedFiles.length > 0 && (
          <Form.Item>
            <View className="mb-[10px]">
              <View className="text-[14px] font-medium mb-[8px] text-[#333]">
                已上传图片 ({uploadedFiles.length})
              </View>
              <Grid
                columns={3}
                gap={8}
                style={
                  {
                    "--nutui-grid-item-content-padding": "0px",
                    "--nutui-grid-item-content-margin": "0px",
                  } as any
                }
              >
                {uploadedFiles.map((item, index) => (
                  <GridItem key={item.url}>
                    <View style={{ position: "relative" }}>
                      <Image
                        src={item.url}
                        height="100"
                        mode="aspectFill"
                        style={{ borderRadius: "8px" }}
                      />
                      {/* 删除按钮 */}
                      <View
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDeleteImage(index);
                        }}
                        style={{
                          position: "absolute",
                          top: "4px",
                          right: "4px",
                          width: "20px",
                          height: "20px",
                          backgroundColor: "rgba(0, 0, 0, 0.6)",
                          borderRadius: "50%",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          cursor: "pointer",
                        }}
                      >
                        <Text
                          style={{
                            color: "white",
                            fontSize: "12px",
                            fontWeight: "bold",
                          }}
                        >
                          ×
                        </Text>
                      </View>
                    </View>
                  </GridItem>
                ))}
              </Grid>
            </View>
          </Form.Item>
        )}
        <Form.Item name="urls" initialValue={[]}>
          {/* 调试信息 */}

          <Uploader
            uploadLabel="添加图片"
            multiple
            maxCount={9}
            autoUpload
            accept="image/*"
            url={`http://127.0.0.1:8181/files/upload`}
            headers={{
              Authorization: getAuthToken(),
            }}
            onSuccess={handleUploadSuccess}
          />
        </Form.Item>
      </Form>
    </View>
  );
};

export default Publish;
