import BuyShareModal from "@/components/sections/marketplace/buy-share-modal";
import { createContext, ReactNode, use, useState } from "react";

interface BuyShareData {
  project_id: number;
  seller_id: number | null;
  price: number;
  number_of_shares: number;
  shareCount?: number;
  onQuantityChange?: (quantity: number) => void;
}

interface BuyShareModalContextType {
  openBuyModal: (data: BuyShareData) => void;
  closeBuyModal: () => void;
}

const BuyShareModalContext = createContext<BuyShareModalContextType | undefined>(undefined);

export const BuyShareModalProvider = ({ children }: { children: ReactNode }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [shareData, setShareData] = useState<BuyShareData | null>(null);

  const openBuyModal = (data: BuyShareData) => {
    setShareData(data);
    setIsOpen(true);
  };

  const closeBuyModal = () => setIsOpen(false);

  return (
    <BuyShareModalContext.Provider value={{ openBuyModal, closeBuyModal }}>
      {children}
      {shareData && (
        <BuyShareModal
          isOpen={isOpen}
          onClose={closeBuyModal}
          projectId={shareData.project_id}
          sellerId={shareData.seller_id}
          price={shareData.price}
          maxShares={shareData.number_of_shares}
          shareCount={shareData.shareCount}
          onQuantityChange={shareData.onQuantityChange}
        />
      )}
    </BuyShareModalContext.Provider>
  );
};

export const useBuySharesModal = () => {
  const context = use(BuyShareModalContext);
  if (!context) throw new Error("useBuySharesModal must be used inside BuyShareModalProvider");
  return context;
};
