"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 {
  ChevronDown,
  Search,
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import { listPendingApproval, PendingApprovalData } from "@/service/content/content";
import usePendingApprovalColumns from "./pending-approval-columns";

type PendingApprovalTableProps = {
  typeId?: number;
};

const PendingApprovalTable = ({ typeId }: PendingApprovalTableProps) => {
  const searchParams = useSearchParams();
  const [dataTable, setDataTable] = React.useState<PendingApprovalData[]>([]);
  const [totalData, setTotalData] = React.useState<number>(0);
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
  const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({});
  const [rowSelection, setRowSelection] = React.useState({});
  const [showData, setShowData] = React.useState("10");
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: Number(showData),
  });
  const [page, setPage] = React.useState(1);
  const [totalPage, setTotalPage] = React.useState(1);
  const [search, setSearch] = React.useState("");

  const columns = usePendingApprovalColumns();
  
  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(() => {
    fetchPendingData();
  }, [page, showData, search]);

  async function fetchPendingData() {
    try {
      const res = await listPendingApproval(page, Number(showData), typeId);
      
      if (res && !res.error && res.data) {
        // Filter data based on search if provided
        let filteredData = res.data;
        if (search) {
          filteredData = res.data.filter((item: PendingApprovalData) => 
            item.title.toLowerCase().includes(search.toLowerCase()) ||
            item.authorName.toLowerCase().includes(search.toLowerCase()) ||
            item.categoryName.toLowerCase().includes(search.toLowerCase())
          );
        }
        
        setDataTable(filteredData);
        setTotalData(filteredData.length);
        setTotalPage(Math.ceil(filteredData.length / Number(showData)));
      } else {
        setDataTable([]);
        setTotalData(0);
        setTotalPage(1);
      }
    } catch (error) {
      console.error("Error fetching pending approval data:", error);
      setDataTable([]);
      setTotalData(0);
      setTotalPage(1);
    }
  }

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
  };

  return (
    <div className="w-full overflow-x-auto">
      <div className="flex flex-col md:flex-row lg:flex-row md:justify-between lg:justify-between items-center md:px-5 lg:px-5">
        <div className="relative w-full md:w-[200px] lg:w-[200px] px-2">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 dark:text-white" />
          <Input
            type="text"
            placeholder="Search title, author, category..."
            className="pl-9 bg-transparent dark:border-secondary dark:placeholder-white/80 dark:focus:border-secondary dark:text-white"
            value={search}
            onChange={handleSearch}
          />
        </div>
        <div className="flex flex-row items-center gap-3">
          <div className="flex items-center py-4">
            <div className="mx-3">
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button size="md" variant="outline">
                    {showData} Data
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="w-56 text-sm">
                  <DropdownMenuRadioGroup
                    value={showData}
                    onValueChange={setShowData}
                  >
                    <DropdownMenuRadioItem value="10">
                      10 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="50">
                      50 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="100">
                      100 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="250">
                      250 Data
                    </DropdownMenuRadioItem>
                  </DropdownMenuRadioGroup>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
          <div className="flex items-center py-4">
            <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 mt-3 mx-3">
        <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 pending approval data found.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
      <TablePagination
        table={table}
        totalData={totalData}
        totalPage={totalPage}
      />
    </div>
  );
};

export default PendingApprovalTable;
