import { createContext, ReactNode, useCallback, useMemo } from 'react';
import { useCreateProposal, useUpdateProposalStatus } from '@/hooks/api/useProposalsAPI.ts';
import type { Proposal } from '@/types.ts';

interface PartnershipContextType {
  createProposal: (newProposalData: Omit<Proposal, 'id' | 'createdAt' | 'status'>) => void;
  updateProposalStatus: (proposalId: string, status: Proposal['status']) => void;
  isLoading?: boolean;
}

export const PartnershipContext = createContext<PartnershipContextType | undefined>(undefined);

export const PartnershipProvider = ({ children }: { children?: ReactNode }) => {
  const createProposalMutation = useCreateProposal();
  const updateProposalStatusMutation = useUpdateProposalStatus();

  const createProposal = useCallback(
    (newProposalData: Omit<Proposal, 'id' | 'createdAt' | 'status'>) => {
      createProposalMutation.mutate({
        from_org_id: newProposalData.fromOrgId,
        to_org_id: newProposalData.toOrgId,
        resource_id: newProposalData.resourceId,
        resource_type: newProposalData.resourceType,
        resource_name: newProposalData.resourceName,
        message: newProposalData.message,
      });
    },
    [createProposalMutation]
  );

  const updateProposalStatus = useCallback(
    (proposalId: string, status: Proposal['status']) => {
      updateProposalStatusMutation.mutate({ id: proposalId, status });
    },
    [updateProposalStatusMutation]
  );

  const value = useMemo(
    () => ({
      createProposal,
      updateProposalStatus,
      isLoading: createProposalMutation.isPending || updateProposalStatusMutation.isPending,
    }),
    [
      createProposal,
      updateProposalStatus,
      createProposalMutation.isPending,
      updateProposalStatusMutation.isPending,
    ]
  );

  return <PartnershipContext.Provider value={value}>{children}</PartnershipContext.Provider>;
};
