import { useRef, useState } from "react";
import {
  applyRadioGroupWrapperStyle,
  baseRadioGroupContainerStyle,
} from "@/page/App/components/InspectPanel/PanelSetters/RadioGroupSetter/style";
import { PanelLabel } from "@/page/App/components/InspectPanel/components/Label";
import { BaseUploadFileProps } from "./interface";
import ToggleButton from "@mui/material/ToggleButton";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import { imageUrlStyle, setterContainerStyle, setterInputStyle } from "./style";
import Image from "./assets/image";
import axios from "axios";
import 'regenerator-runtime/runtime';
 
const BaseUploadFileSetter = (props: BaseUploadFileProps) => {
  const {
    value,
    attrName,
    labelName,
    labelDesc,
    handleUpdateDsl,
  } = props;

  const [imageName, setImageName] = useState((value as any)?.name || "Upload File");
  const [imageUrl, setImageUrl] = useState((value as any)?.url || "");

  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    const formData = new FormData();
    formData.append("image", file);
    try {
      const imageUrlData = await axios.post(
        `${"http://52.183.132.161/backend"}/api/uploads/upload`,
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      );
      handleUpdateDsl(attrName, {name: e.target.files?.[0].name, url: `${"http://52.183.132.161/backend"}/api/uploads/image/${imageUrlData.data.id}`})
      setImageName(e.target.files?.[0].name)
      setImageUrl(`${"http://52.183.132.161/backend"}/api/uploads/image/${imageUrlData.data.id}`)
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <div css={setterContainerStyle}>
      {labelName && (
        <span>
          <PanelLabel
            labelName={labelName}
            labelDesc={labelDesc}
            labelSize="medium"
          />
        </span>
      )}
      <div css={setterInputStyle} onClick={handleClick}>
        <Image></Image>
        <span>{imageName || "Upload File"}</span>
      </div>
      {imageUrl && (
        <div>
          <PanelLabel
            labelName={"Generated Url"}
            labelSize="small"
          />
          <div css={imageUrlStyle}>
            {imageUrl}
          </div>
        </div>
      )}
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: "none" }}
        onChange={handleFileChange}
        accept=""
      />
    </div>
  );
};

BaseUploadFileSetter.displayName = "BaseUploadFileSetter";

export default BaseUploadFileSetter;
