"use client";

import * as React from "react";
import type {
  Deal,
  KanbanBoardCopy,
  Stage,
} from "../types";
import type { KanbanClientBoardFilters } from "./deal-kanban-client-filters";
import type { LeadsListParams } from "@/features/leads/types";
import type { CustomerPaymentKpis } from "@/api/rtk/customers-api";

export type KanbanBoardContextValue = {
  boardUiKey: string;
  stages: Stage[];
  convertedDealIds: Set<string>;
  expandedByParentId: Record<string, boolean>;
  onOpen: (deal: Deal) => void;
  onEdit: (deal: Deal) => void;
  onDelete: (id: string) => void;
  onAssignTask?: (deal: Deal) => void;
  canManageStages: boolean;
  boardCopy: KanbanBoardCopy;
  boardPagingEnabled: boolean;
  boardPagingEntity: "leads" | "business";
  businessPipelineId?: string;
  boardListParams?: LeadsListParams;
  inflightStageByDealId?: ReadonlyMap<string, string>;
  stageCounts: Record<string, number>;
  onColumnDealsChange?: (columnKey: string, deals: Deal[]) => void;
  columnSerialByStageId: Map<string, number>;
  leadsStagedPaging: boolean;
  restStagesUnlocked: boolean;
  onLeadsPriorityColumnReady: (index: number) => void;
  kanbanPermissions: { source: unknown };
  canDragCards: boolean;
  clientSearchQuery?: string;
  kanbanClientBoardFilters?: KanbanClientBoardFilters;
  leadsUnifiedSearchActive: boolean;
  unifiedSearchBuckets?: Record<string, { items: Deal[]; total: number }>;
  canSubject: "lead" | "deal";
  closedWonCustomerPaymentKpis?: CustomerPaymentKpis | null;
  closedWonCustomerPaymentKpisLoading: boolean;
  refetchOnMountStageId: string | null;
  teams?: Array<{ id: string; name: string }>;
  timelineIntents: Array<{ id: string; name: string }>;
};

const KanbanBoardContext = React.createContext<KanbanBoardContextValue | null>(null);

export function KanbanBoardProvider({
  value,
  children,
}: {
  value: KanbanBoardContextValue;
  children: React.ReactNode;
}) {
  return (
    <KanbanBoardContext.Provider value={value}>{children}</KanbanBoardContext.Provider>
  );
}

export function useKanbanBoardContext(): KanbanBoardContextValue {
  const ctx = React.useContext(KanbanBoardContext);
  if (!ctx) {
    throw new Error("useKanbanBoardContext must be used within KanbanBoardProvider");
  }
  return ctx;
}
