import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/shared/context/AuthContext";
import {
  approvePlan,
  createPlan,
  CreatePlanDto,
  deletePlan,
  getMinePlan,
  getMySubPlans,
  getPlan,
  getPlanList,
  getSectorList,
  getSubPlans,
  getTeamSubPlans,
  PlanParams,
  rejectPlan,
  requestApproval,
  updatePlan,
} from "../services/api/planService";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { MeDto } from "@/shared/dto/user/meDto";
import { SectorListParam } from "../types/planTypes";

//  Query Keys
const Plan_KEYS = {
  all: ["plans"] as const,
  list: (id: string, params?: PlanParams) =>
    ["plans", "list", id, params] as const,
  detail: (id: string) => ["plans", id] as const,
};

// Helper function to check if user is unit admin
export const checkIsUnitAdmin = (user: MeDto | null): boolean => {
  if (!user || !user.roles) return false;
  return user.roles.some((role) => role.key === "unit_admin");
};

export const checkIsPlanInitiator = (
  user: MeDto | null,
  positionId?: string
): boolean => {
  if (!user || !user.employee) return false;

  if (positionId) {
    // Check specific position
    return user.employee.some((emp) =>
      emp.positions.some(
        (pos) =>
          pos.employeePositionId === positionId &&
          pos.permissions.some((perm) => perm.key === "can:initiatePlan")
      )
    );
  }

  // Check all positions (fallback)
  return user.employee.some((emp) =>
    emp.positions.some((pos) =>
      pos.permissions.some((perm) => perm.key === "can:initiatePlan")
    )
  );
};

//  GET SINGLE Plan
export function usePlan(id: string) {
  return useQuery({
    queryKey: Plan_KEYS.detail(id),
    queryFn: () => getPlan(id),
    enabled: !!id,
  });
}
export function useSectorList(id?: string) {
  return useQuery({
    queryKey: ["plans-sector", "sector", id],
    queryFn: () => getSectorList(id),
    enabled: !!id,
  });
}

export function useMinePlan(params?: SectorListParam) {
  const { selectedPositionId } = useAuth();
  return useQuery({
    // Include selectedPositionId in the key so switching positions yields a
    // distinct cache entry and refetches with the up-to-date header.
    queryKey: ["my-plans", selectedPositionId, params],
    queryFn: () => getMinePlan(params),
  });
}
//  GET Plan LIST with optional params filtering
export function usePlanList(unitId: string, params?: PlanParams) {
  return useQuery({
    queryKey: Plan_KEYS.list(unitId, params),
    queryFn: () => getPlanList(unitId, params),
    enabled: !!unitId,
  });
}

export function useSubPlans(id: string) {
  return useQuery({
    queryKey: ["plans", "sub-plans", id],
    queryFn: () => getSubPlans(id),
    enabled: !!id,
  });
}
export function useMySubPlans(id: string) {
  return useQuery({
    queryKey: ["plans", "my-sub-plans", id],
    queryFn: () => getMySubPlans(id),
    enabled: !!id,
  });
}
export function useTeamSubPlans(id: string) {
  return useQuery({
    queryKey: ["plans", "team-sub-plans", id],
    queryFn: () => getTeamSubPlans(id),
    enabled: !!id,
  });
}
//UNIFIED HOOK - Returns all Plan operations in one object
export function usePlanMutations() {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const createMutation = useMutation({
    mutationFn: (data: CreatePlanDto) => createPlan(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      toast("Plan created successfully");
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      handleError(exception);
    },
  });

  const updateMutation = useMutation({
    mutationFn: (data: CreatePlanDto) => updatePlan(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      handleError(exception);
    },
  });
  const requestApprovalMutation = useMutation({
    mutationFn: (id: string) => requestApproval(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      toast("Plan Approval Requested successfully");
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      handleError(exception);
    },
  });
  const approveMutation = useMutation({
    mutationFn: (id: string) => approvePlan(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      toast("Plan Approved successfully");
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      handleError(exception);
    },
  });
  const rejectMutation = useMutation({
    mutationFn: (id: string) => rejectPlan(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      toast("Plan Rejected successfully");
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      handleError(exception);
    },
  });
  const deleteMutation = useMutation({
    mutationFn: (id: string) => deletePlan(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      toast("Plan deleted successfully");
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: Plan_KEYS.all });
      handleError(exception);
    },
  });

  return {
    create: createMutation,
    update: updateMutation,
    delete: deleteMutation,
    requestApproval: requestApprovalMutation,
    approve: approveMutation,
    reject: rejectMutation,
  };
}
