import { Button, Upload } from "antd";
import { UploadOutlined } from "@ant-design/icons";

import useFormField from "../../../Hooks/useFormField";
import { customRequest } from "../utils/customRequest";
import { getNestedValue } from "../../Utils/getNestedValue";
import { fixImageUrl } from "../utils/fixImageUrl";
import { ImageBaseURL } from "../../../api/config";
import { Console } from "console";

const MaltyFile = ({
  name,
  label,
  onChange,
  isDisabled,
  placeholder,
  className,
  props,
}: any) => {
  const { formik, t, isError } = useFormField(name, props);
  const FormikName = getNestedValue(formik.values, name);
  let imageUrl = FormikName ?? null;

  // Mapping formik values to fileList format
  console.table(imageUrl)
  const fileList = imageUrl
    ? imageUrl.map((file: any, index: number) => {
      const imageUrl = (file?.path || file?.url) ? fixImageUrl(ImageBaseURL + file?.path ?? file?.url): '';
        console.log(file);
          console.log(imageUrl);
          
        return file instanceof File
          ? {
              uid: index,
              name: file?.name,
              status: "done",
              originFileObj: file,
            }
          : {
              uid: index,
              id: file?.id,
              name: file?.name,
              status: "done",
              url: imageUrl || "",
              thumbUrl: imageUrl || "",
            };
      })
    : [];

  const FilehandleChange = ({ fileList }: any) => {
    if (fileList.length === 0) {
      formik.setFieldValue(name, null);
    } else {
      formik.setFieldValue(
        name,
        fileList.map((file: any) => {
          console.log(file);
          
          return(
            file?.originFileObj ?? file
          )
        }),
      );
    }
  };


  return (
    <div className="ValidationField upload_image_button">
      <label htmlFor={name} className="text">
        {t(`input.${label || name}`)}
      </label>

      <Upload
        disabled={isDisabled}
        listType="picture"
        fileList={fileList} // Using fileList instead of defaultFileList
        onChange={onChange || FilehandleChange}
        customRequest={customRequest}
        className={`${className} w-100`}
        multiple // Allow multiple files to be selected
        id={name}
      >
        <Button
          className={isError ? "isError w-100" : " w-100"}
          icon={<UploadOutlined />}
        >
          {t(`input.` + placeholder) ?? t("input.upload_image")}
        </Button>
        <div className="Error_color"> {isError ? "required" : ""}</div>
      </Upload>
    </div>
  );
};

export default MaltyFile;
78