"use client";

import { useEffect, useState } from "react";
import Script from "next/script";
import { useTranslations } from "next-intl";

import { Button, Typography } from "@/components/ui";
import { ROUTES } from "@/shared/constants/client-routes";

import styles from "./Metrics.module.scss";

interface MetricsProps {
  fbPixels: string[];
  productPrice: string;
  currency: string;
}

export default function Metrics({
  fbPixels,
  productPrice,
  currency,
}: MetricsProps) {
  const t = useTranslations("Payment.Success");

  const [isButtonVisible, setIsButtonVisible] = useState(false);

  const handleNext = () => {
    window.location.href = ROUTES.additionalPurchases();
  };

  // Yandex Metrica
  useEffect(() => {
    const timeout = setTimeout(() => {
      if (
        typeof window.ym === "function" &&
        typeof window.klaviyo === "object" &&
        typeof window.gtag === "function"
      ) {
        try {
          window.gtag("event", "PaymentSuccess");
          window.klaviyo.push(["track", "PaymentSuccess"]);

          window.ym(95799066, "init", {
            clickmap: true,
            trackLinks: true,
            accurateTrackBounce: true,
            webvisor: true,
          });

          window.ym(95799066, "reachGoal", "PaymentSuccess", {}, () => {
            // deleteYm()
          });
        } catch (e) {
          // eslint-disable-next-line no-console
          console.error("YM error:", e);
        } finally {
          clearTimeout(timeout);
          setIsButtonVisible(true);
        }
      }
    }, 200);

    return () => clearTimeout(timeout);
  }, []);

  return (
    <>
      {/* Klaviyo */}
      {/* <Script src="https://static.klaviyo.com/onsite/js/klaviyo.js?company_id=RM7w5r" /> */}
      <Script id="klaviyo-script">
        {`const script = document.createElement("script");
    script.src = "https://static.klaviyo.com/onsite/js/klaviyo.js?company_id=RM7w5r";
    script.type = "text/javascript";
    script.async = "";
    document.head.appendChild(script);`}
      </Script>
      <Script id="klaviyo-script-proxy">
        {`
            !(function () {
      if (!window.klaviyo) {
                window._klOnsite = window._klOnsite || [];
            try {
                window.klaviyo = new Proxy(
                    {},
                    {
                        get: function (n, i) {
                            return "push" === i
                                ? function () {
                                    var n;
                                    (n = window._klOnsite).push.apply(n, arguments);
                                }
                                : function () {
                                    for (
                                        var n = arguments.length, o = new Array(n), w = 0;
                                        w < n;
                                        w++
                                    )
                                        o[w] = arguments[w];
                                    var t =
                                        "function" == typeof o[o.length - 1]
                                            ? o.pop()
                                            : void 0,
                                        e = new Promise(function (n) {
                                            window._klOnsite.push(
                                                [i].concat(o, [
                                                    function (i) {
                                                        t && t(i), n(i);
                                                    },
                                                ])
                                            );
                                        });
                                    return e;
                                };
                        },
                    }
                );
        } catch (n) {
                (window.klaviyo = window.klaviyo || []),
                (window.klaviyo.push = function () {
                    var n;
                    (n = window._klOnsite).push.apply(n, arguments);
                });
        }
      }
    })();
    `}
      </Script>

      {/* Yandex Metrica */}
      <Script id="yandex-metrica-script">
        {`(function (m, e, t, r, i, k, a) {
    m[i] =
        m[i] ||
        function () {
            (m[i].a = m[i].a || []).push(arguments);
        };
    m[i].l = 1 * new Date();
    for (var j = 0; j < document.scripts.length; j++) {
        if (document.scripts[j].src === r) {
            return;
        }
    }
    (k = e.createElement(t)),
        (a = e.getElementsByTagName(t)[0]),
        (k.async = 1),
        (k.src = r),
        a.parentNode.insertBefore(k, a);
})(
    window,
    document,
    "script",
    "https://cdn.jsdelivr.net/npm/yandex-metrica-watch/tag.js",
    "ym"
);`}
      </Script>

      {/* Google Analytics */}
      <Script
        id="google-analytics-script"
        async
        src="https://www.googletagmanager.com/gtag/js?id=G-4N17LL3BB5"
      />
      <Script id="google-analytics-script-config">
        {`window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config','G-4N17LL3BB5');`}
      </Script>

      {/* Facebook Pixel */}
      {fbPixels.map(pixel => (
        <Script id={`facebook-pixel-${pixel}`} key={pixel}>
          {`!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '${pixel}');
fbq('track', 'PageView');
fbq('track', 'Purchase', { value: ${productPrice}, currency: "${currency}" });`}
        </Script>
      ))}

      {isButtonVisible && (
        <Button onClick={handleNext} className={styles.button}>
          <Typography color="white">{t("button")}</Typography>
        </Button>
      )}
    </>
  );
}
