"use client";

import * as React from "react";
import {
  ColumnDef,
  ColumnFiltersState,
  PaginationState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import { useSearchParams } from "next/navigation";

import { close, loading } from "@/config/swal";
import { Link, useRouter } from "@/i18n/routing";
import columns from "./popup-column";
import { listBanner, listStaticBanner } from "@/service/settings/settings";
import { listDataPopUp } from "@/service/broadcast/broadcast";

const PopUpListTable = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [showData, setShowData] = React.useState("10");

  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: Number(showData),
  });
  const [getData, setGetData] = React.useState<any>([]);
  const [categoryFilter, setCategoryFilter] = React.useState<number[]>([]);
  const [statusFilter, setStatusFilter] = React.useState<number[]>([]);
  const dataChange = searchParams?.get("dataChange");

  const [page, setPage] = React.useState(1);
  const [totalPage, setTotalPage] = React.useState(1);
  const table = useReactTable({
    data: getData,
    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,
    },
  });

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

  React.useEffect(() => {
    if (dataChange) {
      router.push("/admin/settings/banner");
    }
    getListBanner();
  }, [dataChange]);

  React.useEffect(() => {
    getListBanner();
    // getListStaticBanner();
  }, [page, showData]);

  async function getListBanner() {
    loading();
    let temp: any;

    const response = await listDataPopUp(
      page - 1,
      showData,
      "",
      categoryFilter?.sort().join(","),
      statusFilter?.sort().join(",")
    );
    const data = response?.data?.data?.content;
    console.log("banner", data);
    setGetData(data);

    close();
  }

  return (
    <>
      <Table className="overflow-hidden mt-10">
        <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}
                data-state={row.getIsSelected() && "selected"}
                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>
    </>
  );
};

export default PopUpListTable;
