"use client";

import React from "react";
import { Stack, Typography, Button, Alert } from "@mui/material";
import Modal from "@/app/components/Modal/Modal";
import Spinner from "@/app/components/Spinner/Spinner";
import { IDeleteModalProps } from "./types";

const DeleteModal: React.FC<IDeleteModalProps> = ({
  open,
  onClose,
  onConfirm,
  resource,
  resourceType = "item",
  isLoading = false,
  error = null,
}) => {
  const handleConfirm = async () => {
    if (!resource?.id) return;
    await Promise.resolve(onConfirm(resource.id));
  };

  const handleClose = () => {
    if (!isLoading) {
      onClose();
    }
  };

  const resourceLabel = resource?.label || `this ${resourceType}`;
  const title = `Delete ${resourceType.charAt(0).toUpperCase() + resourceType.slice(1)}`;

  return (
    <Modal open={open} onClose={handleClose} title={title}>
      <Stack spacing={3}>
        <Typography variant="body1">
          Are you sure you want to delete <strong>{resourceLabel}</strong>? This
          action cannot be undone.
        </Typography>

        {error && (
          <Alert severity="error" sx={{ mt: 1 }}>
            {error}
          </Alert>
        )}

        <Stack direction="row" spacing={2} justifyContent="flex-end">
          <Button variant="outlined" onClick={handleClose} disabled={isLoading}>
            Cancel
          </Button>
          <Button
            color="error"
            variant="contained"
            onClick={handleConfirm}
            disabled={isLoading || !resource?.id}
            startIcon={isLoading ? <Spinner size="small" color="#fff" /> : null}
          >
            {isLoading ? "Deleting..." : `Delete ${resourceType}`}
          </Button>
        </Stack>
      </Stack>
    </Modal>
  );
};

export default DeleteModal;
