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

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

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

type ConfirmState = ConfirmOptions & {
  open: boolean;
};

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

export function ConfirmProvider({ children }: { children: React.ReactNode }) {
  const i18n = useOptionalI18n();
  const resolverRef = useRef<((value: boolean) => void) | null>(null);
  const [state, setState] = useState<ConfirmState>({
    open: false,
    message: "",
    title: "Confirm action",
    confirmLabel: "Confirm",
    cancelLabel: "Cancel",
    destructive: false,
  });

  const closeWith = useCallback((value: boolean) => {
    const resolve = resolverRef.current;
    resolverRef.current = null;
    setState((prev) => ({ ...prev, open: false }));
    resolve?.(value);
  }, []);

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

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

  return (
    <ConfirmContext.Provider value={value}>
      {children}
      <Dialog open={state.open} onClose={() => closeWith(false)} fullWidth maxWidth="xs"
        slotProps={{ paper: { sx: { borderRadius: 3, border: 1, borderColor: "divider", backgroundImage: "none" } } }}>
        <DialogTitle sx={{ pb: 1, fontWeight: 800 }}>{state.title}</DialogTitle>
        <DialogContent>
          <Alert severity={state.destructive ? "warning" : "info"} variant="outlined" sx={{ mb: 2 }}>
            {state.destructive
              ? i18n?.t("confirmDestructiveHint") ?? "This action may be hard to undo."
              : i18n?.t("confirmStandardHint") ?? "Please confirm this action."}
          </Alert>
          <Typography sx={{ color: "text.secondary" }}>{state.message}</Typography>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2.5, gap: 1 }}>
          <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;
}
