import { Edcm } from "@komi-app/edcm-sdk";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { EdcmOptionalId } from "models/edcm/edcm";
import { getEdcm } from "services";
import { defaultEdcm } from "constants/dca/embed";
import notification from "utils/notification";
import { useTypedSelector } from "redux/rootReducer";
import { selectUserData } from "redux/User/selector";
import { useMemo } from "react";
import config from "config";

export function useEdcmResolve() {
  const {
    data: edcmId,
    isSuccess,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ["edcm-list"],
    queryFn: async () => {
      const items = await getEdcm().getSettingsForTalent();
      return items ?? [];
    },
    select: (res) => (res.length > 0 ? res[0].id : undefined),
  });

  return { edcmId, isSuccess, isLoading, isError };
}

export function useEcdmConfig(edcmId: string | undefined, enabled = true) {
  const queryClient = useQueryClient();
  const edcmConfig = useQuery({
    queryKey: ["edcm-config", edcmId],
    queryFn: () => {
      if (!edcmId) return Promise.resolve(defaultEdcm);
      return getEdcm().getSettings(edcmId);
    },
    enabled,
  });

  const saveEdcmConfig = useMutation({
    mutationKey: ["edcm-config", edcmId],
    mutationFn: (newConfig: EdcmOptionalId) => {
      if (hasId(newConfig)) {
        return getEdcm().updateSettings(newConfig);
      } else {
        return getEdcm().insertSettings(newConfig);
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["edcm-config", edcmId],
      });
      queryClient.invalidateQueries({
        queryKey: ["approved-domains", edcmId],
      });
      queryClient.invalidateQueries({
        queryKey: ["edcm-list"],
      });
      notification.success({ message: "Your website embed has been saved." });
    },
    onError: () => {
      notification.error({ message: "Something went wrong" });
    },
  });

  return {
    edcmConfig,
    saveEdcmConfig,
  };
}

export function useEdcmPrivacyPolicy() {
  const user = useTypedSelector(selectUserData);

  const privacyPolicy = useMemo(() => {
    const defaultPrivacyPolicy =
      new URL(config.client.url) + `talent-privacy-policy`;

    if (user?.talentProfile) {
      return {
        name:
          user.talentProfile.privacyPolicyName ||
          [user.talentProfile.firstName, user.talentProfile.lastName].join(" "),
        url: user.talentProfile.privacyPolicy || defaultPrivacyPolicy,
      };
    }

    return {
      name: "Talent",
      url: defaultPrivacyPolicy,
    };
  }, [user]);

  return privacyPolicy;
}

export function useEdcmApprovedDomains(edcmId: string | null | undefined) {
  const queryClient = useQueryClient();
  const { data: approvedDomains } = useQuery({
    queryKey: ["approved-domains", edcmId],
    queryFn() {
      if (!edcmId) return Promise.resolve([]);
      return getEdcm().getWhitelist(edcmId);
    },
  });

  const updateApprovedDomains = useMutation({
    mutationKey: ["approved-domains", edcmId],
    mutationFn: (approvedDomains: string[]) => {
      if (!edcmId) return Promise.resolve();
      return getEdcm().updateWhitelist(edcmId, approvedDomains);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["approved-domains", edcmId],
      });
    },
  });

  return {
    approvedDomains,
    updateApprovedDomains,
  };
}

function hasId(data: EdcmOptionalId): data is Edcm {
  return typeof data.id === "string";
}
