import React, { useState } from "react";
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  CircularProgress,
  Grid,
  Typography,
  Box,
} from "@mui/material";
import Delete from "@mui/icons-material/Delete";
import CloseIcon from "@mui/icons-material/Close";
import { useStyles } from "../../theme/appStyles";

interface IDeletePopup {
  open: boolean;
  handleCloseDelete: (close: boolean) => void;
  onConfirm: () => Promise<void>; // Ensure onConfirm returns a promise
  title: string;
  content: string;
}

const DeletePopup = ({
  open,
  handleCloseDelete,
  onConfirm,
  title,
  content,
}: IDeletePopup) => {
  const classes = useStyles();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null); // For storing any error messages

  const onClose = () => {
    handleCloseDelete(false);
    setError(null); // Clear any existing error on close
  };

  const handleDelete = async () => {
    setIsLoading(true);
    setError(null); // Clear previous errors before attempting to delete
    try {
      await onConfirm();
      handleCloseDelete(true); // Close the dialog on successful deletion
    } catch (error) {
      console.error("Error while deleting:", error);
      setError("Failed to delete. Please try again."); // Set the error message
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} sx={{ padding: 5, minWidth: 450 }}>
      <Grid className={classes.Dialog}>
        <Grid
          container
          justifyContent={"space-between"}
          spacing={5}
          sx={{ borderBottom: 2, padding: 2 }}
          className={classes.titleGrid}
        >
          <Grid item lg={12} md={12} sm={12} xs={12} pt={2}>
            <Typography className={classes.cardTitle}>{title}</Typography>
          </Grid>
        </Grid>
        <DialogContent>
          <DialogContentText sx={{ pt: 3 }}>{content}</DialogContentText>
          {error && <Typography color="error">{error}</Typography>} {/* Display error message */}
        </DialogContent>
        <DialogActions sx={{ paddingRight: "24px", p: 4, py: 3, gap: 2 }}>
          <Grid container spacing={3}>
            <Grid item lg={12} md={12} sm={12} xs={12} sx={{ display: "flex", justifyContent: "flex-end" }}>
              <Button
                variant="outlined"
                startIcon={<CloseIcon />}
                className={classes.addButton}
                onClick={onClose}
              >
                Cancel
              </Button>
              <Box m={0.5}></Box>

              <Button
                variant="contained"
                startIcon={<Delete />}
                className={classes.addButton}
                onClick={handleDelete}
                disabled={isLoading} // Disable button while loading
              >
                {isLoading ? (
                  <CircularProgress size={24} color="inherit" />
                ) : (
                  "Delete"
                )}
              </Button>
            </Grid>
          </Grid>
        </DialogActions>
      </Grid>
    </Dialog>
  );
};

export default DeletePopup;
