import postDocument from "@/services/api/basePostDocument";
import FileUploadIcon from "@mui/icons-material/FileUpload";
import { Button, Typography, useTheme } from "@mui/material";
import Grid from "@mui/material/Unstable_Grid2";
import { enqueueSnackbar } from "notistack";
import { useRef } from "react";

export default function UploadFile({ fetchDocuments, fetchChunks }) {
  const theme = useTheme();
  const fileInputRef = useRef(null);

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

  const onHandleFileChange = async (event) => {
    const url = "/upload/document";
    const uploadedfile = event.target.files[0];

    if (!uploadedfile) return;

    const formData = new FormData();
    formData.append("file", uploadedfile);

    try {
      await postDocument(url, formData);
      await fetchDocuments();
      await fetchChunks();
    } catch (error) {
      enqueueSnackbar(error.detail || error.message, {
        variant: "error",
      });
    }
  };

  return (
    <Grid
      container
      border={1}
      borderColor={theme.palette.border.default}
      borderRadius={2}
      p={1}
      sx={{
        backgroundColor: theme.palette.background.default,
      }}
    >
      <Button fullWidth sx={{ textTransform: "none" }} onClick={openExplorer}>
        <Grid
          container
          xs={12}
          alignItems="center"
          justifyContent="space-between"
          border={1}
          borderColor={theme.palette.divider}
          borderRadius={1}
          p={1}
          sx={{
            backgroundColor: "white",
          }}
        >
          <input
            type="file"
            ref={fileInputRef}
            style={{ display: "none" }}
            onChange={onHandleFileChange}
            accept=".pdf"
          />
          <Grid item>
            <Typography variant="h6" color="black">
              Upload File
            </Typography>
          </Grid>
          <FileUploadIcon sx={{ color: "black" }} />
        </Grid>
      </Button>
    </Grid>
  );
}
