import { getCategoryData, getPublicCategoryData } from "@/service/landing/landing";
import Link from "next/link";
import React, { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { usePathname } from "next/navigation";
import { useParams } from "next/navigation";
import Image from "next/image";
import { Reveal } from "../Reveal";
import { Button } from "@/components/ui/button";

const ContentCategory = (props: { group?: string }) => {
  const [categories, setCategories] = useState<any>();
  const t = useTranslations("LandingPage");
  const params = useParams();
  const locale = params?.locale;
  const poldaName = params?.polda_name;
  const satkerName = params?.satker_name;
  const [searchTerm, setSearchTerm] = useState("");
  const [seeAllValue, setSeeAllValue] = useState(false);
  const pathname = usePathname();

  useEffect(() => {
    initFetch();
  }, []);
  const initFetch = async () => {
    const response = await getPublicCategoryData(
      props.group == "mabes" ? "" : props.group == "polda" && poldaName && String(poldaName)?.length > 1 ? poldaName : props.group == "satker" && satkerName && String(satkerName)?.length > 1 ? "satker-" + satkerName : "",
      "",
      locale == "en" ? true : false
    );
    console.log("category", response);
    setCategories(response?.data?.data?.content);
  };

  const shimmer = (w: number, h: number) => `
  <svg width="${w}" height="${h}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
      <linearGradient id="g">
        <stop stop-color="#bcbcbd" offset="20%" />
        <stop stop-color="#f9fafb" offset="50%" />
        <stop stop-color="#bcbcbd" offset="70%" />
      </linearGradient>
    </defs>
    <rect width="${w}" height="${h}" fill="#bcbcbd" />
    <rect id="r" width="${w}" height="${h}" fill="url(#g)" />
    <animate xlink:href="#r" attributeName="x" from="-${w}" to="${w}" dur="1s" repeatCount="indefinite"  />
  </svg>`;

  const toBase64 = (str: string) => (typeof window === "undefined" ? Buffer.from(str).toString("base64") : window.btoa(str));

  return (
    <div className="mx-auto px-4 lg:px-24 py-10 max-w-screen-2xl ">
      <Reveal>
        <h2 className="text-center text-xl lg:text-2xl font-bold text-[#bb3523] mb-4">
          {pathname?.split("/")[1] == "in" ? (
            <>
              <span className="text-black dark:text-white">{t("category")}&nbsp;</span>
              {t("content")}
            </>
          ) : (
            <>
              <span className="text-black dark:text-white">{t("content")}&nbsp;</span>
              {t("category")}
            </>
          )}
        </h2>
        <div className="h-1 w-48 bg-[#bb3523] mx-auto mb-6 rounded"></div>

        <div className="grid my-3 grid-cols-2 lg:grid-cols-4 gap-4">
          {categories?.map((category: any, index: number) =>
            !seeAllValue ? (
              index < 4 ? (
                <Link key={category?.id} href={`all/filter?category=${category?.id}`} className="relative group rounded-md overflow-hidden shadow-md hover:shadow-lg">
                  <Image
                    placeholder={`data:image/svg+xml;base64,${toBase64(shimmer(700, 475))}`}
                    alt="category"
                    width={2560}
                    height={1440}
                    src={category?.thumbnailLink}
                    className="w-full h-48 sm:h-40 object-cover group-hover:scale-110 transition-transform duration-300"
                  />
                  <div className="absolute  bottom-0 rounded-lg left-0 right-0 bg-gray-400 border-l-4 mb-4 border-[#bb3523] text-white p-2">
                    <h3 className="text-sm font-semibold truncate">{category?.name}</h3>
                  </div>
                </Link>
              ) : (
                ""
              )
            ) : (
              <Link key={category?.id} href={`all/filter?category=${category?.id}`} className="relative group rounded-md overflow-hidden shadow-md hover:shadow-lg">
                <Image
                  placeholder={`data:image/svg+xml;base64,${toBase64(shimmer(700, 475))}`}
                  alt="category"
                  width={2560}
                  height={1440}
                  src={category?.thumbnailLink}
                  className="w-full h-48 sm:h-40 object-cover group-hover:scale-110 transition-transform duration-300"
                />
                <div className="absolute bottom-0 left-0 right-0 bg-gray-400 border-l-4 mb-4 border-[#bb3523] rounded-lg text-white p-2">
                  <h3 className="text-sm font-semibold truncate">{category?.name}</h3>
                </div>
              </Link>
            )
          )}
        </div>
        <div className="flex items-center flex-row justify-center">
          <Button onClick={() => setSeeAllValue(!seeAllValue)} className="bg-white hover:bg-[#bb3523] text-[#bb3523] hover:text-white border-2 border-[#bb3523]">
            {seeAllValue ? t("seeLess") : t("seeMore")}
          </Button>
        </div>
      </Reveal>
    </div>
  );
};

export default ContentCategory;
