// hooks/useRecordTagPrefixes.ts
"use client";

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

import {
  CreatePrefixPayload,
  PrefixSuffixListResponseDto,
  prefixSuffixService,
} from "../services/api/prefixSuffixService";

export interface UseRecordTagPrefixesParams {
  unitId: string;
  recordTagId?: string;
  skip?: number;
  take?: number;
}

export const useRecordTagPrefixes = ({
  unitId,
  recordTagId,
  skip = 0,
  take = 10,
}: UseRecordTagPrefixesParams) => {
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const queryClient = useQueryClient();

  // --- Get Prefixes by Record Tag ---
  const {
    data: prefixesResponse,
    isLoading: isLoadingPrefixes,
    isError: isErrorPrefixes,
    refetch: refetchPrefixes,
  } = useQuery<PrefixSuffixListResponseDto>({
    queryKey: ["recordTagPrefixes", unitId, recordTagId, skip, take],
    queryFn: async () => {
      const { data } = await prefixSuffixService.getPrefixByRecordTagId(
        unitId,
        recordTagId!,
        skip,
        take,
      );
      return data;
    },
    enabled: !!unitId && !!recordTagId,
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  // --- Create Prefix for Tag ---
  const { mutate: createPrefix, isPending: isCreatingPrefix } = useMutation({
    mutationFn: async (payload: CreatePrefixPayload) => {
      const { data } = await prefixSuffixService.createPrefix(payload);
      return data;
    },
    onSuccess: () => {
      toast.success(
        t("prefixes.createdSuccess") || "Prefix created successfully ✅",
      );
      queryClient.invalidateQueries({
        queryKey: ["recordTagPrefixes", unitId, recordTagId],
      });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // --- Delete Prefix ---
  const { mutate: deletePrefix, isPending: isDeletingPrefix } = useMutation({
    mutationFn: async (prefixId: string) => {
      const { data } = await prefixSuffixService.deletePrefix(prefixId);
      return data;
    },
    onSuccess: () => {
      toast.success(
        t("prefixes.deletedSuccess") || "Prefix deleted successfully 🗑️",
      );
      queryClient.invalidateQueries({
        queryKey: ["recordTagPrefixes", unitId, recordTagId],
      });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  return {
    // queries
    prefixes: prefixesResponse?.items ?? [],
    total: prefixesResponse?.count ?? 0,
    isLoadingPrefixes,
    isErrorPrefixes,
    refetchPrefixes,

    // mutations
    createPrefix,
    isCreatingPrefix,
    deletePrefix,
    isDeletingPrefix,
  };
};
