"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 "./banner-column";
import { listBanner, listStaticBanner } from "@/service/settings/settings";

const BannerListTable = () => {
  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 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 listBanner();
    temp = response?.data?.data;
    const response2 = await listStaticBanner();
    console.log("sadadddd", response2?.data?.data.length);
    for (let i = 0; i < response2?.data?.data.length; i++) {
      for (let j = 0; j < temp.length; j++) {
        console.log("temp", j, temp[j].id);
        if (response2?.data?.data[i].mediaUploadId === temp[j].id) {
          temp[j].staticPage = true;
        } else {
          temp[j].staticPage = false;
        }
      }
    }

    console.log("tesmasdasdasdasd", temp);
    setGetData(temp);

    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 BannerListTable;
