"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 {
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Eye,
  MoreVertical,
  Search,
  SquarePen,
  Trash2,
  TrendingDown,
  TrendingUp,
  UploadIcon,
} from "lucide-react";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import { ticketingPagination } from "@/service/ticketing/ticketing";
import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./columns";
import { paginationSchedule } from "@/service/schedule/schedule";
import { useTranslations } from "next-intl";
import { CardHeader, CardTitle } from "@/components/ui/card";
import { Link } from "@/i18n/routing";
import useTableColumns from "./columns";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Label } from "@/components/ui/label";

const PressReleaseTable = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useTranslations("Schedule");
  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("50");
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: Number(showData),
  });
  const [page, setPage] = React.useState(1);
  const [totalPage, setTotalPage] = React.useState(1);
  const [limit, setLimit] = React.useState(10);
  const [search, setSearch] = React.useState<string>("");
  const [statusFilter, setStatusFilter] = React.useState<number[]>([]);
  const columns = useTableColumns();
  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, showData, search, statusFilter]);

  async function fetchData() {
    try {
      const res = await paginationSchedule(
        showData,
        page - 1,
        3,
        search,
        statusFilter
      );
      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);
    }
  }

  const handleStatusCheckboxChange = (statusId: number) => {
    const updatedFilter = statusFilter.includes(statusId)
      ? statusFilter.filter((id) => id !== statusId)
      : [...statusFilter, statusId];

    setStatusFilter(updatedFilter);
  };

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value); // Perbarui state search
    table.getColumn("judul")?.setFilterValue(e.target.value); // Set filter tabel
  };

  return (
    <div>
      <CardHeader className="border-b border-solid border-default-200 mb-6">
        <CardTitle>
          <div className="flex items-center">
            <div className="flex-1 text-xl font-medium text-default-900">
              {t("press-release")} {t("schedule")}
            </div>
            <div className="flex-none">
              <Link href={"/contributor/schedule/press-release/create"}>
                <Button color="primary" className="text-white">
                  <UploadIcon size={18} className="mr-2" />
                  {t("create-schedule")}
                </Button>
              </Link>
            </div>
          </div>
        </CardTitle>
      </CardHeader>
      <div className="w-full overflow-x-auto">
        <div className="flex flex-col sm:flex-row md:flex-row lg:flex-row justify-between items-center px-3 gap-y-2">
          <div className="w-full sm:w-[150px] md:w-[250px] lg:w-[250px]">
            <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 Title..."
                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="flex flex-row">
            <div className="mx-3">
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button size="md" variant="outline">
                    1 - {showData} Data
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="w-56 text-sm">
                  <DropdownMenuRadioGroup
                    value={showData}
                    onValueChange={setShowData}
                  >
                    <DropdownMenuRadioItem value="10">
                      1 - 10 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="50">
                      1 - 50 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="100">
                      1 - 100 Data
                    </DropdownMenuRadioItem>
                    <DropdownMenuRadioItem value="250">
                      1 - 250 Data
                    </DropdownMenuRadioItem>
                  </DropdownMenuRadioGroup>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
            <div className="">
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" className="ml-auto" size="md">
                    Filter <ChevronDown />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent
                  align="end"
                  className="w-64 h-[150px] overflow-y-auto"
                >
                  <div className="flex flex-row justify-between my-1 mx-1">
                    <p>Filter</p>
                  </div>

                  <Label className="ml-2 mt-2">Status</Label>
                  <div className="flex items-center px-4 py-1">
                    <input
                      type="checkbox"
                      id="status-1"
                      className="mr-2"
                      checked={statusFilter.includes(1)}
                      onChange={() => handleStatusCheckboxChange(1)}
                    />
                    <label htmlFor="status-1" className="text-sm">
                      Menunggu Review
                    </label>
                  </div>
                  <div className="flex items-center px-4 py-1">
                    <input
                      type="checkbox"
                      id="status-2"
                      className="mr-2"
                      checked={statusFilter.includes(2)}
                      onChange={() => handleStatusCheckboxChange(2)}
                    />
                    <label htmlFor="status-2" className="text-sm">
                      Diterima
                    </label>
                  </div>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </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>
    </div>
  );
};

export default PressReleaseTable;
