"use client";

import InvestConfirmModal from "@/components/sections/details/invest-confirm-modal";
import { createContext, ReactNode, use, useState } from "react";

interface ProjectData {
  title: string;
  slug: string;
  share_value: number;
  share_count?: number;
  max: number;
  onQuantityChange?: (quantity: number) => void;
}

interface InvestModalContextType {
  openModal: (data: ProjectData) => void;
  closeModal: () => void;
}

const InvestModalContext = createContext<InvestModalContextType | undefined>(undefined);

export const InvestModalProvider = ({ children }: { children: ReactNode }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [projectData, setProjectData] = useState<ProjectData | null>(null);

  const openModal = (data: ProjectData) => {
    setProjectData(data);
    setIsOpen(true);
  };

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

  return (
    <InvestModalContext.Provider value={{ openModal, closeModal }}>
      {children}
      {projectData && (
        <InvestConfirmModal
          isOpen={isOpen}
          onClose={closeModal}
          title={projectData.title}
          projectSlug={projectData.slug}
          shareCount={projectData.share_count}
          shareValue={projectData.share_value}
          max={projectData.max}
          onQuantityChange={projectData.onQuantityChange}
        />
      )}
    </InvestModalContext.Provider>
  );
};

export const useInvestModal = () => {
  const context = use(InvestModalContext);
  if (!context) throw new Error("useInvestModal must be used inside InvestModalProvider");
  return context;
};
