"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 { UserIcon } from "lucide-react";

import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./column";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { getMediaBlastAccountPage } from "@/service/broadcast/broadcast";
import { Checkbox } from "@/components/ui/checkbox";
import { close, loading } from "@/config/swal";
import { Link } from "@/i18n/routing";
import { Icon } from "@iconify/react/dist/iconify.js";

const AccountListTable = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [dataTable, setDataTable] = React.useState<any[]>([]);
  const [totalData, setTotalData] = 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] = React.useState(1);
  const [totalPage, setTotalPage] = React.useState(1);
  const [filtered, setFiltered] = React.useState<string[]>([]);
  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,
    },
  });

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

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

  async function fetchData() {
    try {
      loading();
      const res = await getMediaBlastAccountPage(
        page - 1,
        filtered ? filtered.join(",") : ""
      );
      const data = res?.data?.data;
      const contentData = data?.content;
      contentData.forEach((item: any, index: number) => {
        item.no = (page - 1) * 10 + index + 1;
      });

      setDataTable(contentData);
      setTotalData(data?.totalElements);
      setTotalPage(data?.totalPages);
      close();
    } catch (error) {
      console.error("Error fetching tasks:", error);
    }
  }

  const handleFilter = (id: string, checked: boolean) => {
    let temp = [...filtered];
    if (checked) {
      temp = [...temp, id];
    } else {
      temp = temp.filter((a) => a !== id);
    }
    setFiltered(temp);
    console.log("sss", temp);
  };

  return (
    <div className="w-full overflow-x-auto bg-white p-4 rounded-sm space-y-3">
      <div className="flex justify-between mb-10 items-center">
        <p className="text-xl font-medium text-default-900">Daftar Akun</p>
        <div className="flex flex-row gap-3">
          <Link href="/admin/broadcast/campaign-list/account-list/create">
            <Button color="primary" size="md" className="text-sm">
              <Icon icon="tdesign:user-add-filled" />
              Tambah Akun
            </Button>
          </Link>
          <Link href="/admin/broadcast/campaign-list/import">
            <Button color="success" size="md" className="text-sm">
              <UserIcon />
              Import Akun
            </Button>
          </Link>
        </div>
      </div>
      <div className="flex justify-end">
        <Popover>
          <PopoverTrigger asChild>
            <Button size="md" variant="outline">
              Filter
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-80 ">
            <div className="flex flex-col gap-2 px-2">
              <div className="flex justify-between text-sm">
                <p>Filter</p>
                <a
                  onClick={() => fetchData()}
                  className="cursor-pointer text-primary"
                >
                  Simpan
                </a>
              </div>
              <div className="flex flex-col gap-1 overflow-auto max-h-[300px] text-xs custom-scrollbar-table">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="accepted"
                    checked={filtered.includes("polri")}
                    onCheckedChange={(e) => handleFilter("polri", Boolean(e))}
                  />
                  <label
                    htmlFor="accepted"
                    className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    POLRI
                  </label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="accepted"
                    checked={filtered.includes("jurnalis")}
                    onCheckedChange={(e) =>
                      handleFilter("jurnalis", Boolean(e))
                    }
                  />
                  <label
                    htmlFor="accepted"
                    className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    JURNALIS
                  </label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="accepted"
                    checked={filtered.includes("umum")}
                    onCheckedChange={(e) => handleFilter("umum", Boolean(e))}
                  />
                  <label
                    htmlFor="accepted"
                    className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    UMUM
                  </label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="accepted"
                    checked={filtered.includes("ksp")}
                    onCheckedChange={(e) => handleFilter("ksp", Boolean(e))}
                  />
                  <label
                    htmlFor="accepted"
                    className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    KSP
                  </label>
                </div>
              </div>
            </div>
          </PopoverContent>
        </Popover>
      </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}
                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>
      <TablePagination
        table={table}
        totalData={totalData}
        totalPage={totalPage}
      />
    </div>
  );
};

export default AccountListTable;
