import { useQuery, useQueryClient } from "@tanstack/react-query";
import { getShortVideoService } from "services";
import { useFeatureIsOn, FLAGS } from "@komi-app/flags-sdk";
import { IntegrationAccount } from "types/integration";

export const useTikTokAccounts = (
  onDisconnect?: (accountId: string) => void
) => {
  const isTikTokIntegrationOn = useFeatureIsOn(FLAGS.SHORT_VIDEO_AUTOMATION);

  const queryClient = useQueryClient();

  const query = useQuery({
    enabled: isTikTokIntegrationOn,
    queryKey: ["tiktok-accounts"],
    refetchOnWindowFocus: false,
    queryFn: async (): Promise<IntegrationAccount[]> => {
      const accounts = await getShortVideoService().getTikTokAccounts();

      if (accounts && "ok" in accounts) {
        return accounts?.response.map((account) => ({
          id: account.id,
          name: account.displayName,
          avatar: account.avatarUrl,
          platformId: account.tiktokOpenId || account.id,
          onDisconnect: () => {
            // If we've been provided a custom onDisconnect function, use it
            if (onDisconnect) {
              onDisconnect(account.id);
            } else {
              // Otherwise, use the default disconnect function
              disconnectAccount(account.id);
            }
          },
        }));
      }

      return [];
    },
  });

  const disconnectAccount = async (accountId: string) => {
    // Optimistically update the cache
    queryClient.setQueryData(["tiktok-accounts"], (oldData: any) => {
      if (!oldData) return [];
      return oldData.filter((account: any) => account.id !== accountId);
    });

    try {
      await getShortVideoService().disconnectTikTokAccount(accountId);
    } catch (error) {
      console.error(error);
    }

    await queryClient.invalidateQueries(["tiktok-accounts"]);
  };

  return { ...query, disconnectAccount };
};
