"use client";

import { useRef, useState } from "react";
import { Button } from "@mui/material";
import ProfileP from "@/components/icons/ProfileP";
import ArrowLeftPU from "@/components/icons/ArrowLeftPU";
import { uploadImage } from "@/helper";
import ModalUpload from "./ModalUpload";
import Image from "next/image";

function UploadFile({ image, setImage }) {
  const fileRef = useRef();

  const [open, setOpen] = useState(false);
  const [data, setData] = useState();

  const handleClose = () => setOpen(false);
  const handleOpen = () => setOpen(true);

  const openInput = () => fileRef.current.click();
  const handleChange = async (event) => {
    if (!!event.target.value) {
      const result = await uploadImage(event);
      handleOpen();
      setData(result);
    }
  };

  const uploadImg = (prop) => {
    setImage(prop);
    handleClose();
  };

  return (
    <>
      <ModalUpload
        open={open}
        data={data}
        uploadImg={uploadImg}
        handleClose={handleClose}
      />
      <input
        type="file"
        ref={fileRef}
        accept="image/*"
        className="contents"
        onChange={handleChange}
      />
      <div
        onClick={openInput}
        className="flex items-center justify-start gap-[10px] cursor-pointer w-fit"
      >
        {image ? (
          <Image
            width={24}
            height={24}
            src={image.blob}
            alt="img-uploaded"
            className="w-[74px] h-[74px] rounded-full overflow-hidden object-cover"
          />
        ) : (
          <div className="p-[24px] grid place-items-center border border-solid border-[#EFEFEF] bg-[#EFEFEF] rounded-full">
            <ProfileP />
          </div>
        )}
        <Button
          variant="text"
          className="!flex !p-1 dark:!text-[#A1A1A1] !text-[#525252] !text-[16px] !font-medium !items-center !justify-center !gap-[4px]"
        >
          انتخاب تصویر
          <ArrowLeftPU />
        </Button>
      </div>
    </>
  );
}

export default UploadFile;
