import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  getPositions,
  PositionQueryParams,
  getPositionById,
  getPositionHierarchy,
  getPositionList,
  getEmployeesUnderPosition,
  PositionPayload,
  createPosition,
  updatePosition,
  deletePosition,
  MovePostionPayload,
  movePosition,
} from "@/user-management/services/api/positionService";

import { PositionDto } from "../dto/positions/positionDto";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

export interface Position {
  id: string;
  name: string;
  code?: string;
  parentId?: string;
  organizationId?: string;
  isExpanded?: boolean;
  children?: PositionDto[];
}

export interface PositionWithEmployees extends Position {
  employees?: any[];
}

export const usePositions = (params?: PositionQueryParams) => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  // Main positions query
  const usePositionsQuery = () => {
    return useQuery({
      queryKey: ["positions", params],
      queryFn: () => getPositions(params),
      select: (data) => ({
        count: data.data.count as number,
        items: data.data.items as PositionDto[],
      }),
      staleTime: 5 * 60 * 1000,
      enabled: params ? true : false,
    });
  };

  // Single position by ID
  const usePositionById = (id: string) => {
    return useQuery({
      queryKey: ["position", id],
      queryFn: () => getPositionById(id),
      enabled: !!id,
      select: (data) => data.data,
    });
  };

  // Position hierarchy
  const usePositionHierarchy = (id: string = "root") => {
    return useQuery({
      queryKey: ["positionHierarchy", id],
      queryFn: () => getPositionHierarchy(id),
      enabled: !!id,
      select: (data) => data.data,
    });
  };

  // Employees under position
  const useEmployeesUnderPosition = (positionId: string) => {
    return useQuery({
      queryKey: ["positionEmployees", positionId],
      queryFn: () => getEmployeesUnderPosition(positionId),
      enabled: !!positionId || params ? true : false,
    });
  };

  // Position list by unit/organization
  const usePositionListByUnitId = (
    organizationId: string,
    params: PositionQueryParams
  ) => {
    return useQuery({
      queryKey: ["positionList", organizationId, params],
      queryFn: () => getPositionList(organizationId, params),
      enabled: !!organizationId,
      select: (data) => data.data,
    });
  };
  const createPositionMutation = useMutation({
    mutationFn: ({
      payload,
      successCallback,
    }: {
      payload: PositionPayload;
      successCallback: () => void;
    }) => createPosition(payload),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["positionHierarchy"] });
      variables.successCallback();
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const updatePositionMutation = useMutation({
    mutationFn: ({
      id,
      payload,
      successCallback,
    }: {
      id: string;
      payload: PositionPayload;
      successCallback: () => void;
    }) => updatePosition(id, payload),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["positionHierarchy"] });
      variables.successCallback();
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const deletePositionMutation = useMutation({
    mutationFn: ({
      id,
      successCallback,
    }: {
      id: string;
      successCallback: () => void;
    }) => deletePosition(id),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["positionHierarchy"] });
      toast.success("Department removed successfully.");

      variables.successCallback();
    },
    onError: (error: any) => {
      // Check if it's a "Referenced Entity" error (meaning department has related employees)
      if (error?.response?.status === 400 && error?.response?.data?.message) {
        const errorMessage = error?.response?.data?.message;
        
        if (errorMessage.includes("Referenced Entity") || errorMessage.includes("referenced")) {
          toast.error(
            t("department.cannotDeleteWithEmployees", "Cannot delete department with assigned employees"),
            {
              description: t("department.reassignEmployeesFirst", "Please reassign or remove all employees from this department first."),
              duration: 5000
            }
          );
        } else {
          handleError(error);
        }
      } else {
        handleError(error);
      }
    },
  });

  return {
    usePositionsQuery,
    usePositionById,
    usePositionHierarchy,
    useEmployeesUnderPosition,
    usePositionListByUnitId,
    createPosition: createPositionMutation.mutateAsync,
    isCreating: createPositionMutation.isPending,
    updatePosition: updatePositionMutation.mutateAsync,
    isUpdating: updatePositionMutation.isPending,
    deletePosition: deletePositionMutation.mutateAsync,
    isDeleting: deletePositionMutation.isPending,
  };
};

export const useMovePosition = () => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  return useMutation({
    mutationFn: (data: MovePostionPayload) => movePosition(data),
    onSuccess: (_data, variables) => {
      // ✅ Invalidate anything related to positions so UI updates
      queryClient.invalidateQueries({ queryKey: ["positions"] });
      queryClient.invalidateQueries({ queryKey: ["positionHierarchy"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });
};
