import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  getOrganizations,
  createOrganization,
  OrgQueryParams,
  OrganizationPayload,
  getOrganizationById,
  updateOrganization,
} from "@/record-management/services/api/organizationsService";
import { AxiosError } from "axios";
import { OrganizationDto } from "@/record-management/dto/organization/organizationDto";

import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

export const useOrganizations = (params?: OrgQueryParams) => {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const {
    data: organizationsResponse,
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["organizations", params],
    queryFn: async () => {
      const { data } = await getOrganizations(params);
      return {
        count: data.count as number,
        items: data.items as OrganizationDto[],
      };
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  const {
    mutate: createMutation,
    isPending: isOrganizationCreating,
    isError: organizationCreationError,
  } = useMutation({
    mutationFn: async (payload: OrganizationPayload) => {
      const { data } = await createOrganization(payload);
      return data;
    },
    onSuccess: () => {
      toast.success("Organization created successfully!", {
        description: "Redirecting...",
      });

      navigate("/organizations");
      queryClient.invalidateQueries({ queryKey: ["organizations"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });
  const {
    mutate: editMutation,
    isPending: isOrganizationEditing,
    isError: organizationEditError,
    status: organizationEditStatus,
  } = useMutation({
    mutationFn: async ({
      id,
      payload,
    }: {
      id: string;
      payload: OrganizationPayload;
    }) => {
      const { data } = await updateOrganization(id, payload);
      return data;
    },
    onSuccess: () => {
      toast.success("Organization created successfully!", {
        description: "Redirecting...",
      });

      navigate("/organizations");
      queryClient.invalidateQueries({ queryKey: ["organizations"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const { mutate: getOrganization, isPending: isFetchingOrganization } =
    useMutation({
      mutationFn: async (id: string) => {
        const { data } = await getOrganizationById(id);
        return data;
      },
      onSuccess: (data) => {
        return data;
      },
    });

  return {
    organizationsResponse,
    isLoading,
    isError,
    refetch,
    createOrganization: createMutation,
    editOrganization: editMutation,
    isCreating: isOrganizationCreating,
    isEditing: isOrganizationEditing,
    editStatus: organizationEditStatus,
    organizationCreationError,
    organizationEditError,
    getOrganizationByDetails: getOrganization,
    isFetchingOrganization,
  };
};
