import React from "react";
import { Box, IconButton, CircularProgress, Typography } from "@mui/material";
import {
  Close as CloseIcon,
  Replay as ReplayIcon,
  HighlightOff as ClearIcon,
  FileDownload as DownloadIcon,
} from "@mui/icons-material";

// Styles will be injected once when component is mounted
const scssStyles = `
.file-uploader-container {
  display: flex;
  align-items: center;
  position: relative;
  padding: 4px 8px;
  border-radius: 8px;
  background-color: #f5f5f5;
  margin: 2px 0;
  max-width: 300px;
}

.file-uploader-container.error {
  border: 1px solid #f44336;
}

.file-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  overflow: hidden;
}

.file-name {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.file-size {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 4px;
}

.error-message {
  font-size: 12px;
  color: #f44336;
  margin-top: 4px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
}
`;

// Helper to inject styles
const injectStyles = () => {
  if (!document.getElementById("file-uploader-styles")) {
    const style = document.createElement("style");
    style.id = "file-uploader-styles";
    style.innerHTML = scssStyles;
    document.head.appendChild(style);
  }
};

const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

const FileUploader = ({
  file,
  fileUrl,
  isLoading,
  isError,
  errorMessage = "Upload failed",
  onClear,
  onRetry,
  onDownload,
}) => {
  // Inject styles on first render
  React.useEffect(() => {
    injectStyles();
  }, []);

  const handleDownload = () => {
    if (fileUrl && onDownload) {
      onDownload(fileUrl, file.name);
    }
  };

  if (!file && !isLoading && !isError) return null;

  return (
    <Box className={`file-uploader-container ${isError ? "error" : ""}`}>
      <div className="file-info">
        <Typography className="file-name" title={file?.name}>
          {file?.name || "Unknown file"}
        </Typography>
        {file && (
          <Typography className="file-size">
            {formatFileSize(file.size)}
          </Typography>
        )}
      </div>

      <div className="action-buttons">
        {fileUrl && !isLoading && !isError && (
          <IconButton
            size="small"
            onClick={handleDownload}
            title="Download file"
          >
            <DownloadIcon sx={{ fontSize: 20 }} />
          </IconButton>
        )}

        {isError ? (
          <>
            <IconButton size="small" onClick={onRetry} title="Retry upload">
              <ReplayIcon sx={{ fontSize: 20 }} />
            </IconButton>
            <IconButton size="small" onClick={onClear} title="Clear">
              <ClearIcon sx={{ fontSize: 20 }} />
            </IconButton>
          </>
        ) : (
          <IconButton size="small" onClick={onClear} title="Remove file">
            <CloseIcon sx={{ fontSize: 20 }} />
          </IconButton>
        )}
      </div>

      {isLoading && (
        <div className="loading-overlay">
          <CircularProgress size={20} />
        </div>
      )}

      {isError && (
        <Typography className="error-message">{errorMessage}</Typography>
      )}
    </Box>
  );
};

export default FileUploader;
