"use client";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel";
import { close, loading } from "@/config/swal";
import { Link, usePathname } from "@/i18n/routing";
import { listData } from "@/service/landing/landing";
import { formatDateToIndonesian, getOnlyMonthAndYear } from "@/utils/globals";
import { Icon } from "@iconify/react/dist/iconify.js";
import { pages } from "next/dist/build/templates/app-page";
import { useParams, useSearchParams } from "next/navigation";
import React, { useEffect } from "react";
import { useState } from "react";

export default function SearchImageComponent(props: {
  categoryFilter?: any;
  sortByOpt?: string;
  startDateString?: string;
  endDateString?: string;
  monthYearFilter?: any;
}) {
  const {
    categoryFilter,
    sortByOpt,
    startDateString,
    endDateString,
    monthYearFilter,
  } = props;
  const [newContent, setNewContent] = useState<any>();
  const asPath = usePathname();
  const params = useParams();
  const searchParams = useSearchParams();
  const [totalData, setTotalData] = useState<number>(1);
  const [totalPage, setTotalPage] = useState<number>(1);
  const sortBy = searchParams?.get("sortBy");
  const title = searchParams?.get("title");
  const categorie = searchParams?.get("category");
  const group = searchParams?.get("group");
  const [totalContent, setTotalContent] = useState();

  useEffect(() => {
    getDataAll();
  }, [
    title,
    categoryFilter,
    categorie,
    group,
    startDateString,
    endDateString,
    monthYearFilter,
    sortByOpt,
  ]);

  async function getDataAll() {
    if (asPath?.includes("/polda/") == true) {
      if (asPath?.split("/")[2] !== "[polda_name]") {
        const filter =
          categoryFilter?.length > 0
            ? categoryFilter?.sort().join(",")
            : categorie || "";

        const name = title == undefined ? "" : title;
        const filterGroup = group == undefined ? asPath.split("/")[2] : group;
        loading();
        const response = await listData(
          "1",
          name,
          filter,
          12,
          0,
          sortByOpt,
          "",
          "",
          filterGroup,
          startDateString,
          endDateString,
          monthYearFilter
            ? getOnlyMonthAndYear(monthYearFilter)
                ?.split("/")[0]
                ?.replace("", "")
            : "",
          monthYearFilter
            ? getOnlyMonthAndYear(monthYearFilter)?.split("/")[1]
            : ""
        );
        close();
        const data = response?.data?.data;
        const contentData = data?.content;
        setNewContent(contentData);
        setTotalData(data?.totalElements);
        setTotalPage(data?.totalPages);
        setTotalContent(response?.data?.data?.totalElements);
      }
    } else {
      const filter =
        categoryFilter?.length > 0
          ? categoryFilter?.sort().join(",")
          : categorie || "";

      const name = title == undefined ? "" : title;
      loading();
      const response = await listData(
        "1",
        name,
        filter,
        12,
        0,
        sortByOpt,
        "",
        "",
        "",
        startDateString,
        endDateString,
        monthYearFilter
          ? getOnlyMonthAndYear(monthYearFilter)?.split("/")[0]?.replace("", "")
          : "",
        monthYearFilter
          ? getOnlyMonthAndYear(monthYearFilter)?.split("/")[1]
          : ""
      );
      close();

      const data = response?.data?.data;
      const contentData = data?.content;

      setNewContent(contentData);
      setTotalData(data?.totalElements);
      setTotalPage(data?.totalPages);
      setTotalContent(response?.data?.data?.totalElements);
    }
  }

  return newContent?.length > 0 ? (
    <div className="flex flex-col gap-3 w-full">
      <p className="py-2">{`Foto(${totalContent})`}</p>
      <Carousel className="w-full max-w-7xl mx-auto">
        <CarouselContent>
          {newContent?.map((image: any) => (
            <CarouselItem key={image?.id} className="md:basis-1/2 lg:basis-1/2">
              <Link
                href={`/image/detail/${image?.slug}`}
                className="relative group rounded-md overflow-hidden shadow-md hover:shadow-lg"
              >
                <img
                  src={image?.thumbnailLink}
                  className="w-full h-40 lg:h-60 object-cover rounded-lg group-hover:scale-100 transition-transform duration-300"
                />
                <div className="absolute bottom-0 rounded-lg left-0 right-0 border-l-4 border-[#bb3523] bg-gray-600 text-white p-2">
                  <h1 className="text-sm font-semibold h-5 hover:h-auto truncate hover:whitespace-normal hover:overflow-visible">
                    {image?.title}
                  </h1>
                  <p className="flex flex-row items-center text-sm gap-2">
                    {formatDateToIndonesian(new Date(image?.createdAt))}{" "}
                    {image?.timezone ? image?.timezone : "WIB"}|{" "}
                    <Icon icon="formkit:eye" width="15" height="15" />{" "}
                    {image?.clickCount}{" "}
                  </p>
                </div>
              </Link>
            </CarouselItem>
          ))}
        </CarouselContent>
        <CarouselPrevious />
        <CarouselNext />
      </Carousel>
    </div>
  ) : (
    ""
  );
}
