"use client";

import React, { useEffect, useState } from "react";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Carousel,
  CarouselApi,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel";
import { useParams, usePathname } from "next/navigation";
import { Icon } from "@iconify/react/dist/iconify.js";
import { formatDateToIndonesian, secondToTimes } from "@/utils/globals";
import { getListContent } from "@/service/landing/landing";
import { Link, useRouter } from "@/i18n/routing";
import { Reveal } from "./Reveal";
import { useTranslations } from "next-intl";
import { Skeleton } from "../ui/skeleton";
import Image from "next/image";
import { motion } from "framer-motion";

const NewContent = (props: { group: string; type: string }) => {
  const [newContent, setNewContent] = useState<any>();
  const [selectedTab, setSelectedTab] = useState("image");
  const [isLoading, setIsLoading] = useState<any>(true);
  const router = useRouter();
  const pathname = usePathname();
  const params = useParams();
  const locale = params?.locale;
  const poldaName = params?.polda_name;
  const satkerName = params?.satker_name;
  const t = useTranslations("LandingPage");
  const [api, setApi] = React.useState<CarouselApi | null>(null);
  const [current, setCurrent] = React.useState(0);
  const [count, setCount] = React.useState(0);

  React.useEffect(() => {
    if (!api) return;

    setCount(api.scrollSnapList().length);
    setCurrent(api.selectedScrollSnap());

    const onSelect = () => {
      setCurrent(api.selectedScrollSnap());
    };

    api.on("select", onSelect);

    return () => {
      api.off("select", onSelect);
    };
  }, [api]);

  let prefixPath = poldaName
    ? `/polda/${poldaName}`
    : satkerName
    ? `/satker/${satkerName}`
    : "/";

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 3000);

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

  useEffect(() => {
    initFetch();
  }, [selectedTab]);
  const initFetch = async () => {
    console.log("Satker Name : ", satkerName);
    const request = {
      title: "",
      page: 0,
      size: 5,
      sortBy: props.type == "popular" ? "clickCount" : "createdAt",
      contentTypeId:
        selectedTab == "image"
          ? "1"
          : selectedTab == "video"
          ? "2"
          : selectedTab == "text"
          ? "3"
          : selectedTab == "audio"
          ? "4"
          : "",
      group:
        props.group == "mabes"
          ? ""
          : props.group == "polda" && poldaName && String(poldaName)?.length > 1
          ? poldaName
          : props.group == "satker" &&
            satkerName &&
            String(satkerName)?.length > 1
          ? "satker-" + satkerName
          : "",
      isInt: locale == "en" ? true : false,
    };
    const response = await getListContent(request);
    console.log("category", response);
    setNewContent(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="px-4 lg:px-0 py-4">
      <Reveal>
        <div className="flex flex-col">
          <h2 className="flex items-center text-lg md:text-xl font-bold text-[#bb3523] border-b-2 border-[#bb3523]  uppercase">
            {pathname?.split("/")[1] == "in" ? (
              <>
                <span className="text-[#bb3523] ">{t("content")}</span>&nbsp;
                {props.type == "popular"
                  ? "Terpopuler"
                  : props.type == "latest"
                  ? t("new")
                  : "Serupa"}
              </>
            ) : (
              <>
                <span className="text-[#bb3523] ">
                  {props.type == "popular"
                    ? "Popular"
                    : props.type == "latest"
                    ? t("new")
                    : "Serupa"}
                </span>
                &nbsp;
                {t("content")}
              </>
            )}
          </h2>
          <div className="mx-auto w-full justify-start flex flex-col lg:flex-row gap-5 my-8">
            <Tabs value={selectedTab} onValueChange={setSelectedTab}>
              <TabsList className="flex gap-2 bg-transparent p-0">
                {[
                  { label: t("image"), value: "image" },
                  { label: t("video"), value: "video" },
                  { label: t("text"), value: "text" },
                  { label: t("audio"), value: "audio" },
                ].map((tab) => (
                  <TabsTrigger
                    key={tab.value}
                    value={tab.value}
                    className={`
          rounded-md px-6 py-2 text-sm transition-all
          bg-[#f5f5f5] text-[#666] hover:bg-[#e0e0e0]
          data-[state=active]:bg-[#bb0000]
          data-[state=active]:text-white
          data-[state=active]:font-bold
        `}
                  >
                    {tab.label}
                  </TabsTrigger>
                ))}
              </TabsList>
            </Tabs>
          </div>

          {isLoading ? (
            <div className="flex flex-row space-y-3 w-full justify-center items-center gap-10">
              <Skeleton className="h-[200px] w-[400px] rounded-xl" />
              <Skeleton className="h-[200px] w-[400px] rounded-xl hidden md:block" />
              <Skeleton className="h-[200px] w-[400px] rounded-xl hidden md:block" />
            </div>
          ) : (
            <div className="">
              {selectedTab == "image" ? (
                newContent?.length > 0 ? (
                  <Carousel setApi={setApi} className="w-full mx-auto">
                    <CarouselContent>
                      {newContent?.map((image: any) => (
                        <CarouselItem
                          key={image?.id}
                          className="md:basis-1/2 lg:basis-1/3"
                        >
                          <div
                            onClick={() =>
                              router.push(
                                prefixPath + `/image/detail/${image?.slug}`
                              )
                            }
                            className="cursor-pointer relative group overflow-hidden bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow duration-300"
                          >
                            {/* Image with motion effect */}
                            <motion.div
                              className="w-full h-48 lg:h-60"
                              whileHover={{ scale: 0.95 }}
                              transition={{ duration: 0.3 }}
                            >
                              <Image
                                placeholder={`data:image/svg+xml;base64,${toBase64(
                                  shimmer(700, 475)
                                )}`}
                                width={2560}
                                height={1440}
                                alt="image"
                                src={image?.smallThumbnailLink}
                                className="w-full h-full object-cover"
                              />
                            </motion.div>

                            {/* Badge category */}
                            {/* <div className="absolute top-2 left-2 bg-white px-2 py-1 rounded-sm text-[10px] font-bold text-[#bb3523]">{image?.category?.toUpperCase() ?? "GIAT PIMPINAN"}</div> */}

                            {/* Red icon overlay */}
                            <div className="absolute top-2 right-2 bg-[#bb3523] rounded-full p-1">
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="24"
                                height="24"
                                viewBox="0 0 24 24"
                              >
                                <g fill="none">
                                  <path d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z" />
                                  <path
                                    fill="white"
                                    d="M20 6a2 2 0 0 1 2 2v11.333a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2zm-8.268 7.944L7.136 18.54l-.066.06l-.07.054v.68h13v-.68l-.07-.053l-.066-.06l-2.24-2.24l-.353.354l.055.055a1 1 0 0 1-1.32 1.497l-.094-.083zM17 3a2 2 0 0 1 1.995 1.85L19 5H5a1 1 0 0 0-.993.883L4 6v12a2 2 0 0 1-1.995-1.85L2 16V6a3 3 0 0 1 2.824-2.995L5 3zm3 5H7v7.848L10.848 12a1.25 1.25 0 0 1 1.768 0l3.241 3.24l.884-.883a1.25 1.25 0 0 1 1.768 0L20 15.848zm-3.5 1.5a1.5 1.5 0 1 1 0 3a1.5 1.5 0 0 1 0-3"
                                  />
                                </g>
                              </svg>{" "}
                            </div>

                            {/* Caption section */}
                            <div className="p-4 h-full flex flex-col justify-between">
                              <div className="flex flex-col gap-1 flex-grow">
                                <p className="text-[10px] font-bold text-[#bb3523] uppercase">
                                  {image?.categoryName?.toUpperCase() ??
                                    "Giat Pimpinan"}
                                </p>
                                <p
                                  className="
        text-sm lg:text-base font-semibold text-black
        line-clamp-4         /* LIMIT to 2 lines if plugin available */
        /* or use min-h-[3rem] as fallback */
      "
                                >
                                  {image?.title}
                                </p>
                              </div>
                              {/* Optional metadata area (uncomment if needed) */}
                              {/* 
  <p className="flex flex-row items-center text-[10px] gap-1 mt-2 text-gray-600">
    {formatDateToIndonesian(new Date(image?.createdAt))} {image?.timezone ?? "WIB"} |
    <Icon icon="formkit:eye" width="15" height="15" /> {image.clickCount}
  </p>
  */}
                            </div>
                          </div>
                        </CarouselItem>
                      ))}
                    </CarouselContent>

                    <div className="flex justify-center mt-4">
                      {Array.from({ length: count }).map((_, index) => (
                        <button
                          key={index}
                          className={`w-3 h-3 mx-1 rounded-full ${
                            index === current ? "bg-gray-800" : "bg-gray-300"
                          }`}
                          onClick={() => api?.scrollTo(index)}
                          aria-label={`Slide ${index + 1}`}
                        />
                      ))}
                    </div>

                    <CarouselPrevious className="hover:bg-black ml-2" />
                    <CarouselNext className="hover:bg-black mr-2" />
                  </Carousel>
                ) : (
                  <p className="flex items-center justify-center">
                    <Image
                      width={1920}
                      height={1080}
                      src="/assets/empty-data.png"
                      alt="empty"
                      className="h-52 w-52 my-4"
                    />
                  </p>
                )
              ) : selectedTab == "audio" ? (
                newContent?.length > 0 ? (
                  <Carousel setApi={setApi} className="w-full mx-auto">
                    <CarouselContent>
                      {newContent?.map((audio: any) => (
                        <CarouselItem
                          key={audio?.id}
                          className="md:basis-1/2 lg:basis-1/3"
                        >
                          <div
                            onClick={() =>
                              router.push(
                                prefixPath + `/audio/detail/${audio?.slug}`
                              )
                            }
                            className="cursor-pointer bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow duration-300 overflow-hidden"
                          >
                            {/* Icon Background */}
                            <div className="flex items-center justify-center bg-[#bb3523] w-full h-[170px] text-white">
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="150"
                                height="150"
                                viewBox="0 0 20 20"
                              >
                                <path
                                  fill="currentColor"
                                  d="M14.702 2.226A1 1 0 0 1 16 3.18v6.027a5.5 5.5 0 0 0-1-.184V6.18L8 8.368V15.5a2.5 2.5 0 1 1-1-2V5.368a1 1 0 0 1 .702-.955zM8 7.32l7-2.187V3.18L8 5.368zM5.5 14a1.5 1.5 0 1 0 0 3a1.5 1.5 0 0 0 0-3m13.5.5a4.5 4.5 0 1 1-9 0a4.5 4.5 0 0 1 9 0m-2.265-.436l-2.994-1.65a.5.5 0 0 0-.741.438v3.3a.5.5 0 0 0 .741.438l2.994-1.65a.5.5 0 0 0 0-.876"
                                />
                              </svg>{" "}
                            </div>

                            {/* Caption */}
                            <div className="p-4">
                              <p className="text-[12px] font-bold text-[#bb3523] uppercase mb-1">
                                {audio?.categoryName?.toUpperCase() ??
                                  "GIAT PIMPINAN"}
                              </p>

                              <p className="text-xl font-semibold text-black line-clamp-4">
                                {audio?.title}
                              </p>

                              {/* <p className="text-[10px] text-gray-600 mt-2 flex items-center gap-1">
                                {formatDateToIndonesian(new Date(audio?.createdAt))} {audio?.timezone ?? "WIB"} |
                                <Icon icon="formkit:eye" width="15" height="15" /> {audio?.clickCount}
                              </p> */}
                            </div>
                          </div>
                        </CarouselItem>
                      ))}
                    </CarouselContent>

                    <div className="flex justify-center mt-4">
                      {Array.from({ length: count }).map((_, index) => (
                        <button
                          key={index}
                          className={`w-3 h-3 mx-1 rounded-full ${
                            index === current ? "bg-gray-800" : "bg-gray-300"
                          }`}
                          onClick={() => api?.scrollTo(index)}
                          aria-label={`Slide ${index + 1}`}
                        />
                      ))}
                    </div>

                    <CarouselPrevious className="hover:bg-black ml-2" />
                    <CarouselNext className="hover:bg-black mr-2" />
                  </Carousel>
                ) : (
                  <p className="flex items-center justify-center">
                    <Image
                      width={1920}
                      height={1080}
                      src="/assets/empty-data.png"
                      alt="empty"
                      className="h-52 w-52 my-4"
                    />
                  </p>
                )
              ) : selectedTab == "video" ? (
                newContent?.length > 0 ? (
                  <Carousel setApi={setApi} className="w-full mx-auto">
                    <CarouselContent>
                      {newContent?.map((video: any) => (
                        <CarouselItem
                          key={video?.id}
                          className="md:basis-1/2 lg:basis-1/3"
                        >
                          <div
                            onClick={() =>
                              router.push(
                                prefixPath + `/video/detail/${video?.slug}`
                              )
                            }
                            className="cursor-pointer relative group overflow-hidden bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow duration-300"
                          >
                            {/* Image with motion effect */}
                            <motion.div
                              className="w-full h-48 lg:h-60"
                              whileHover={{ scale: 0.95 }}
                              transition={{ duration: 0.3 }}
                            >
                              <Image
                                placeholder={`data:image/svg+xml;base64,${toBase64(
                                  shimmer(700, 475)
                                )}`}
                                alt="video"
                                width={2560}
                                height={1440}
                                src={video?.smallThumbnailLink}
                                className="w-full h-full object-cover"
                              />
                            </motion.div>

                            {/* Badge category */}
                            {/* <div className="absolute top-2 left-2 bg-white px-2 py-1 rounded-sm text-[10px] font-bold text-[#bb3523]">{video?.category?.toUpperCase() ?? "VIDEO"}</div> */}

                            {/* Red icon overlay */}
                            <div className="absolute top-2 right-2 bg-[#bb3523] rounded-full p-1">
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="24"
                                height="24"
                                viewBox="0 0 24 24"
                              >
                                <g fill="none">
                                  <path d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z" />
                                  <path
                                    fill="white"
                                    d="M20 6a2 2 0 0 1 2 2v11.333a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2zm-8.268 7.944L7.136 18.54l-.066.06l-.07.054v.68h13v-.68l-.07-.053l-.066-.06l-2.24-2.24l-.353.354l.055.055a1 1 0 0 1-1.32 1.497l-.094-.083zM17 3a2 2 0 0 1 1.995 1.85L19 5H5a1 1 0 0 0-.993.883L4 6v12a2 2 0 0 1-1.995-1.85L2 16V6a3 3 0 0 1 2.824-2.995L5 3zm3 5H7v7.848L10.848 12a1.25 1.25 0 0 1 1.768 0l3.241 3.24l.884-.883a1.25 1.25 0 0 1 1.768 0L20 15.848zm-3.5 1.5a1.5 1.5 0 1 1 0 3a1.5 1.5 0 0 1 0-3"
                                  />
                                </g>
                              </svg>{" "}
                            </div>

                            {/* Caption section */}
                            <div className="p-4 h-full flex flex-col justify-between">
                              <div className="flex flex-col gap-1 flex-grow">
                                <p className="text-[10px] font-bold text-[#bb3523] uppercase">
                                  {video?.categoryName?.toUpperCase() ??
                                    "Giat Pimpinan"}
                                </p>
                                <p
                                  className="text-sm lg:text-base font-semibold text-black line-clamp-5">
                                  {video?.title}
                                </p>
                              </div>
                              {/* Optional metadata area (uncomment if needed) */}
                              {/* 
  <p className="flex flex-row items-center text-[10px] gap-1 mt-2 text-gray-600">
    {formatDateToIndonesian(new Date(image?.createdAt))} {image?.timezone ?? "WIB"} |
    <Icon icon="formkit:eye" width="15" height="15" /> {image.clickCount}
  </p>
  */}
                            </div>
                          </div>
                        </CarouselItem>
                      ))}
                    </CarouselContent>

                    {/* Pagination Dots */}
                    <div className="flex justify-center mt-4">
                      {Array.from({ length: count }).map((_, index) => (
                        <button
                          key={index}
                          className={`w-3 h-3 mx-1 rounded-full ${
                            index === current ? "bg-gray-800" : "bg-gray-300"
                          }`}
                          onClick={() => api?.scrollTo(index)}
                          aria-label={`Slide ${index + 1}`}
                        />
                      ))}
                    </div>

                    <CarouselPrevious className="hover:bg-black ml-2" />
                    <CarouselNext className="hover:bg-black mr-2" />
                  </Carousel>
                ) : (
                  <p className="flex items-center justify-center">
                    <Image
                      width={1920}
                      height={1080}
                      src="/assets/empty-data.png"
                      alt="empty"
                      className="h-52 w-52 my-4"
                    />
                  </p>
                )
              ) : newContent.length > 0 ? (
                <Carousel setApi={setApi} className="w-full mx-auto">
                  <CarouselContent>
                    {newContent?.map((text: any) => (
                      <CarouselItem
                        key={text?.id}
                        className="md:basis-1/2 lg:basis-1/3"
                      >
                        <div
                          onClick={() =>
                            router.push(
                              prefixPath + `/document/detail/${text?.slug}`
                            )
                          }
                          className="cursor-pointer rounded-lg shadow-md overflow-hidden bg-white"
                        >
                          {/* Ikon di tengah dengan latar kuning */}
                          <div className="bg-[#e0c350] flex items-center justify-center h-[170px] text-white">
                            <svg
                              xmlns="http://www.w3.org/2000/svg"
                              width="150"
                              height="150"
                              viewBox="0 0 16 16"
                            >
                              <path
                                fill="currentColor"
                                d="M5 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V5.414a1.5 1.5 0 0 0-.44-1.06L9.647 1.439A1.5 1.5 0 0 0 8.586 1zM4 3a1 1 0 0 1 1-1h3v2.5A1.5 1.5 0 0 0 9.5 6H12v7a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1zm7.793 2H9.5a.5.5 0 0 1-.5-.5V2.207zM7 7.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5M7.5 9a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1zM7 11.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5M5.5 8a.5.5 0 1 0 0-1a.5.5 0 0 0 0 1M6 9.5a.5.5 0 1 1-1 0a.5.5 0 0 1 1 0M5.5 12a.5.5 0 1 0 0-1a.5.5 0 0 0 0 1"
                              />
                            </svg>
                          </div>

                          {/* Konten bawah */}
                          <div className="p-4 flex flex-col gap-2">
                            {/* Kategori merah */}
                            <div className="text-[12px] font-bold text-red-600 uppercase">
                              {text?.categoryName?.toUpperCase() ?? "Text"}
                            </div>

                            {/* Judul */}
                            <div className="font-semibold text-gray-900 text-xl leading-snug line-clamp-4">
                              {text?.title}
                            </div>

                            {/* Meta info */}
                            {/* <div className="text-gray-500 flex items-center text-xs gap-2">
                              <span>
                                {formatDateToIndonesian(new Date(text?.createdAt))}
                                {text?.timezone ? text?.timezone : "WIB"}
                              </span>
                              <span className="flex items-center gap-1">
                                <Icon icon="formkit:eye" width={14} height={14} />
                                {text?.clickCount}
                              </span>
                            </div> */}

                            {/* Download */}
                            {/* <div className="flex items-center gap-2 text-sm text-red-500 mt-2">
                              <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 512 512">
                                <path fill="#f00" d="M224 30v256h-64l96 128l96-128h-64V30zM32 434v48h448v-48z" />
                              </svg>
                              Download {t("document")}
                            </div> */}
                          </div>
                        </div>
                      </CarouselItem>
                    ))}
                  </CarouselContent>

                  {/* Pagination Dots */}
                  <div className="flex justify-center mt-4">
                    {Array.from({ length: count }).map((_, index) => (
                      <button
                        key={index}
                        className={`w-3 h-3 mx-1 rounded-full ${
                          index === current ? "bg-gray-800" : "bg-gray-300"
                        }`}
                        onClick={() => api?.scrollTo(index)}
                        aria-label={`Slide ${index + 1}`}
                      />
                    ))}
                  </div>

                  <CarouselPrevious className="hover:bg-black ml-2" />
                  <CarouselNext className="hover:bg-black mr-2" />
                </Carousel>
              ) : (
                <p className="flex items-center justify-center">
                  <Image
                    width={1920}
                    height={1080}
                    src="/assets/empty-data.png"
                    alt="empty"
                    className="h-52 w-52 my-4"
                  />
                </p>
              )}
            </div>
          )}
        </div>
        {/* <div className="flex items-center flex-row justify-center">
          <div onClick={() => router.push(prefixPath + `/${selectedTab}/filter?sortBy=${props.type}`)} className="cursor-pointer border text-[#bb3523] rounded-lg text-sm lg:text-md px-4 py-1 border-[#bb3523]">
            {t("seeAll")}
          </div>
        </div> */}
      </Reveal>
    </div>
  );
};

export default NewContent;
