import { useQuery } from "@tanstack/react-query";
import {
  ChipFilterProps,
  EmailTemplateItem,
  useToast,
} from "@komi-app/creator-ui";
import {
  GetSystemTemplateCategoriesResponse,
  GetSystemTemplatesQuery,
  GetSystemTemplatesResponse,
  SystemTemplate,
  SystemTemplateCategory,
} from "@komi-app/messaging-sdk";
import { getSystemTemplatesSDK } from "services";
import {
  allCategoriesOption,
  blankSystemTemplate,
  getCategoryIcon,
} from "./config";
import { useEffect } from "react";

interface UseSystemCategoriesResult {
  systemCategories: ChipFilterProps[];
  hasFetchedCategories: boolean;
}

interface ErrorNotification {
  isError: boolean;
  text: string;
  dismissible?: boolean;
}

/**
 * Hook to fetch and transform system templates based on filters
 * @param filters Query parameters for filtering templates
 */
export const useSystemTemplates = (
  filters: GetSystemTemplatesQuery,
): EmailTemplateItem[] => {
  const { data, isError } = useQuery({
    queryKey: ["systemTemplates", filters],
    queryFn: () => getSystemTemplatesSDK().getSystemTemplates(filters),
    refetchOnWindowFocus: false,
  });
  //Show toast if there was an error
  useErrorNotification({
    isError,
    text: "We couldn’t load the templates. Try again.",
  });

  return mapSystemTemplates(data);
};

/**
 * Hook to fetch and transform system template categories
 */
export const useSystemCategories = (): UseSystemCategoriesResult => {
  const { data, isFetched, isError } = useQuery({
    queryKey: ["systemTemplateCategories"],
    queryFn: () => getSystemTemplatesSDK().getSystemTemplateCategories(),
    refetchOnWindowFocus: false,
  });

  //Show toast if there was an error
  useErrorNotification({
    isError,
    text: "We couldn’t load goals. Try again.",
  });

  return {
    systemCategories: mapSystemTemplateCategories(data),
    hasFetchedCategories: isFetched,
  };
};

export function useErrorNotification({
  isError,
  text,
  dismissible = true,
}: ErrorNotification) {
  const { createToast } = useToast();

  useEffect(() => {
    if (isError) {
      createToast({
        semantic: "error",
        text,
        dismissible,
      });
    }
  }, [isError]);
}

/**
 * Maps API template data to frontend template format.
 * First template options is always "Blank template"
 * @param data Response from the templates API
 */
const mapSystemTemplates = (
  data: GetSystemTemplatesResponse | undefined,
): EmailTemplateItem[] => {
  if (!data?.templates) return [blankSystemTemplate];
  return [
    blankSystemTemplate,

    ...data.templates.map((template: SystemTemplate) => ({
      id: template.id,
      title: template.name,
      imageURL: template.thumbnailUrl,
    })),
  ];
};

/**
 * Maps API category data to frontend chip filter format.
 * First category is always "All categories"
 * @param data Response from the categories API
 */
const mapSystemTemplateCategories = (
  data: GetSystemTemplateCategoriesResponse | undefined,
): ChipFilterProps[] => {
  if (!data?.categories.length) return [allCategoriesOption];

  return [
    allCategoriesOption,
    ...data.categories.map((category: SystemTemplateCategory) => {
      return {
        id: category.key,
        label: category.name,
        prefixIcon: getCategoryIcon(category.name),
        selected: false,
      };
    }),
  ];
};
