/* eslint-disable @typescript-eslint/no-explicit-any */
import { useCallback, useEffect } from "react";
import { IconButton, InputAdornment, TextField } from "@mui/material";

import FileUploadIcon from "@mui/icons-material/FileUpload";
import { AutoHeightContainer } from "@/widgetLibrary/PublicSector/AutoHeightContainer";
import { handleValidateCheck } from "@/widgetLibrary/PublicSector/InvalidMessage/utils";
import { InvalidMessage } from "../PublicSector/InvalidMessage";

const getAcceptedFileTypes = (allowedTypes) => {
  if (!allowedTypes || !allowedTypes.length) {
    return undefined;
  }

  return allowedTypes.map((type) => `.${type}`).join(",");
};

export const UploadFile = (props: any) => {
  const {
    required,
    errors,
    updateComponentHeight,
    colorScheme,
    disabled,
    value,
    tooltipText,
    fileType,
    minSize,
    maxSize,
    sizeType,
    hideValidationMessage,
    validateMessage,
    handleUpdateDsl,
    updateComponentRuntimeProps,
    deleteComponentRuntimeProps
  } = props;

  const getValidateMessage = useCallback(
    (value?: any) => {
      if (!hideValidationMessage) {
        const message = handleValidateCheck({
          value,
          minSize,
          maxSize,
          sizeType,
          required,
        });
        const showMessage = message && message.length > 0;
        return showMessage ? message : "";
      }
      return "";
    },
    [hideValidationMessage, minSize, sizeType, maxSize, required]
  );

  const handleValidate = useCallback(
    (value?: any) => {
      const message = getValidateMessage(value);

      handleUpdateDsl({
        validateMessage: message,
      });

      return message;
    },
    [getValidateMessage, handleUpdateDsl]
  );

  const handleFileChange = async (event) => {
    const uploadedFile = event.target.files[0];

    handleValidate([uploadedFile]);

  
    const formData = new FormData();
    formData.append("file", event.target.files[0]);

    const apiKey = "66447c48ff3f04664528a558";
    const apiEndpoint = "http://localhost:5000//upload";

    try {
      const response = await fetch(apiEndpoint, {
        method: "POST",
        body: formData,
        headers: {
          Authorization: `Bearer ${apiKey}`,
        },
      });

      if (!response.ok) {
        throw new Error(`Upload failed: ${response.statusText}`);
      }

    } catch (error) {
      console.error("Error uploading file:", error);
    }
  };

  const accept = getAcceptedFileTypes(fileType);
  useEffect(() => {
    updateComponentRuntimeProps({
      setValue: (value: any) => {
        handleUpdateDsl({ value });
      },
      clearValue: () => {
        handleUpdateDsl({ value: undefined });
      },
      validate: () => {
        return handleValidate(value);
      },
      clearValidation: () => {},
    });
    return () => {
      deleteComponentRuntimeProps();
    };
  }, [
    updateComponentRuntimeProps,
    handleUpdateDsl,
    deleteComponentRuntimeProps,
    handleValidate,
    value,
  ]);
  return (
    <>
      <div>
        <TextField
          sx={{
            "& .MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline": {
              borderColor: colorScheme,
            },
          }}
          required
          fullWidth
          onChange={handleFileChange}
          title={tooltipText}
          error={errors !== "" ? true : false}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton onClick={() => {}} title="Upload File">
                  <FileUploadIcon />
                </IconButton>
              </InputAdornment>
            ),
            required: true,
            inputProps: {
              accept,
            },
          }}
          disabled={disabled}
          size={"medium"}
          type={"file"}
        />
        {validateMessage && !hideValidationMessage && (
          <div>
          <InvalidMessage validateMessage={validateMessage} />
        </div>
        )}
      </div>
    </>
  );
};
