import React, { createContext, useContext, useState, useCallback } from 'react';
import Popup from '@/components/Popup';

const PopupContext = createContext();

export const PopupProvider = ({ children }) => {
  const [popupState, setPopupState] = useState({
    visible: false,
    message: '',
    onConfirm: null,
    onCancel: null,
  });

  const showPopup = useCallback((message, onConfirm, onCancel) => {
    setPopupState({
      visible: true,
      message,
      onConfirm: () => {
        setPopupState((prev) => ({ ...prev, visible: false }));
        if (onConfirm) onConfirm();
      },
      onCancel: () => {
        setPopupState((prev) => ({ ...prev, visible: false }));
        if (onCancel) onCancel();
      },
    });
  }, []);

  return (
    <PopupContext.Provider value={{ showPopup }}>
      <Popup
        isOpen={popupState.visible}
        message={popupState.message}
        onConfirm={popupState.onConfirm}
        onCancel={popupState.onCancel}
        popupClassName="fixed z-[9999] inset-0 flex items-center justify-center"
      />
      {children}
    </PopupContext.Provider>
  );
};

export const usePopup = () => useContext(PopupContext);
