import React, { useContext, useEffect, useState } from "react";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { styled } from "@mui/material/styles";
import {
  Button,
  IconButton,
  Typography,
  Box,
  LinearProgress,
  Chip,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import { AppContext } from "../../contexts/AppContext";
import { motion, AnimatePresence } from "framer-motion";

const VisuallyHiddenInput = styled("input")({
  clip: "rect(0 0 0 0)",
  clipPath: "inset(50%)",
  height: 1,
  overflow: "hidden",
  position: "absolute",
  bottom: 0,
  left: 0,
  whiteSpace: "nowrap",
  width: 1,
});

const CompactFileItem = styled(motion.div)(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  padding: theme.spacing(0.5),
  margin: theme.spacing(0.25, 0),
  borderRadius: theme.shape.borderRadius,
  "&:hover": {
    backgroundColor: theme.palette.action.hover,
  },
}));

export const FileUploader = ({ onChange }) => {
  const [filesList, setFilesList] = useState([]);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [openNotif] = useContext(AppContext);

  const handleFileUpload = (event) => {
    const file = event.target.files[0];
    if (!file) return;

    if (file.size > 5000000) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "حجم فایل بیش از حد مجاز است!",
        severity: "error",
      });
      return;
    }

    setIsUploading(true);
    setUploadProgress(0);

    const interval = setInterval(() => {
      setUploadProgress((prev) => {
        if (prev >= 100) {
          clearInterval(interval);
          setIsUploading(false);
          return 100;
        }
        return prev + 10;
      });
    }, 100);

    setFilesList((prev) => [...prev, file]);
  };

  const handleRemoveFile = (index) => {
    setFilesList((prevFiles) => prevFiles.filter((_, i) => i !== index));
  };

  useEffect(() => {
    if (onChange) {
      onChange(filesList);
    }
  }, [filesList, onChange]);

  return (
    <Box sx={{ width: "100%" }}>
      <Button
        disabled={filesList.length >= 4}
        component="label"
        variant="contained"
        color="primary"
        size="small"
        startIcon={<CloudUploadIcon fontSize="small" />}
        sx={{
          borderRadius: "12px",
          padding: "4px 12px",
          fontSize: "0.8125rem",
          minWidth: "auto",
          "&:hover": {
            transform: "none",
          },
        }}
      >
        {filesList.length >= 4 ? "حداکثر 4 فایل" : "آپلود فایل"}
        <VisuallyHiddenInput type="file" onChange={handleFileUpload} />
      </Button>

      <AnimatePresence>
        {!!filesList.length && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.2 }}
            style={{ marginTop: 8 }}
          >
            <Box sx={{ maxHeight: 150, overflowY: "auto", pr: 1 }}>
              {isUploading && (
                <LinearProgress
                  variant="determinate"
                  value={uploadProgress}
                  color="secondary"
                  sx={{ height: 4, borderRadius: 2, mb: 0.5 }}
                />
              )}

              {filesList.map((item, i) => (
                <CompactFileItem
                  key={item?.name}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  transition={{ duration: 0.15 }}
                >
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      gap: 1,
                      overflow: "hidden",
                    }}
                  >
                    <CheckCircleIcon
                      color="success"
                      fontSize="small"
                      sx={{ fontSize: "16px" }}
                    />
                    <Typography
                      variant="body2"
                      sx={{
                        fontSize: "0.8125rem",
                        whiteSpace: "nowrap",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        maxWidth: 120,
                      }}
                    >
                      {item.name}
                    </Typography>
                    <Chip
                      label={`${(item.size / 1000000).toFixed(2)}MB`}
                      size="small"
                      sx={{ height: 20, fontSize: "0.6875rem" }}
                    />
                  </Box>
                  <IconButton
                    color="error"
                    onClick={() => handleRemoveFile(i)}
                    size="small"
                    sx={{ p: 0.5 }}
                  >
                    <CloseIcon fontSize="small" sx={{ fontSize: "16px" }} />
                  </IconButton>
                </CompactFileItem>
              ))}
            </Box>
          </motion.div>
        )}
      </AnimatePresence>
    </Box>
  );
};
