"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,
  UploadIcon,
} from "lucide-react";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  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 {
  listDataAudio,
  listDataImage,
  listDataVideo,
} from "@/service/content/content";
import { listTicketingInternal } from "@/service/communication/communication";
import { Link } from "@/components/navigation";
import { Card } from "nextra-theme-docs";
import { CardContent } from "@/components/ui/card";

const ContactTable = () => {
  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 [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<string>("");
  const userId = getCookiesDecrypt("uie");
  const userLevelId = getCookiesDecrypt("ulie");
  const [activeCategory, setActiveCategory] = React.useState<string | null>(
    null
  );

  const roleId = getCookiesDecrypt("urie");

  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();
  //   setPagination({
  //     pageIndex: 0,
  //     pageSize: Number(showData),
  //   });
  // }, [page, showData]);
  React.useEffect(() => {
    if (activeCategory) {
      fetchData();
      setPagination({
        pageIndex: 0,
        pageSize: Number(showData),
      });
    }
  }, [page, showData, activeCategory]);

  let typingTimer: any;
  const doneTypingInterval = 1500;

  const handleKeyUp = () => {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  };

  const handleKeyDown = () => {
    clearTimeout(typingTimer);
  };

  async function doneTyping() {
    fetchData();
  }

  // async function fetchData() {
  //   try {
  //     const res = await listTicketingInternal(
  //       page - 1,
  //       Number(showData),
  //       search
  //     );
  //     const data = res?.data?.data;
  //     const contentData = data?.content;
  //     contentData.forEach((item: any, index: number) => {
  //       item.no = (page - 1) * Number(showData) + index + 1;
  //     });

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

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

  async function fetchData() {
    try {
      const res = await listTicketingInternal(
        page - 1,
        Number(showData),
        search,
        activeCategory
      );
      const data = res?.data?.data;
      const contentData = data?.content || [];
      contentData.forEach((item: any, index: number) => {
        item.no = (page - 1) * Number(showData) + index + 1;
      });
      setDataTable(contentData);
      setTotalData(data?.totalElements);
      setTotalPage(data?.totalPages);
    } catch (error) {
      console.error("Error fetching tasks:", error);
    }
  }

  return (
    <div className="w-full overflow-x-auto ">
      <div className="flex justify-between items-center">
        <div className="mt-3 flex flex-row items-center gap-2">
          <InputGroup merged>
            <InputGroupText className="bg-transparent dark:border-secondary dark:group-focus-within:border-secondary">
              <Search className=" h-4 w-4 dark:text-white" />
            </InputGroupText>
            <Input
              type="text"
              placeholder="Search Judul..."
              className="bg-transparent  dark:border-secondary dark:placeholder-white/80 dark:focus:border-secondary dark:text-white"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              onKeyDown={handleKeyDown}
              onKeyUp={handleKeyUp}
            />
          </InputGroup>
        </div>
      </div>
      <div className="flex flex-row items-center justify-around my-3">
        {["Polda", "Satker Humas", "Satker Mabes"].map((category, index) => (
          <CardContent
            key={index}
            className="shadow-lg border p-2 cursor-pointer"
            onClick={() => setActiveCategory(category)}
          >
            <div className="flex flex-col gap-3 text-center py-5 w-[250px]">
              <p className="text-3xl font-bold">
                {index === 0 ? 34 : index === 1 ? 1 : 43}
              </p>
              <p>{category}</p>
              <p className="text-blue-700">Lihat Kontak</p>
            </div>
          </CardContent>
        ))}
      </div>
      {activeCategory && (
        <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>
      )}
    </div>
  );
};

export default ContactTable;
