"use client";
import React, { useEffect, useState } from "react";
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "@/components/ui/pagination";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Icon } from "@iconify/react/dist/iconify.js";
import { formatDateToIndonesian, generateLocalizedPath } from "@/utils/globals";
import { useParams, usePathname, useRouter, useSearchParams } from "next/navigation";
import { getListContent } from "@/service/landing/landing";
import { ColumnDef, ColumnFiltersState, PaginationState, SortingState, VisibilityState, flexRender, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table";
import TablePagination from "@/components/table/table-pagination";
import { Response } from "@dnd-kit/core/dist/sensors/types";
import LandingPagination from "@/components/landing-page/pagination";

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

const categories = [
  { id: 1, title: "HUT HUMAS KE - 73" },
  { id: 2, title: "OPERASI ZEBRA 2024" },
  { id: 3, title: "PON XXI" },
  { id: 4, title: "OPS LILIN NATARU 2024" },
  { id: 5, title: "HUT HUMAS KE - 72" },
  { id: 6, title: "OPS MANTAP PRAJA & PILKADA 2024" },
  { id: 7, title: "OPS KETUPAT 2024" },
  { id: 8, title: "OPS PATUH 2024" },
  { id: 9, title: "HARI JUANG POLRI" },
  { id: 10, title: "HUT RI KE-79" },
  { id: 11, title: "HARI BHAYANGKARA KE-78" },
];
const formatPicture = [
  { id: 1, title: "PNG" },
  { id: 2, title: "JPEG" },
  { id: 3, title: "JPG" },
];

const FilterPage = () => {
  const router = useRouter();
  const pathname = 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);

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

  useEffect(() => {
    fetchData();
  }, [page]);

  const fetchData = async () => {
    const response = await getListContent({ page: page - 1, size: 6, sortBy: "createdAt", contentTypeId: "1" });
    console.log(response);

    const data = response.data?.data;
    const contentData = data?.content;
    setImageData(contentData);
    setTotalData(data?.totalElements);
    setTotalPage(data?.totalPages);
  };

  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,
    },
  });

  return (
    <div className="flex flex-col">
      {/* Header */}
      <div className="flex flex-col md:flex-row items-start gap-5 p-10 bg-gray-200">
        <p>
          {" "}
          Audio Visual {">"} <span className="font-bold">Semua Audio Visual</span>
        </p>
        <p className="font-bold">|</p>
        <p>Terdapat 324911 artikel berisi Audio Visual yang dapat diunduh </p>
      </div>
      {/* Left */}
      <div className="flex flex-col lg:flex-row gap-6 p-4">
        <div className="lg:w-1/4 w-full bg-white p-4 rounded-lg shadow-md">
          <h2 className="text-lg font-semibold mb-4">Filter</h2>
          <div className="space-y-6">
            <div>
              <label htmlFor="search" className="block text-sm font-medium text-gray-700">
                Pencarian
              </label>
              <input type="text" id="search" placeholder="Cari judul..." className="mt-1 w-full border rounded-md py-2 px-3 focus:ring-red-500 focus:border-red-500" />
            </div>

            <div>
              <label htmlFor="month" className="block text-sm font-medium text-gray-700">
                Tahun & Bulan
              </label>
              <input type="month" id="month" className="mt-1 w-full border rounded-md py-2 px-3 focus:ring-red-500 focus:border-red-500" />
            </div>

            <div>
              <label htmlFor="date" className="block text-sm font-medium text-gray-700">
                Tanggal
              </label>
              <input type="date" id="date" className="mt-1 w-full border rounded-md py-2 px-3 focus:ring-red-500 focus:border-red-500" />
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-700">Kategori</h3>
              <ul className="mt-2 space-y-2">
                {categories.map((category) => (
                  <li key={category?.id}>
                    <label className="inline-flex items-center">
                      <Checkbox id="terms" />
                      <span className="ml-2 text-gray-700">{category.title}</span>
                    </label>
                  </li>
                ))}
              </ul>
            </div>
            {/* Garis */}
            <div className="border-t border-black my-4"></div>
            {/* Garis */}
            <div>
              <h3 className="text-sm font-medium text-gray-700">Format Foto</h3>
              <ul className="mt-2 space-y-2">
                {formatPicture.map((format) => (
                  <li key={format?.id}>
                    <label className="inline-flex items-center">
                      <Checkbox id="terms" />
                      <span className="ml-2 text-gray-700">{format.title}</span>
                    </label>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>

        {/* Konten Kanan */}
        <div className="flex-1">
          <div className="flex flex-col items-end mb-4">
            <h2 className="text-lg font-semibold">Urutkan berdasarkan</h2>
            <select className="border rounded-md py-2 px-3 focus:ring-red-500 focus:border-red-500">
              <option value="terbaru">Terbaru</option>
              <option value="terlama">Terlama</option>
            </select>
          </div>

          <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">
                  <img src={image?.thumbnailLink} className="h-60 object-cover items-center justify-center cursor-pointer rounded-lg" />
                  <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>
                </CardContent>
              </Card>
            ))}
          </div>
          <LandingPagination table={table} totalData={totalData} totalPage={totalPage}/>
        </div>
      </div>
    </div>
  );
};

export default FilterPage;
