import React, { useEffect, useState } from "react";
import { Upload } from "antd";
import type { GetProp, UploadProps } from "antd";
import { TbCameraPlus } from "react-icons/tb";
import { useFormikContext } from "formik";
import Image from "../../../../Components/Ui/Image";
import { useTranslation } from "react-i18next";

type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];

const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const CustomFile: React.FC = () => {
  const formik = useFormikContext<any>();
  const fieldName = "image";
  const FormikName = formik.values[fieldName] ?? "";

  const [imageUrl, setImageUrl] = useState<string>(FormikName);
  useEffect(() => {
    if (typeof FormikName === "string") {
      // console.log(FormikName);

      setImageUrl(FormikName);
    }
  }, [FormikName]);

  const handleChange: UploadProps["onChange"] = (info) => {
    // console.log(info,"info");

    if (info.file.status === "done") {
      getBase64(info.file.originFileObj as FileType, (url) => {
        setImageUrl(url);
        formik.setFieldValue(fieldName, info.file.originFileObj);
      });
    }
  };
  const customRequest = async ({ onSuccess }: any) => {
    onSuccess();
  };
  const [t] = useTranslation();
  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      <div className="CustomFile">
        {t("input.drag_and_drop_or_click_here_to_select_the_file")}
      </div>
    </button>
  );
  const uploadIcon = (
    <div className="uploadIcon">
      <TbCameraPlus />
    </div>
  );

  return (
    <div className={`ValidationField ${imageUrl && `have_value`} w-100`}>
      <label className="text">{t("input.image")}</label>

      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        customRequest={customRequest}
        onChange={handleChange}
      >
        {imageUrl ? (
          <Image src={imageUrl} alt="avatar" style={{ width: "100%" }} />
        ) : (
          uploadButton
        )}
        {imageUrl && uploadIcon}
      </Upload>
    </div>
  );
};

export default CustomFile;
