import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import {
  sealService,
  CreateSealPayload,
  SealListResponse,
  SealResponseDto,
  SealStatusUpdatePayload,
} from "../services/api/sealService";

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

  // Query for fetching all seals
  const {
    data: sealsData,
    isLoading: isLoadingSeals,
    isError: isSealsError,
    refetch: refetchSeals,
  } = useQuery<SealListResponse>({
    queryKey: ["seals"],
    queryFn: async () => {
      const response = await sealService.getSeals();
      return response.data;
    },
    enabled: false,
  });

  // Query for fetching a single seal
  const getSealsByUnitId = (id: string | null) => {
    return useQuery({
      queryKey: ["seal", id],
      queryFn: async () => {
        if (id) {
          const response = await sealService.getSealListsByUnitId(id);
          return response.data;
        }
      },
      enabled: !!id,
    });
  };
  // Query for fetching a single seal
  const getSealsById = (id: string | null) => {
    return useQuery({
      queryKey: ["seal", id],
      queryFn: async () => {
        if (id) {
          const response = await sealService.getSeal(id);
          return response.data;
        }
      },
      enabled: !!id,
    });
  };

  // Mutation for creating a seal
  const createSealMutation = useMutation<
    SealResponseDto,
    Error,
    CreateSealPayload
  >({
    mutationFn: async (payload) => {
      const response = await sealService.createSeal(payload);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["seals"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // Mutation for updating a seal
  const updateSealMutation = useMutation({
    mutationFn: async ({
      id,
      payload,
    }: {
      id: string;
      payload: Partial<CreateSealPayload>;
    }) => {
      const response = await sealService.updateSeal(id, payload);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["seal"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // Mutation for deleting a seal (actually deactivates via change-status)
  const deleteSealMutation = useMutation({
    mutationFn: async (id: string) => {
      await sealService.changeSealStatus(id, { isCurrent: false });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["seals"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // Mutation for updating seal upload status
  const updateSealStatusMutation = useMutation({
    mutationFn: async ({
      id,
      updateSealStatusPayload,
    }: {
      id: string;
      updateSealStatusPayload: SealStatusUpdatePayload;
    }) => {
      const response = await sealService.updateSealUploadStatus(
        id,
        updateSealStatusPayload
      );
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["seals"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  return {
    // Queries
    seals: sealsData?.items || [],
    totalSeals: sealsData?.count || 0,
    isLoadingSeals,
    isSealsError,
    refetchSeals,
    getSealsByUnitId,
    getSealsById,

    // Mutations
    createSeal: createSealMutation.mutateAsync,
    isCreatingSeal: createSealMutation.isPending,
    updateSeal: updateSealMutation.mutate,
    isUpdatingSeal: updateSealMutation.isPending,
    deleteSeal: deleteSealMutation.mutate,
    isDeletingSeal: deleteSealMutation.isPending,
    updateSealStatus: updateSealStatusMutation.mutateAsync,
    isUpdatingStatus: updateSealStatusMutation.isPending,
  };
};
