import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Alert,
  CircularProgress,
} from "@mui/material";
import { useState, useEffect } from "react";

interface StatusChangeDialogProps {
  open: boolean;
  newStatus: string;
  reason: string;
  setReason: React.Dispatch<React.SetStateAction<string>>;
  handleClose: () => void;
  handleSave: () => void;
  isSubmitting?: boolean;
  errorMessage?: string | null;
}

const StatusChangeDialog = ({
  open,
  newStatus,
  reason,
  setReason,
  handleClose,
  handleSave,
  isSubmitting = false,
  errorMessage,
}: StatusChangeDialogProps) => {
  const [isValid, setIsValid] = useState(false);

  useEffect(() => {
    const noSpaces = reason.replace(/\s/g, "");
    const length = noSpaces.length;
    setIsValid(length >= 12 && length <= 400);
  }, [reason]);

  return (
    <Dialog open={open} onClose={handleClose} fullWidth maxWidth="sm">
      <DialogTitle>Change Status</DialogTitle>
      <DialogContent>
        You want to change the status to <b>{newStatus}</b>. Please provide a
        reason for the change.
        <TextField
          label="Reason for change"
          variant="outlined"
          fullWidth
          multiline
          rows={4}
          value={reason}
          onChange={e => setReason(e.target.value)}
          helperText="Reason must be between 12 and 400 characters"
          sx={{ mt: 2 }}
        />
        {errorMessage && (
          <Alert severity="error" sx={{ mt: 2 }}>
            {errorMessage}
          </Alert>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} disabled={isSubmitting}>
          Cancel
        </Button>
        <Button
          variant="contained"
          onClick={handleSave}
          disabled={!isValid || isSubmitting}
          startIcon={isSubmitting ? <CircularProgress size={18} /> : undefined}
        >
          Save
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default StatusChangeDialog;
