import {
  keepPreviousData,
  useMutation,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";

import {
  getTemplatesByUnitId,
  getTemplateById,
  createTemplate,
  updateTemplate,
  deleteTemplate,
  LetterTemplatePayload,
  LetterTemplate,
} from "@/user-management/services/api/letterTemplateService";

export interface UseLetterTemplatesOptions {
  skip?: number;
  take?: number;
  // BE expects "field:DIRECTION" form, e.g. "createdAt:DESC".
  orderBy?: string;
  order?: string;
  enabled?: boolean;
}

export const useLetterTemplates = (
  unitId: string,
  options: UseLetterTemplatesOptions = {},
) => {
  const queryClient = useQueryClient();

  const {
    skip = 0,
    take = 20,
    // Default to newest-first so freshly-created templates appear at the top.
    orderBy = "createdAt:DESC",
    order,
    enabled = true,
  } = options;

  const params = {
    skip,
    take,
    orderBy,
    ...(order ? { order } : {}),
  };

  // GET all templates by unitId
  const {
    data: letterTemplatesResponse,
    isLoading,
    isFetching,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["letter-templates", unitId, params],
    queryFn: async () => {
      const { data } = await getTemplatesByUnitId(unitId, params);
      return data;
    },
    enabled: !!unitId && enabled,
    staleTime: 5 * 60 * 1000,
    retry: false,
    placeholderData: keepPreviousData,
  });

  // GET single template
  const { mutate: getTemplateByDetails, isPending: isFetchingTemplate } =
    useMutation({
      mutationFn: async (id: string) => {
        const { data } = await getTemplateById(id);
        return data as LetterTemplate;
      },
    });

  // CREATE
  const { mutate: createLetterTemplate, isPending: isCreating } = useMutation({
    mutationFn: async (data: LetterTemplatePayload) => {
      const { data: created } = await createTemplate(data);
      return created;
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: ["letter-templates", variables.unitId],
      });
    },
  });

  // UPDATE
  const { mutate: updateLetterTemplate, isPending: isUpdating } = useMutation({
    mutationFn: async (payload: {
      id: string;
      data: LetterTemplatePayload;
    }) => {
      const { data: updated } = await updateTemplate(payload.id, payload.data);
      return updated;
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: ["letter-templates", variables.data.unitId],
      });
      queryClient.invalidateQueries({
        queryKey: ["letter-template", variables.id],
      });
    },
  });

  // DELETE
  const { mutate: deleteLetterTemplate, isPending: isDeleting } = useMutation({
    mutationFn: async ({ id }: { id: string }) => {
      await deleteTemplate(id);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["letter-templates", unitId],
      });
    },
  });

  return {
    letterTemplatesResponse,
    items: letterTemplatesResponse?.items ?? [],
    count: letterTemplatesResponse?.count ?? 0,
    isLoading,
    isFetching,
    isError,
    refetch,
    getTemplateByDetails,
    isFetchingTemplate,
    createLetterTemplate,
    isCreating,
    updateLetterTemplate,
    isUpdating,
    deleteLetterTemplate,
    isDeleting,
  };
};
