import { useState, type ReactNode } from "react";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogActions from "@mui/material/DialogActions";
import MuiButton from "@mui/material/Button";
import useDialogScrollLock from "./useDialogScrollLock";

export interface ConfirmDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: () => void;
  title: string;
  message: string;
  confirmText?: string;
  cancelText?: string;
  confirmVariant?: "primary" | "danger";
  loading?: boolean;
  /** Optional extra content rendered below the message (e.g. a checkbox). */
  children?: ReactNode;
}

/** Confirmation dialog over MUI Dialog. Preserves the legacy ConfirmModal prop shape. */
export default function ConfirmDialog({
  isOpen,
  onClose,
  onConfirm,
  title,
  message,
  confirmText = "Potvrdit",
  cancelText = "Zrušit",
  confirmVariant = "primary",
  loading = false,
  children,
}: ConfirmDialogProps) {
  useDialogScrollLock(isOpen);
  // Freeze content + label + loading while open, so neither the message NOR the
  // confirm button label flips during the close fade-out (e.g. on confirm,
  // `loading` goes false a beat before the dialog finishes closing — without
  // this the button would flash back to "Smazat"/confirmText). React
  // "adjust state from props during render": update only while open. Also keeps
  // content from flashing empty when the caller clears its row on close.
  const [shown, setShown] = useState({
    title,
    message,
    confirmText,
    cancelText,
    confirmVariant,
    loading,
  });
  if (
    isOpen &&
    (shown.title !== title ||
      shown.message !== message ||
      shown.confirmText !== confirmText ||
      shown.cancelText !== cancelText ||
      shown.confirmVariant !== confirmVariant ||
      shown.loading !== loading)
  ) {
    setShown({
      title,
      message,
      confirmText,
      cancelText,
      confirmVariant,
      loading,
    });
  }

  return (
    <Dialog
      open={isOpen}
      onClose={shown.loading ? undefined : onClose}
      disableScrollLock
      slotProps={{ paper: { sx: { borderRadius: 3 } } }}
    >
      <DialogTitle>{shown.title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{shown.message}</DialogContentText>
        {children}
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <MuiButton onClick={onClose} color="inherit" disabled={shown.loading}>
          {shown.cancelText}
        </MuiButton>
        <MuiButton
          onClick={onConfirm}
          variant="contained"
          color={shown.confirmVariant === "danger" ? "error" : "primary"}
          disabled={shown.loading}
        >
          {shown.loading ? "Zpracovávám…" : shown.confirmText}
        </MuiButton>
      </DialogActions>
    </Dialog>
  );
}
