import React, { createContext, useCallback, useContext, useMemo, useState } from "react";
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, Typography } from "@mui/material";

type ConfirmOptions = {
  title?: string;
  message: string;
  confirmLabel?: string;
  cancelLabel?: string;
  destructive?: boolean;
};

type ConfirmContextValue = {
  confirm: (options: ConfirmOptions) => Promise<boolean>;
};

type ConfirmState = ConfirmOptions & {
  open: boolean;
  resolver?: (value: boolean) => void;
};

const ConfirmContext = createContext<ConfirmContextValue | null>(null);

export function ConfirmProvider({ children }: { children: React.ReactNode }) {
  const [state, setState] = useState<ConfirmState>({
    open: false,
    message: "",
    title: "Confirm action",
    confirmLabel: "Confirm",
    cancelLabel: "Cancel",
    destructive: false,
  });

  const closeWith = useCallback((value: boolean) => {
    setState((prev) => {
      prev.resolver?.(value);
      return { ...prev, open: false, resolver: undefined };
    });
  }, []);

  const confirm = useCallback((options: ConfirmOptions) => {
    return new Promise<boolean>((resolve) => {
      setState({
        open: true,
        title: options.title ?? "Confirm action",
        message: options.message,
        confirmLabel: options.confirmLabel ?? "Confirm",
        cancelLabel: options.cancelLabel ?? "Cancel",
        destructive: options.destructive ?? false,
        resolver: resolve,
      });
    });
  }, []);

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

  return (
    <ConfirmContext.Provider value={value}>
      {children}
      <Dialog open={state.open} onClose={() => closeWith(false)} fullWidth maxWidth="xs">
        <DialogTitle>{state.title}</DialogTitle>
        <DialogContent>
          <Alert severity={state.destructive ? "warning" : "info"} variant="outlined" sx={{ mb: 2 }}>
            {state.destructive ? "This action may be hard to undo." : "Please confirm this action."}
          </Alert>
          <Typography sx={{ color: "text.secondary" }}>{state.message}</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => closeWith(false)}>{state.cancelLabel}</Button>
          <Button color={state.destructive ? "error" : "primary"} variant="contained" onClick={() => closeWith(true)}>
            {state.confirmLabel}
          </Button>
        </DialogActions>
      </Dialog>
    </ConfirmContext.Provider>
  );
}

export function useConfirm() {
  const ctx = useContext(ConfirmContext);
  if (!ctx) throw new Error("useConfirm must be used within ConfirmProvider");
  return ctx;
}
