"use client";
import ListShareModal from "@/components/modals/list-share-modal";
import { createContext, useState, use, ReactNode } from "react";

interface ListModalData {
  project_id: number;
  active_shares: number;
}

interface ListShareModalContextType {
  openListModal: (data: ListModalData) => void;
  closeListModal: () => void;
}

const ListShareModalContext = createContext<
  ListShareModalContextType | undefined
>(undefined);

export const ListShareModalProvider = ({
  children,
}: {
  children: ReactNode;
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [modalData, setModalData] = useState<ListModalData | null>(null);

  const openListModal = (data: ListModalData) => {
    setModalData(data);
    setIsOpen(true);
  };

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

  return (
    <ListShareModalContext.Provider value={{ openListModal, closeListModal }}>
      {children}
      {modalData && (
        <ListShareModal
          isOpen={isOpen}
          onClose={closeListModal}
          project_id={modalData.project_id}
          active_shares={modalData.active_shares}
        />
      )}
    </ListShareModalContext.Provider>
  );
};

export const useListSharesModal = () => {
  const context = use(ListShareModalContext);
  if (!context)
    throw new Error(
      "useListSharesModal must be used inside ListShareModalProvider",
    );
  return context;
};
