import { UploadOutlined } from "@ant-design/icons"
import { Button, Input, Space } from "antd"
import { useRef, useState } from "react"
import uploadOss from "../_lib/upload"

export default function ImageUpload(props: {
  accept: string
  width?: number
  height?: number
  value?: string
  background?: string
  onChange?: (val: string) => void
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [loading, setLoading] = useState(false)

  const handleFile = async (file: File) => {
    setLoading(true)
    try {

      const url = await uploadOss(file, "aibot")
      setLoading(false)
      if (url) {
        props.onChange?.(url)
      }
    } catch (e) {
      setLoading(false)

    }

  }
  return (
    <>
      <div
        className="bg-center bg-no-repeat bg-contain rounded-lg shadow-lg flex items-center"
        style={{
          width: props.width || 240 + "px",
          height: props.height || 120 + "px",
          backgroundImage: `url('${props.value}')`,
          backgroundColor: props.background || "rgba(0,0,0,0.2)",
        }}
      />
      <Space className="mt-2">

        <Input  value={props.value} onChange={(e) => {
          props.onChange?.(e.target.value)
        }}></Input>
        <Button
          loading={loading}
          disabled={loading}
          icon={<UploadOutlined />}
          onClick={() => {
            inputRef.current?.click()
          }}
        >
          上传文件
        </Button>
      </Space>
      <input
        type="file"
        accept={props.accept}
        ref={inputRef}
        style={{
          display: "none",
        }}
        onChange={(e) => {
          const file = e.target.files?.[0]
          e.target.value = ""
          if (!file) return
          handleFile(file)
        }}
      />

    </>
  )
}
