"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 { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/components/ui/carousel";
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 [audioData, setAudioData] = 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 satkerName = params?.satker_name;
  let prefixPath = satkerName ? `/satker/${satkerName}` : "/";
  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("4");
    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 (satkerName && String(satkerName)?.length > 1) {
      const filter = categoryFilter?.length > 0 ? categoryFilter?.sort().join(",") : categorie || "";

      const name = title == undefined ? "" : title;
      const format = formatFilter == undefined ? "" : formatFilter?.join(",");
      const filterGroup = "satker-" + String(satkerName);
      loading();
      const response = await listData(
        "4",
        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;
      setAudioData(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(
        "4",
        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;
      setAudioData(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: audioData,
    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>
          {" "}
          Audio {">"} <span className="font-bold">{t("allAudio")}</span>
        </p>
        <p className="font-bold">|</p>
        <p>{`${t("thereIs")} ${totalContent} ${t("downloadableAudio")}`}</p>
      </div>

      {/* Left */}
      <div className="flex flex-col lg:flex-row gap-6 p-4">
        <div className="lg:w-[25%] 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 text-sm 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("searchDate")}
                  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("wav")} onCheckedChange={(e) => handleFormatFilter(Boolean(e), "wav")} />
                    <span className="ml-2 text-gray-700 dark:text-white">WAV</span>
                  </label>
                </li>
                <li>
                  <label className="inline-flex items-center">
                    <Checkbox id="jpeg" value="jpeg" checked={formatFilter.includes("mp3")} onCheckedChange={(e) => handleFormatFilter(Boolean(e), "mp3")} />
                    <span className="ml-2 text-gray-700 dark:text-white">MP3</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>

            {audioData?.length > 0 ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {audioData?.map((image: any) => (
                  <Carousel className="w-full max-w-7xl mx-auto">
                    <CarouselContent>
                      {audioData?.map((audio: any) => (
                        <CarouselItem key={audio?.id} className="md:basis-1/2 lg:basis-1/3">
                          <div className="flex flex-row gap-6">
                            <Link href={`${prefixPath}/audio/detail/${audio?.slug}`} className="flex flex-col sm:flex-row items-center bg-white dark:bg-gray-800 cursor-pointer shadow-md rounded-lg p-4 gap-4 w-full">
                              <div className="flex items-center justify-center bg-red-500 text-white rounded-lg w-16 h-8 lg:h-16">
                                <svg width="32" height="34" viewBox="0 0 32 34" fill="null" xmlns="http://www.w3.org/2000/svg">
                                  <path
                                    d="M23.404 0.452014C23.7033 0.35857 24.0204 0.336816 24.3297 0.388509C24.639 0.440203 24.9318 0.563895 25.1845 0.749599C25.4371 0.935304 25.6426 1.17782 25.7843 1.45756C25.9259 1.73731 25.9998 2.04644 26 2.36001V14.414C25.3462 14.2296 24.6766 14.1064 24 14.046V8.36001L10 12.736V27C10 28.1264 9.6197 29.2197 8.92071 30.1029C8.22172 30.9861 7.24499 31.6075 6.14877 31.8663C5.05255 32.125 3.90107 32.0061 2.88089 31.5287C1.86071 31.0514 1.03159 30.2435 0.52787 29.2361C0.024152 28.2286 -0.124656 27.0806 0.105556 25.9781C0.335768 24.8755 0.931513 23.883 1.79627 23.1613C2.66102 22.4396 3.74413 22.031 4.87009 22.0017C5.99606 21.9724 7.09893 22.3242 8.00001 23V6.73601C7.99982 6.30956 8.13596 5.8942 8.38854 5.55059C8.64112 5.20698 8.99692 4.9531 9.40401 4.82601L23.404 0.452014ZM10 10.64L24 6.26601V2.36001L10 6.73601V10.64ZM5.00001 24C4.20436 24 3.44129 24.3161 2.87869 24.8787C2.31608 25.4413 2.00001 26.2044 2.00001 27C2.00001 27.7957 2.31608 28.5587 2.87869 29.1213C3.44129 29.6839 4.20436 30 5.00001 30C5.79566 30 6.55872 29.6839 7.12133 29.1213C7.68394 28.5587 8.00001 27.7957 8.00001 27C8.00001 26.2044 7.68394 25.4413 7.12133 24.8787C6.55872 24.3161 5.79566 24 5.00001 24ZM32 25C32 27.387 31.0518 29.6761 29.364 31.364C27.6761 33.0518 25.387 34 23 34C20.6131 34 18.3239 33.0518 16.636 31.364C14.9482 29.6761 14 27.387 14 25C14 22.6131 14.9482 20.3239 16.636 18.6361C18.3239 16.9482 20.6131 16 23 16C25.387 16 27.6761 16.9482 29.364 18.6361C31.0518 20.3239 32 22.6131 32 25ZM27.47 24.128L21.482 20.828C21.3298 20.7443 21.1583 20.7016 20.9846 20.7043C20.8108 20.707 20.6408 20.7549 20.4912 20.8433C20.3416 20.9317 20.2176 21.0576 20.1315 21.2086C20.0453 21.3595 20 21.5302 20 21.704V28.304C20 28.4778 20.0453 28.6486 20.1315 28.7995C20.2176 28.9504 20.3416 29.0763 20.4912 29.1647C20.6408 29.2531 20.8108 29.301 20.9846 29.3037C21.1583 29.3064 21.3298 29.2638 21.482 29.18L27.47 25.88C27.6268 25.7937 27.7575 25.6669 27.8486 25.5128C27.9397 25.3587 27.9877 25.183 27.9877 25.004C27.9877 24.825 27.9397 24.6493 27.8486 24.4952C27.7575 24.3412 27.6268 24.2143 27.47 24.128Z"
                                    fill="white"
                                  />
                                </svg>
                              </div>

                              <div className="flex flex-col  flex-1">
                                <div className="text-gray-500 dark:text-gray-400 flex flex-row text-sm">
                                  {formatDateToIndonesian(new Date(audio?.createdAt))} {audio?.timezone ? audio?.timezone : "WIB"} | <Icon icon="formkit:eye" width="15" height="15" /> {audio?.clickCount}{" "}
                                </div>
                                <div className="font-semibold text-gray-900 dark:text-white mt-1 text-sm h-5 hover:h-auto truncate hover:whitespace-normal hover:overflow-visible">{audio?.title}</div>
                              </div>
                            </Link>
                          </div>
                        </CarouselItem>
                      ))}
                    </CarouselContent>
                    <CarouselPrevious />
                    <CarouselNext />
                  </Carousel>
                ))}
              </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;
