import { useQuery } from "@tanstack/react-query";
import {
  getEmployeePlanByPlanId,
  getEmployeeSubPlanByPlanId,
} from "../services/api/employeePlanService";
interface CombinedEmployeePlanResponse {
  items: any[];
  total: number;
}

export const useCombinedEmployeePlanByPlanId = (planId: string | undefined) => {
  // Main query that intelligently fetches data
  const query = useQuery<CombinedEmployeePlanResponse>({
    queryKey: ["combined-employee-plan", planId],
    queryFn: async () => {
      if (!planId) return { items: [], total: 0 };

      try {
        // First, try to get data from the sub endpoint (this has actual plan data)
        const subResponse = await getEmployeeSubPlanByPlanId(planId);

        if (subResponse.data?.items && subResponse.data.items.length > 0) {
          return {
            items: subResponse.data.items,
            total: subResponse.data.total || subResponse.data.items.length,
          };
        }

        // If sub endpoint returns empty, try the initial endpoint
        const initialResponse = await getEmployeePlanByPlanId(planId);

        if (initialResponse.data?.items) {
          // Transform initial data to match the expected format
          const transformedItems = initialResponse.data.items.map(
            (item: any) => ({
              ...item,
              weeks: {}, // Initialize empty weeks object
              no_of_employee_plans: "0", // No plans exist yet
            })
          );

          return {
            items: transformedItems,
            total: transformedItems.length,
          };
        }

        // Both endpoints returned empty
        return { items: [], total: 0 };
      } catch (error) {
        console.error("Error fetching employee plans:", error);
        // Return empty but don't throw - we'll show empty state in UI
        return { items: [], total: 0 };
      }
    },
    enabled: !!planId,
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes
  });

  return {
    data: query.data,
    isLoading: query.isLoading,
    error: query.error,
    refetch: query.refetch,
  };
};
