import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import { createContext, useCallback, useContext, useMemo, useRef, useState } from "react";
import { Button } from "./Button.jsx";

const ConfirmContext = createContext(null);

export function ConfirmProvider({ children }) {
  const resolverRef = useRef(null);
  const [state, setState] = useState(null);

  const confirm = useCallback((options) => {
    setState({
      title: options.title || "确认操作",
      message: options.message || "该操作提交后会立即生效。",
      confirmText: options.confirmText || "确认",
      tone: options.tone || "primary"
    });

    return new Promise((resolve) => {
      resolverRef.current = resolve;
    });
  }, []);

  const close = useCallback((result) => {
    resolverRef.current?.(result);
    resolverRef.current = null;
    setState(null);
  }, []);

  const value = useMemo(() => ({ confirm }), [confirm]);

  return (
    <ConfirmContext.Provider value={value}>
      {children}
      <Dialog className="confirm-dialog" maxWidth="xs" onClose={() => close(false)} open={Boolean(state)} fullWidth>
        <DialogTitle>{state?.title}</DialogTitle>
        <DialogContent className="confirm-dialog__content">{state?.message}</DialogContent>
        <DialogActions>
          <Button onClick={() => close(false)}>取消</Button>
          <Button variant={state?.tone === "danger" ? "danger" : "primary"} onClick={() => close(true)}>
            {state?.confirmText}
          </Button>
        </DialogActions>
      </Dialog>
    </ConfirmContext.Provider>
  );
}

export function useConfirm() {
  const context = useContext(ConfirmContext);
  if (!context) {
    throw new Error("useConfirm must be used inside ConfirmProvider");
  }
  return context.confirm;
}
