import {
  Box,
  InputLabel,
  OutlinedInput,
  CircularProgress,
} from "@mui/material";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { useState } from "react";
import { uploadFile } from "../../services";
import styles from "./index.module.css";

interface IProps {
  label?: string;
  name?: string;
  value?: string;
  onChange: (value: string) => void;
}

export default function UploadFile({ label, name, value, onChange }: IProps) {
  const [loading, setLoading] = useState<boolean>(false);

  const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files[0];
    if (file) {
      setLoading(true);
      const formData = new FormData();
      formData.append("file", file);
      uploadFile(formData)
        .then((res) => {
          console.log(res.data);
          onChange(res.data);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  };
  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
      }}
      className={styles.uploadBox}
    >
      {value && <img className={styles.img} src={value} alt={value} />}
      {loading && <CircularProgress className={styles.loading} />}
      {label && (
        <InputLabel>
          {value ? (
            label
          ) : (
            <span className={styles.label}>
              <CloudUploadIcon className={styles.labelIcon} /> {label}
            </span>
          )}
        </InputLabel>
      )}
      <OutlinedInput
        name={name}
        label={label}
        onChange={changeHandler}
        readOnly
        className={styles.uploadInput}
        type="file"
      />
    </Box>
  );
}
