import { ChangeEvent, CSSProperties, Dispatch, SetStateAction } from "react"
import styles from "./upload-card.module.css"
import { Icon } from "../icon/icon.component.tsx"
import classNames from "classnames"
import { Config } from "../../utils/config.ts"

// type buildFormDataValueFromFilePath = {
//   path: string;
//   name: string;
//   mimeType: string;
// };

export function UploadCard({
  photo,
  className,
  style,
  wrapperStyle,
  selectedImage,
  setSelectedImage,
}: {
  photo: string | null
  className?: string
  style?: CSSProperties
  wrapperStyle?: CSSProperties
  selectedImage: string | null
  setSelectedImage: Dispatch<SetStateAction<string | null>>
}) {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  // ---------------------------------------------------------------------------
  // functions
  // ---------------------------------------------------------------------------

  async function handleImageChange(event: ChangeEvent<HTMLInputElement>) {
    const files = event.target.files
    if (!files || files.length === 0) return

    const file = files[0]
    const form = new FormData()
    form.append("file", file)

    try {
      const response = await fetch(`${Config.url}/api/file/upload`, {
        method: "POST",
        body: form,
      })

      if (!response.ok) {
        console.error("Error uploading file")
        return
      }

      const data = await response.json()
      console.log("===================filename=================")
      console.log(data)
      console.log("==================end filename==================")
      // Assuming the response contains an array under “filenames” key
      const filename = data.filenames && data.filenames[0]
      // const fullPath = `${Config.url}/uploads/${filename}`
      setSelectedImage(filename)
    } catch (error) {
      console.error("Error uploading file", error)
    }
  }

  // async function handleImageChange(event: ChangeEvent<HTMLInputElement>) {
  //   if (event.target.files && event.target.files[0]) {
  //     const reader = new FileReader()
  //     reader.onload = (e) => {
  //       if (e.target?.result) {
  //         setSelectedImage(e.target.result as string)
  //       }
  //     }
  //     reader.readAsDataURL(event.target.files[0])
  //   }
  // }
  console.log("=================selectedImage===================")
  console.log(selectedImage)
  console.log("=================end selectedImage===================")
  // ---------------------------------------------------------------------------
  return (
    <div
      style={wrapperStyle}
      className={classNames(styles.container, className)}
    >
      <img
        style={style}
        src={selectedImage ? Config.imageUrl + selectedImage : photo || ""}
        className={styles.profileImg}
        alt="img"
      />
      <label htmlFor="files" className={styles.iconBlock}>
        <Icon
          name={"fa-solid fa-up-from-line"}
          size="1.6"
          className={styles.icon}
        />
        <p>Upload photo</p>
      </label>
      <input
        type="file"
        id="files"
        style={{ visibility: "hidden" }}
        onChange={handleImageChange}
      />
    </div>
  )
}
when upload first image it's showing but issue when upload second image not showing second image, how to fix it ?