"use client";

import * as React from "react";
import {
  ColumnDef,
  ColumnFiltersState,
  PaginationState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { Button } from "@/components/ui/button";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Eye,
  MoreVertical,
  Search,
  SquarePen,
  Trash2,
  TrendingDown,
  TrendingUp,
  UserIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./column";
import { listEnableCategory } from "@/service/content/content";
import { close, loading } from "@/config/swal";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { link } from "fs";
import { listDataAll } from "@/service/landing/landing";
import SearchImageComponent from "@/components/form/media-tracking/search-image-card";
import SearchVideoComponent from "@/components/form/media-tracking/search-video-card";
import SearchDocumentComponent from "@/components/form/media-tracking/search-document-card";
import SearchAudioComponent from "@/components/form/media-tracking/search-audio-card";
import { getMediaTracking } from "@/service/media-tracking/media-tracking";
import { group } from "console";
import router from "next/router";
import { title } from "process";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import { Input } from "@/components/ui/input";

const ResultTable = () => {
  const router = useRouter();
  const asPath = usePathname();
  const searchParams = useSearchParams();
  const [showData, setShowData] = React.useState("10");
  const [categories, setCategories] = React.useState<any>();
  const [dataTable, setDataTable] = React.useState<any[]>([]);
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
    []
  );
  const [showTable, setShowTable] = React.useState(false);
  const [onSearch, setOnSearch] = React.useState("");
  const [columnVisibility, setColumnVisibility] =
    React.useState<VisibilityState>({});
  const [rowSelection, setRowSelection] = React.useState({});
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: Number(showData),
  });
  const [categoryFilter, setCategoryFilter] = React.useState<any>([]);
  const [searchTitle, setSearchTitle] = React.useState<string>("");
  const [statusFilter, setStatusFilter] = React.useState<number[]>([]);
  const [page, setPage] = React.useState(1);
  const [imageData, setImageData] = React.useState<any>();
  const [totalData, setTotalData] = React.useState<number>(1);
  const [totalPage, setTotalPage] = React.useState(1);
  const [contentAll, setContentAll] = React.useState([]);
  const [formatFilter, setFormatFilter] = React.useState<any>([]);
  const [totalContent, setTotalContent] = React.useState();
  const [search, setSearch] = React.useState<string>("");
  const group = searchParams?.get("group");
  const title = searchParams?.get("title");
  const categorie = searchParams?.get("category");
  const table = useReactTable({
    data: dataTable,
    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,
    },
  });

  let typingTimer: any;
  const doneTypingInterval = 1500;

  // async function doneTyping() {
  //   fetchData();
  // }

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

  React.useEffect(() => {
    getCategories();
  }, []);

  React.useEffect(() => {
    getDataTable();
  }, [page, showData, search]);

  const getDataTable = async () => {
    const res = await getMediaTracking(page - 1, search, showData);

    const data = res?.data?.data;
    const newData = data?.content;

    newData.forEach((item: any, index: number) => {
      item.no = (page - 1) * Number(showData) + index + 1;
    });

    setDataTable(newData);
    setTotalData(data?.totalElements);
    setTotalPage(data?.totalPages);
    setTotalContent(data.totalElements);
  };

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

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

  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 cleanCheckbox = () => {
    setCategoryFilter([]);
    setFormatFilter([]);
    router.push(`?category=&title=`);
  };

  // async function getData() {
  //   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 format = formatFilter == undefined ? "" : formatFilter?.join(",");
  //       const filterGroup = group == undefined ? asPath.split("/")[2] : group;
  //       loading();
  //       const response = await listDataAll("", name, filter, "");
  //       close();
  //       // setGetTotalPage(response?.data?.data?.totalPages);
  //       // setContentImage(response?.data?.data?.content);
  //       // setTotalContent(response?.data?.data?.totalElements);
  //       const data = response?.data?.data;
  //       const contentData = data?.content;
  //       setImageData(contentData);
  //       setTotalData(data?.totalElements);
  //       setContentAll(response?.data?.data?.content);
  //       setTotalPage(data?.totalPages);
  //       setTotalContent(response?.data?.data?.totalElements);
  //     }
  //   }
  // }

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
    table.getColumn("judul")?.setFilterValue(e.target.value);
  };

  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="w-full overflow-x-auto bg-white dark:bg-black p-4 rounded-sm space-y-3 border ">
      <div className="flex flex-col sm:flex-row lg:flex-row justify-end sm:items-center md:items-center lg:items-center">
        <div className=" flex flex-row justify-end items-center gap-3">
          <div className="flex items-center">
            <div className="mx-3">
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button size="md" variant="outline">
                    1 - {showData} Data
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="w-56 text-sm">
                  <DropdownMenuRadioGroup
                    value={showData}
                    onValueChange={setShowData}
                  >
                    <DropdownMenuRadioItem value="10">
                      1 - 10 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="50">
                      1 - 50 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="100">
                      1 - 100 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="250">
                      1 - 250 Data
                    </DropdownMenuRadioItem>
                  </DropdownMenuRadioGroup>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>

          <div className="flex items-center py-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="ml-auto" size="md">
                  Columns <ChevronDown />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                {table
                  .getAllColumns()
                  .filter((column) => column.getCanHide())
                  .map((column) => {
                    return (
                      <DropdownMenuCheckboxItem
                        key={column.id}
                        className="capitalize"
                        checked={column.getIsVisible()}
                        onCheckedChange={(value) =>
                          column.toggleVisibility(!!value)
                        }
                      >
                        {column.id}
                      </DropdownMenuCheckboxItem>
                    );
                  })}
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>
      <Table className="overflow-hidden">
        <TableHeader>
          {table.getHeaderGroups().map((headerGroup) => (
            <TableRow key={headerGroup.id} className="bg-default-200">
              {headerGroup.headers.map((header) => (
                <TableHead key={header.id}>
                  {header.isPlaceholder
                    ? null
                    : flexRender(
                        header.column.columnDef.header,
                        header.getContext()
                      )}
                </TableHead>
              ))}
            </TableRow>
          ))}
        </TableHeader>
        <TableBody>
          {table.getRowModel().rows?.length ? (
            table.getRowModel().rows.map((row) => (
              <TableRow key={row.id} className="h-[75px]">
                {row.getVisibleCells().map((cell) => (
                  <TableCell key={cell.id}>
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={columns.length} className="h-24 text-center">
                No results.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
      <TablePagination
        table={table}
        totalData={totalData}
        totalPage={totalPage}
      />
      {/* <div className="flex justify-end mt-4">
        <Button
          color="primary"
          size="md"
          className="text-sm mr-3"
          onClick={() => setShowTable(false)}
        >
          Tracking Berita Baru
        </Button>
      </div> */}
      {/* </>
      )} */}
    </div>
  );
};

export default ResultTable;
