import Modal from "antd/lib/modal";
import { PlusOutlined } from "@ant-design/icons";
import Upload, { RcFile, UploadFile, UploadProps } from "antd/lib/upload";
import { useEffect, useState } from "react";
import Config from "@/util/config";
import { UploadFileProps } from "./form/interface";

const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const AliUpload = (props: UploadFileProps) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [previewTitle, setPreviewTitle] = useState("");
  const [files, setFileList] = useState<UploadFile[]>([]);
  const handleCancel = () => setPreviewOpen(false);
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(
      file.name || file.url!.substring(file.url!.lastIndexOf("/") + 1)
    );
  };

  useEffect(() => {
    setFileList(props.value ?? []);
  }, [props.value]);

  const handleChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    newFileList.forEach((i) => {
      i.url = `${Config.baseUrl}/uploads/` + i.name;
      i.fileName = i.name;
    });
    setFileList(newFileList);
    props.onChange!(newFileList);
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <div style={{ margin: 10 }} id={props.id}>
      <Upload
        {...props}
        listType="picture-card"
        fileList={files}
        action={`${Config.baseUrl}/v1/public/fts/upload`}
        onPreview={handlePreview}
        maxCount={props.maxCount ?? 4}
        onChange={handleChange}
      >
        {files.length >= (props.maxCount ?? 4) ? null : uploadButton}
      </Upload>
      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={handleCancel}
      >
        <img alt="example" style={{ width: "100%" }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default AliUpload;
