"use client";
import Cookies from "js-cookie";
import { useEffect, useState } from "react";
import { getCookiesDecrypt } from "@/lib/utils";
import { useTranslations } from "next-intl";
import { generateTicket } from "@/service/service/tableau/tableau-service";

export default function PerformancePolresViz() {
  const [hasMounted, setHasMounted] = useState(false);
  const t = useTranslations("AnalyticsDashboard");
  const levelName = getCookiesDecrypt("ulnae");
  const poldaState = Cookies.get("state");
  const provState = Cookies.get("state-prov");

  const [ticket1, setTicket1] = useState("");
  const [ticket2, setTicket2] = useState("");
  const [ticket3, setTicket3] = useState("");
  const [ticket4, setTicket4] = useState("");
  const [isInternational, setIsInternational] = useState([false, false, false]);

  const baseUrl = "https://analytic.sitani.info/";
  const url = "https://analytic.sitani.info/trusted/";

  const view1 =
    levelName == "MABES POLRI"
      ? isInternational[0]
        ? "views/2023_04_MediaHUB-Viz_INTL_Rev202/db-konten-top10?"
        : "views/2023_09_db-ranking-polda_rev100/db-ranking-13-polda?"
      : `/views/2023_09_db-ranking-polres-by-polda_rev100/db-ranking-by-polda?polda-selected=${poldaState}&`;

  const param = ":embed=yes&:toolbar=no&:iframeSizedToWindow=true";

  useEffect(() => {
    async function initState() {
      const response1 = await generateTicket();
      setTicket1(response1?.data?.data);
    }

    initState();
  }, [isInternational]);

  // Hooks
  useEffect(() => {
    setHasMounted(true);
  }, []);

  // Render
  if (!hasMounted) return null;

  const handleInternational = (index: number, val: boolean) => {
    const updatedIsInternational = [...isInternational];

    updatedIsInternational[index] = val;
    setIsInternational(updatedIsInternational);
  };

  return (
    <div className="flex flex-col gap-2 bg-white rounded-lg p-3">
      <p className="text-lg">
        <b>
          {isInternational[0] ? "POLRES PERFORMANCE" : "POLFORMANCE POLRES"}
        </b>
      </p>
      <div className="my-5">
        {ticket1 == "" ? (
          <iframe
            src={`${baseUrl + view1 + param}`}
            width="100%"
            height="750"
            frameBorder="0"
          />
        ) : (
          <iframe
            src={`${`${url + ticket1}/${view1}${param}`}`}
            width="100%"
            height="750"
            frameBorder="0"
          />
        )}
      </div>
    </div>
  );
}
