import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  permissionService,
  CreatePermissionDto,
  PermissionQueryParams,
} from "../services/api/permissionService";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import {
  PermissionDto,
  PermissionListResponse,
} from "../dto/permissions/permissonDto";

interface UsePermissionManagerProps {
  params?: PermissionQueryParams;
  permissionId?: string;
}

export const usePermissionManager = ({
  params,
  permissionId,
}: UsePermissionManagerProps = {}) => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  // Fetch all permissions
  const {
    data: permissions,
    isLoading: isPermissionsLoading,
    refetch: refetchPermissions,
  } = useQuery<PermissionListResponse>({
    queryKey: ["permissions", params],
    queryFn: () => permissionService.getAll(params).then((res) => res.data),
    enabled: !!params,
    staleTime: 1000 * 60 * 5,
  });

  // Fetch single permission (for edit)
  const {
    data: selectedPermission,
    isLoading: isPermissionLoading,
    refetch: refetchPermission,
  } = useQuery<PermissionDto>({
    queryKey: ["permission", permissionId],
    queryFn: () =>
      permissionService.getById(permissionId!).then((res) => res.data),
    enabled: !!permissionId,
  });

  // Create
  const createPermission = useMutation({
    mutationFn: (payload: CreatePermissionDto) =>
      permissionService.create(payload),
    onSuccess: () => {
      toast.success("Permission created");
      queryClient.invalidateQueries({ queryKey: ["permissions"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // Update
  const updatePermission = useMutation({
    mutationFn: ({ id, data }: { id: string; data: CreatePermissionDto }) =>
      permissionService.update(id, data),
    onSuccess: () => {
      toast.success("Permission updated");
      queryClient.invalidateQueries({ queryKey: ["permissions"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // Delete
  const deletePermission = useMutation({
    mutationFn: (id: string) => permissionService.delete(id),
    onSuccess: () => {
      toast.success("Permission deleted");
      queryClient.invalidateQueries({ queryKey: ["permissions"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  return {
    permissions,
    selectedPermission,
    isPermissionsLoading,
    isPermissionLoading,
    refetchPermissions,
    refetchPermission,
    createPermission,
    updatePermission,
    deletePermission,
  };
};
