// hooks/useEmployeePlanMutations.ts
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { toast } from "sonner";
import { useAuth } from "@/shared/context/AuthContext";
import {
  createEmployeePlan,
  getEmployeePlan,
  getEmployeePlans,
  updateEmployeePlan,
  deleteEmployeePlan,
  getPlansByUnit,
  getPositionsByUnit,
  fetchImmediateChild,
  getServices,
  getParentEmployeePlanDetail,
  type CreateEmployeePlanDto,
  getEmployeePlanByPlanId,
  getEmployeeSubPlanByPlanId,
  getMyEmployeePlan,
  planParam,
} from "../services/api/employeePlanService";

// Query Keys
export const EMPLOYEE_PLAN_KEYS = {
  all: ["employee-plans"] as const,
  list: (planId: string) => ["employee-plans", "list", planId] as const,
  detail: (id: string) => ["employee-plans", id] as const,
  plansByUnit: (unitId: string) => ["employee-plans", "plans", unitId] as const,
  positionsByUnit: (unitId: string) =>
    ["employee-plans", "positions", unitId] as const,
  employeePositions: () => ["employee-plans", "employee-positions"] as const,
  services: ["employee-plans", "services"] as const,
  parentDetail: (id: string) => ["employee-plans", "parent", id] as const,
  planId: (planId: string) => ["employee-plans", "plan", planId] as const,
  subPlanId: (subPlanId: string) =>
    ["sub-employee-plans", "plan", subPlanId] as const,
};

// GET SINGLE Employee Plan
export function useEmployeePlan(id: string) {
  return useQuery({
    queryKey: EMPLOYEE_PLAN_KEYS.detail(id),
    queryFn: () => getEmployeePlan(id),
    enabled: !!id,
  });
}

// GET Employee Plans LIST by planId
export function useEmployeePlanList(planId: string) {
  return useQuery({
    queryKey: EMPLOYEE_PLAN_KEYS.list(planId),
    queryFn: () => getEmployeePlans(planId),
    enabled: !!planId,
  });
}

// GET Plans by Unit
export function usePlansByUnit(unitId: string) {
  return useQuery({
    queryKey: EMPLOYEE_PLAN_KEYS.plansByUnit(unitId),
    queryFn: () => getPlansByUnit(unitId),
    enabled: !!unitId,
  });
}

// GET Positions by Unit
export function usePositionsByUnit(unitId: string) {
  return useQuery({
    queryKey: EMPLOYEE_PLAN_KEYS.positionsByUnit(unitId),
    queryFn: () => getPositionsByUnit(unitId),
    enabled: !!unitId,
  });
}

// GET Employee Positions by Position ID
export function useEmployeePositions() {
  const { selectedPositionId } = useAuth();
  return useQuery({
    queryKey: [...EMPLOYEE_PLAN_KEYS.employeePositions(), selectedPositionId],
    queryFn: () => fetchImmediateChild(),
    enabled: true,
  });
}

// GET Services
export function useServices() {
  return useQuery({
    queryKey: EMPLOYEE_PLAN_KEYS.services,
    queryFn: () => getServices(),
  });
}

// GET MY Employee Plans
export function useMineEmployeePlan(params: planParam) {
  const { selectedPositionId } = useAuth();
  return useQuery({
    queryKey: ["my-employee-plans", selectedPositionId, params],
    queryFn: () => getMyEmployeePlan(params),
  });
}

// GET Employee Plans by Plan ID
export function useEmployeePlanByPlanId(planId: string) {
  const { selectedPositionId } = useAuth();
  return useQuery({
    queryKey: [...EMPLOYEE_PLAN_KEYS.planId(planId), selectedPositionId],
    queryFn: () => getEmployeePlanByPlanId(planId),
    enabled: !!planId,
  });
}
// GET Sub Employee Plans by Plan ID
export function useSubEmployeePlanByPlanId(planId: string) {
  const { selectedPositionId } = useAuth();
  return useQuery({
    queryKey: [...EMPLOYEE_PLAN_KEYS.subPlanId(planId), selectedPositionId],
    queryFn: () => getEmployeeSubPlanByPlanId(planId),
    enabled: !!planId,
  });
}
// GET Parent Employee Plan Detail
export function useParentEmployeePlanDetail(id: string) {
  return useQuery({
    queryKey: EMPLOYEE_PLAN_KEYS.parentDetail(id),
    queryFn: () => getParentEmployeePlanDetail(id),
    enabled: !!id,
  });
}

// Extended DTO interface to include all fields from your form
export interface ExtendedEmployeePlanDto extends CreateEmployeePlanDto {
  id?: string;
}

// UNIFIED HOOK - Returns all Employee Plan operations in one object
export function useEmployeePlanMutations() {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const createMutation = useMutation({
    mutationFn: (data: ExtendedEmployeePlanDto) => {
      const { id, ...createData } = data;
      return createEmployeePlan(createData);
    },
    onError: (exception) => {
      handleError(exception);
    },
  });

  const updateMutation = useMutation({
    mutationFn: (data: ExtendedEmployeePlanDto) => {
      if (!data.id) {
        throw new Error("Employee plan ID is required for update");
      }
      const { id, ...updateData } = data;
      return updateEmployeePlan(id, updateData);
    },
    onError: (exception) => {
      handleError(exception);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => deleteEmployeePlan(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: EMPLOYEE_PLAN_KEYS.all });
      toast.success("Employee plan deleted successfully");
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: EMPLOYEE_PLAN_KEYS.all });
      handleError(exception);
    },
  });

  return {
    create: createMutation,
    update: updateMutation,
    delete: deleteMutation,
  };
}
