"use client";
import React, { useEffect, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Icon } from "@iconify/react/dist/iconify.js";
import { formatDateToIndonesian, getOnlyDate, getOnlyMonthAndYear } from "@/utils/globals";
import { useParams, usePathname, useSearchParams } from "next/navigation";
import { getUserLevelListByParent, listCategory, listData, listDataRegional } from "@/service/landing/landing";
import { ColumnDef, ColumnFiltersState, PaginationState, SortingState, VisibilityState, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table";
import LandingPagination from "@/components/landing-page/pagination";
import { Reveal } from "@/components/landing-page/Reveal";
import { Link, useRouter } from "@/i18n/routing";
import { Input } from "@/components/ui/input";
import ReactDatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { close, loading } from "@/config/swal";
import { useTranslations } from "next-intl";

const columns: ColumnDef<any>[] = [
  {
    accessorKey: "no",
    header: "No",
    cell: ({ row }) => <span>{row.getValue("no")}</span>,
  },
];

const FilterPage = () => {
  const router = useRouter();
  const asPath = usePathname();
  const params = useParams();
  const searchParams = useSearchParams();
  const locale = params?.locale;
  const [imageData, setImageData] = useState<any>();
  const [totalData, setTotalData] = React.useState<number>(1);
  const [totalPage, setTotalPage] = React.useState<number>(1);
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
  const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({});
  const [rowSelection, setRowSelection] = React.useState({});
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });
  const [page, setPage] = useState(1);
  const [totalContent, setTotalContent] = useState();
  const [change, setChange] = useState(false);
  const sortBy = searchParams?.get("sortBy");
  const title = searchParams?.get("title");
  const categorie = searchParams?.get("category");
  const group = searchParams?.get("group");
  const [contentImage, setContentImage] = useState([]);
  const [, setGetTotalPage] = useState();
  let typingTimer: any;
  const doneTypingInterval = 1500;
  const [search, setSearch] = useState();
  const [categoryFilter, setCategoryFilter] = useState<any>([]);
  const [monthYearFilter, setMonthYearFilter] = useState<any>();
  const [searchTitle, setSearchTitle] = useState<string>("");
  const [sortByOpt, setSortByOpt] = useState<any>(sortBy === "popular" ? "clickCount" : "createdAt");
  const isRegional = asPath?.includes("regional");
  const isSatker = asPath?.includes("satker");
  const [formatFilter, setFormatFilter] = useState<any>([]);
  const pages = page ? page - 1 : 0;
  const [startDateString, setStartDateString] = useState<any>();
  const [endDateString, setEndDateString] = useState<any>();
  const [dateRange, setDateRange] = useState<any>([null, null]);
  const [calenderState, setCalenderState] = useState(false);
  const [handleClose, setHandleClose] = useState(false);
  const [categories, setCategories] = useState([]);
  const [userLevels, setUserLevels] = useState([]);
  const poldaName = params?.polda_name;
  let prefixPath = poldaName ? `/polda/${poldaName}` : "/";
  
  const t = useTranslations("FilterPage");

  // const [startDate, endDate] = dateRange;

  React.useEffect(() => {
    const pageFromUrl = searchParams?.get("page");
    if (pageFromUrl) {
      setPage(Number(pageFromUrl));
    }
  }, [searchParams]);

  useEffect(() => {
    async function initState() {
      getCategories();
      // getSelectedCategory();
      if (isSatker) {
        getUserLevels();
      }
    }

    initState();
  }, []);

  useEffect(() => {
    if (categorie) {
      setCategoryFilter(categorie?.split("&")?.length > 1 ? categorie?.split("&") : [categorie]);
      console.log("Kategori", categorie, categorie?.split("&")?.length > 1 ? categorie?.split("&") : [categorie]);
    }
  }, [categorie]);

  // useEffect(() => {
  //   fetchData();
  // }, [page, sortBy, sortByOpt, title]);

  useEffect(() => {
    async function initState() {
      if (isRegional) {
        getDataRegional();
      } else {
        getDataAll();
      }
    }
    console.log(monthYearFilter, "monthFilter");
    initState();
  }, [change, asPath, monthYearFilter, page, sortBy, sortByOpt, title, startDateString, endDateString, categorie, formatFilter]);

  async function getCategories() {
    const category = await listCategory("1");
    const resCategory = category?.data?.data?.content;
    setCategories(resCategory);
  }

  useEffect(() => {
    function initState() {
      if (dateRange[0] != null && dateRange[1] != null) {
        setStartDateString(getOnlyDate(dateRange[0]));
        setEndDateString(getOnlyDate(dateRange[1]));
        setHandleClose(true);
        console.log("date range", dateRange, getOnlyDate(dateRange[0]));
      }
    }
    initState();
  }, [calenderState]);

  async function getDataAll() {
    if (poldaName && String(poldaName)?.length > 1) {
      const filter = categoryFilter?.length > 0 ? categoryFilter?.sort().join(",") : categorie || "";

      const name = title == undefined ? "" : title;
      const format = formatFilter == undefined ? "" : formatFilter?.join(",");
      const filterGroup = String(poldaName);
      loading();
      const response = await listData(
        "1",
        name,
        filter,
        12,
        pages,
        sortByOpt,
        format,
        "",
        filterGroup,
        startDateString,
        endDateString,
        monthYearFilter ? getOnlyMonthAndYear(monthYearFilter)?.split("/")[0]?.replace("", "") : "",
        monthYearFilter ? getOnlyMonthAndYear(monthYearFilter)?.split("/")[1] : ""
      );
      close();
      const data = response?.data?.data;
      const contentData = data?.content;
      setImageData(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;
      const format = formatFilter == undefined ? "" : formatFilter?.join(",");
      loading();
      const response = await listData(
        "1",
        name,
        filter,
        12,
        pages,
        sortByOpt,
        format,
        "",
        "",
        startDateString,
        endDateString,
        monthYearFilter ? getOnlyMonthAndYear(monthYearFilter)?.split("/")[0]?.replace("", "") : "",
        monthYearFilter ? getOnlyMonthAndYear(monthYearFilter)?.split("/")[1] : ""
      );
      close();
      const data = response?.data?.data;
      const contentData = data?.content;
      setImageData(contentData);
      setTotalData(data?.totalElements);
      setTotalPage(data?.totalPages);
      setTotalContent(response?.data?.data?.totalElements);
    }
  }

  const handleCategoryFilter = (e: boolean, id: string) => {
    let filter = [...categoryFilter];

    if (e) {
      filter = [...categoryFilter, String(id)];
    } else {
      filter.splice(categoryFilter.indexOf(id), 1);
    }
    console.log("checkbox filter", filter);
    setCategoryFilter(filter);
    router.push(`?category=${filter.join("&")}`);
  };

  const handleFormatFilter = (e: boolean, id: string) => {
    let filter = [...formatFilter];

    if (e) {
      filter = [...formatFilter, id];
    } else {
      filter.splice(formatFilter.indexOf(id), 1);
    }
    console.log("Format filter", filter);
    setFormatFilter(filter);
  };

  const cleanCheckbox = () => {
    setCategoryFilter([]);
    setFormatFilter([]);
    router.push(`?category=&title=`);
    setDateRange([null, null]);
    setMonthYearFilter(null);
    setChange(!change);
  };

  async function getDataRegional() {
    const filter = categoryFilter?.length > 0 ? categoryFilter?.sort().join(",") : categorie || "";

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

    setGetTotalPage(response?.data?.data?.totalPages);
    setContentImage(response?.data?.data?.content);
    setTotalContent(response?.data?.data?.totalElements);
  }

  const table = useReactTable({
    data: imageData,
    columns: columns,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    onPaginationChange: setPagination,
    state: {
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
      pagination,
    },
  });

  function getSelectedCategory() {
    const filter = [];

    if (categorie) {
      const categoryArr = categorie.split(",");

      for (const element of categoryArr) {
        filter.push(Number(element));
      }

      setCategoryFilter(filter);
    }
  }

  const handleDeleteDate = () => {
    setDateRange([null, null]);
    setStartDateString("");
    setEndDateString("");
    setHandleClose(false);
  };

  const handleSorting = (e: any) => {
    console.log(e.target.value);
    if (e.target.value == "terbaru") {
      setSortByOpt("createdAt");
    } else {
      setSortByOpt("clickCount");
    }

    setChange(!change);
  };

  async function getUserLevels() {
    const res = await getUserLevelListByParent(761);
    const userLevelList = res?.data?.data;

    if (userLevelList !== null) {
      let optionArr: any = [];

      userLevelList?.map((option: any) => {
        let optionData = {
          id: option.id,
          label: option.name,
          value: option.id,
        };

        optionArr.push(optionData);
      });

      setUserLevels(optionArr);
    }
  }

  const handleKeyUp = () => {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  };

  async function doneTyping() {
    if (searchTitle == "" || searchTitle == undefined) {
      router.push("?title=");
    } else {
      router.push(`?title=${searchTitle}`);
    }
  }

  const handleKeyDown = () => {
    clearTimeout(typingTimer);
  };

  return (
    <div className="flex flex-col">
      {/* Header */}

      <div className="flex flex-col md:flex-row items-start gap-5 p-10 bg-[#f7f7f7] dark:bg-black">
        <p>
          {" "}
          {t("image")} {">"} <span className="font-bold">{t("allImage")}</span>
        </p>
        <p className="font-bold">|</p>
        <p>{`${t("thereIs")} ${totalContent} ${t("downloadableImage")}`}</p>
      </div>

      {/* Left */}
      <div className="flex flex-col lg:flex-row gap-6 p-4">
        <div className="lg:w-[25%] h-fit w-full bg-[#f7f7f7] dark:bg-black p-4 rounded-lg shadow-md">
          <h2 className="text-lg font-semibold mb-4 flex items-center gap-1">
            <Icon icon="stash:filter-light" fontSize={30} />
            Filter
          </h2>
          <div className="border-t border-black my-4 dark:border-white"></div>
          <div className="space-y-6">
            <div>
              <label htmlFor="search" className="block text-sm font-medium text-gray-700 dark:text-white">
                {t("search")}
              </label>
              <Input
                value={searchTitle}
                onChange={(e) => setSearchTitle(e.target.value)}
                onKeyUp={handleKeyUp}
                onKeyDown={handleKeyDown}
                type="text"
                id="search"
                placeholder={t("searchTitle")}
                className="mt-1 w-full border rounded-md py-2 px-3 focus:ring-red-500 focus:border-red-500"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-white">{t("monthYear")}</label>
              <ReactDatePicker
                selected={monthYearFilter}
                className="mt-1 w-full text-xs border rounded-md py-2 px-3 focus:ring-red-500 focus:border-red-500"
                onChange={(date) => setMonthYearFilter(date)}
                dateFormat="MM | yyyy"
                placeholderText={t("selectYear")}
                showMonthYearPicker
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-white">{t("date")}</label>
              <div className="flex  flex-row justify justify-between gap-2">
                <ReactDatePicker
                  selectsRange
                  className="mt-1 w-full border text-sm rounded-md py-2 px-3 focus:ring-red-500 focus:border-red-500"
                  startDate={dateRange[0]}
                  endDate={dateRange[1]}
                  onChange={(update) => {
                    setDateRange(update);
                  }}
                  placeholderText={t("selectDate")}
                  onCalendarClose={() => setCalenderState(!calenderState)}
                />
                <div className="flex items-center">{handleClose ? <Icon icon="carbon:close-filled" onClick={handleDeleteDate} width="20" inline color="#216ba5" /> : ""}</div>
              </div>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-700 dark:text-white">{t("categories")}</h3>
              <ul className="mt-2 space-y-2">
                {categories.map((category: any) => (
                  <li key={category?.id}>
                    <label className="inline-flex items-center" htmlFor={`${category.id}`}>
                      <Checkbox id={`${category.id}`} value={category.id} checked={categoryFilter.includes(String(category.id))} onCheckedChange={(e) => handleCategoryFilter(Boolean(e), category.id)} />
                      <span className="ml-2 text-gray-700 dark:text-white">{category?.name}</span>
                    </label>
                  </li>
                ))}
              </ul>
            </div>
            {/* Garis */}
            <div className="border-t border-black my-4 dark:border-white"></div>
            {/* Garis */}
            <div>
              <h3 className="text-sm font-medium text-gray-700 dark:text-white">Format</h3>
              <ul className="mt-2 space-y-2">
                <li>
                  <label className="inline-flex items-center">
                    <Checkbox id="png" value="png" checked={formatFilter.includes("png")} onCheckedChange={(e) => handleFormatFilter(Boolean(e), "png")} />
                    <span className="ml-2 text-gray-700 dark:text-white">PNG</span>
                  </label>
                </li>
                <li>
                  <label className="inline-flex items-center">
                    <Checkbox id="jpeg" value="jpeg" checked={formatFilter.includes("jpeg")} onCheckedChange={(e) => handleFormatFilter(Boolean(e), "jpeg")} />
                    <span className="ml-2 text-gray-700 dark:text-white">JPEG</span>
                  </label>
                </li>
                <li>
                  <label className="inline-flex items-center">
                    <Checkbox id="jpg" value="jpg" checked={formatFilter.includes("jpg")} onCheckedChange={(e) => handleFormatFilter(Boolean(e), "jpg")} />
                    <span className="ml-2 text-gray-700 dark:text-white">JPG</span>
                  </label>
                </li>
              </ul>
            </div>
            <div className="border-t border-black dark:border-white my-4"></div>
            <div className="text-center">
              <a onClick={cleanCheckbox} className="text-[#bb3523] cursor-pointer">
                <b>Reset Filter</b>
              </a>
            </div>
          </div>
        </div>

        {/* Konten Kanan */}
        <Reveal>
          <div className="flex-1">
            <div className="flex flex-col items-end mb-4">
              <h2 className="text-lg font-semibold">{t("sortBy")}</h2>
              <select defaultValue={sortBy == "popular" ? "terpopuler" : "terbaru"} onChange={(e) => handleSorting(e)} className="border rounded-md py-2 px-3 focus:ring-red-500 focus:border-red-500">
                <option value="latest">{t("latest")}</option>
                <option value="popular">{t("mostPopular")}</option>
              </select>
            </div>

            {imageData?.length > 0 ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {imageData?.map((image: any) => (
                  <Card key={image?.id} className="hover:scale-110 transition-transform duration-300">
                    <CardContent className="flex flex-col text-xs lg:text-sm w-full p-0">
                      <Link href={`${prefixPath}/image/detail/${image?.slug}`}>
                        <img src={image?.thumbnailLink} className="h-60 object-cover items-center justify-center cursor-pointer rounded-lg place-self-center" />
                        <div className="flex flex-row items-center gap-2 text-[10px] mx-2">
                          {formatDateToIndonesian(new Date(image?.createdAt))} {image?.timezone ? image?.timezone : "WIB"}| <Icon icon="formkit:eye" width="15" height="15" />
                          {image?.clickCount}{" "}
                          <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20">
                            <path
                              fill="#f00"
                              d="M7.707 10.293a1 1 0 1 0-1.414 1.414l3 3a1 1 0 0 0 1.414 0l3-3a1 1 0 0 0-1.414-1.414L11 11.586V6h5a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h5v5.586zM9 4a1 1 0 0 1 2 0v2H9z"
                            />
                          </svg>{" "}
                        </div>
                        <div className="font-semibold pr-3 pb-3 mx-2 hover:h-auto truncate hover:whitespace-normal hover:overflow-visible w-full">{image?.title}</div>
                      </Link>
                    </CardContent>
                  </Card>
                ))}
              </div>
            ) : (
              <p className="flex items-center justify-center text-black">
                <img src="/assets/empty-data.png" alt="empty" className="h-60 w-60 my-4" />
              </p>
            )}

            <LandingPagination table={table} totalData={totalData} totalPage={totalPage} />
          </div>
        </Reveal>
      </div>
    </div>
  );
};

export default FilterPage;
