"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 {
  ChevronLeft,
  ChevronRight,
  Eye,
  MoreVertical,
  Search,
  SquarePen,
  Trash2,
  TrendingDown,
  TrendingUp,
} from "lucide-react";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import { paginationBlog } from "@/service/blog/blog";
import { ticketingPagination } from "@/service/ticketing/ticketing";
import { Badge } from "@/components/ui/badge";
import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./columns";
import { listDataAll, listDataImage } from "@/service/content/content";
import { Icon } from "@iconify/react/dist/iconify.js";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useTranslations } from "next-intl";

type StatusFilter = string[];

const ContentTable = () => {
  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 [limit, setLimit] = React.useState(10);
  const userId = getCookiesDecrypt("uie");
  const userLevelId = getCookiesDecrypt("ulie");
  const [categories, setCategories] = React.useState<string[]>();
  const [categoryFilter, setCategoryFilter] = React.useState<string[]>([]);
  const [statusFilter, setStatusFilter] = React.useState<StatusFilter>([]);
  const [startDateString, setStartDateString] = React.useState<string>("");
  const [endDateString, setEndDateString] = React.useState<string>("");
  const [filterByCreator, setFilterByCreator] = React.useState<string>("");
  const [fileTypeFilter, setFileTypeFilter] = React.useState<string[]>([]);
  const [filterBySource, setFilterBySource] = React.useState<string>("");
  const [search, setSearch] = React.useState("");
  const roleId = getCookiesDecrypt("urie");
  const t = useTranslations("Form");

  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, limit, fileTypeFilter, statusFilter, search]);

  async function fetchData() {
    try {
      const isForSelf = Number(roleId) === 4;
      const res = await listDataAll(
        isForSelf,
        !isForSelf,
        page - 1,
        limit,
        fileTypeFilter.sort().join(","),
        categoryFilter.sort().join(","),
        statusFilter.sort().join(","),
        statusFilter.sort().join(",").includes("1") ? userLevelId : "",
        filterByCreator,
        filterBySource,
        startDateString,
        endDateString,
        search
      );
      const data = res?.data?.data;
      const contentData = data?.content;
      contentData.forEach((item: any, index: number) => {
        item.no = (page - 1) * limit + index + 1;
      });

      console.log("contentData : ", contentData);

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

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

  return (
    <div className="w-full overflow-x-auto">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between md:flex-row md:items-center md:justify-between lg:flex-row items-start lg:justify-between lg:items-center px-5">
        <div className="w-full md:w-[200px] mb-2 md:mb-0">
          <InputGroup merged>
            <InputGroupText className="bg-transparent dark:border-secondary dark:group-focus-within:border-secondary">
              <Search className="h-4 w-full lg:w-4 dark:text-white" />
            </InputGroupText>
            <Input
              type="text"
              placeholder={t("searchTitle")}
              className="bg-transparent dark:border-secondary dark:placeholder-white/80 dark:focus:border-secondary dark:text-white"
              value={search}
              onChange={handleSearch}
            />
          </InputGroup>
        </div>
        <div className=" items-center gap-3 w-full md:w-[200px]">
          {/* <Select
            onValueChange={(value) => {
              setStatusFilter([value]);
            }}
          >
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="Select a Filter Status" />
            </SelectTrigger>
            <SelectContent>
              <SelectGroup>
                <SelectLabel>Status</SelectLabel>
                <SelectItem value="1">Menunggu Review</SelectItem>
                <SelectItem value="2">Diterima</SelectItem>
                <SelectItem value="3">Minta Update</SelectItem>
                <SelectItem value="4">Ditolak</SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select> */}
          <Select
            onValueChange={(value) => {
              setFileTypeFilter([value]);
            }}
          >
            <SelectTrigger className="w-full lg:w-[180px]">
              <SelectValue placeholder={t("selectFilter")} />
            </SelectTrigger>
            <SelectContent>
              <SelectGroup>
                <SelectLabel>Filter</SelectLabel>
                <SelectItem value="1">{t("image")}</SelectItem>
                <SelectItem value="2">{t("audio-visual")}</SelectItem>
                <SelectItem value="3">{t("text")}</SelectItem>
                <SelectItem value="4">Audio</SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
      </div>
      <Table className="overflow-hidden mt-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 results.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
      <TablePagination
        table={table}
        totalData={totalData}
        totalPage={totalPage}
      />
    </div>
  );
};

export default ContentTable;
