"use client";
import * as React from "react";
import {
  ColumnDef,
  ColumnFiltersState,
  PaginationState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import { Button } from "@/components/ui/button";
import {
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Eye,
  MoreVertical,
  Search,
  Trash2,
} from "lucide-react";
import { title } from "process";
import { getCookiesDecrypt } from "@/lib/utils";
import TablePagination from "@/components/table/table-pagination";
import {
  deleteBulkSPIT,
  listEnableCategory,
  listSPIT,
} from "@/service/content/content";

import { useSearchParams } from "next/navigation";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import columns from "./columns";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Label } from "@/components/ui/label";
import { useTranslations } from "next-intl";
import { format, parseISO } from "date-fns";
import useTableColumns from "./columns";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import toast from "react-hot-toast";

// export type CompanyData = {
//   no: number;
//   id: any;
//   title: string;
//   categoryName: string;
//   createdAt: string;
//   creatorGroup: string;
//   publishedOn: string;
//   isPublish: any;
//   isPublishOnPolda: any;
//   isDone: string;
// };

const TableSPIT = () => {
  const searchParams = useSearchParams();
  const [spitTable, setSpitTable] = React.useState<any[]>([]);
  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 [search, setSearch] = React.useState("");
  const userId = getCookiesDecrypt("uie");
  const userLevelId = getCookiesDecrypt("ulie");
  const t = useTranslations("AnalyticsDashboard");
  const [dateFilter, setDateFilter] = React.useState("");
  const [totalData, setTotalData] = React.useState<number>(1);
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
    []
  );
  const [statusFilter, setStatusFilter] = React.useState<any[]>([]);
  const [showData, setShowData] = React.useState("10");
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: Number(showData),
  });
  const [categories, setCategories] = React.useState<any[]>([]);
  const roleId = getCookiesDecrypt("urie");
  const columns = useTableColumns();
  const table = useReactTable({
    data: spitTable,
    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,
    },
  });

  const MySwal = withReactContent(Swal);

  async function onSubmitDelete(ids: string[]) {
    if (ids.length === 0) return;

    try {
      loading();
      const response = await deleteBulkSPIT(ids);

      if (response?.error) {
        error(response?.message);
        return;
      }

      toast.success("Konten berhasil dihapus");
      table.resetRowSelection();
      await fetchData();
    } catch (err) {
      toast.error("Terjadi kesalahan saat menghapus");
    } finally {
      close();
    }
  }

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

  // React.useEffect(() => {
  //   fetchData();
  // }, [showData, page, search, statusFilter, dateFilter]);

  // React.useEffect(() => {
  //   fetchData();
  //   getCategories();
  // }, [
  //   // categoryFilter,
  //   statusFilter,
  //   page,
  //   showData,
  //   search,
  //   // startDate,
  //   // endDate,
  // ]);

  React.useEffect(() => {
    fetchData();
    getCategories();
  }, [statusFilter, page, showData, search, dateFilter]);

  async function getCategories() {
    const category = await listEnableCategory("4");
    const resCategory = category?.data?.data?.content;
    setCategories(resCategory || []);
  }

  // Panggil fetchData otomatis ketika dateFilter berubah
  React.useEffect(() => {
    if (dateFilter) {
      fetchData();
    }
  }, [dateFilter]);

  async function fetchData() {
    let isPublish;
    if (statusFilter.length === 0) {
      isPublish = "";
    } else if (statusFilter.length > 1) {
      isPublish = "";
    } else {
      isPublish = statusFilter.includes(1) ? false : true;
    }

    const formattedStartDate = dateFilter
      ? format(new Date(dateFilter + "T00:00:00"), "yyyy-MM-dd")
      : "";

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

      setSpitTable(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);
  };

  function handleStatusCheckboxChange(value: any) {
    setStatusFilter((prev: any) =>
      prev.includes(value)
        ? prev.filter((status: any) => status !== value)
        : [...prev, value]
    );
  }

  return (
    <div className="w-full">
      <div className="flex justify-between items-center px-5">
        <div className="w-[150px] md:w-[250px] lg:w-[300px]">
          <InputGroup merged>
            <InputGroupText className="bg-transparent dark:border-secondary dark:group-focus-within:border-secondary">
              <Search className=" h-6 w-6 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 text-[16px]"
              value={search}
              onChange={handleSearch}
            />
          </InputGroup>
        </div>
        <div className="flex fle-row items-center gap-3">
          <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={(value) => {
                    setShowData(value);
                    setPagination((prev) => ({
                      ...prev,
                      pageSize: Number(value),
                      pageIndex: 0,
                    }));
                    setPage(1);
                  }}
                >
                  <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 className="flex items-center py-4">
            <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>
                {/* <div className="mx-2 my-1">
                  <Label>{t("date", { defaultValue: "Date" })}</Label>
                  <Input
                    type="date"
                    value={dateFilter}
                    onChange={(e) => setDateFilter(e.target.value)}
                    className="max-w-sm"
                  />
                </div> */}
                <div className="mx-2 my-1">
                  <Label>{t("date", { defaultValue: "Tanggal" })}</Label>
                  <Input
                    type="date"
                    value={dateFilter}
                    onChange={(e) => {
                      const value = e.target.value;
                      setDateFilter(value);
                      fetchData(); // langsung panggil data baru
                    }}
                    className="max-w-sm"
                  />
                </div>

                <Label className="ml-2 mt-2">Status</Label>
                <div className="flex items-center px-4 py-1">
                  <input
                    type="checkbox"
                    id="status-2"
                    className="mr-2"
                    checked={statusFilter.includes(1)}
                    onChange={() => handleStatusCheckboxChange(1)}
                  />
                  <label htmlFor="status-2" 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 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.getSelectedRowModel().rows.length > 0 && (
        <div className="mt-4 px-5">
          <Button
            variant="default"
            size="sm"
            onClick={async () => {
              const ids = table
                .getSelectedRowModel()
                .rows.map((row) => row.original.contentId);

              const confirm = await MySwal.fire({
                title: "Yakin ingin menghapus?",
                text: `Anda akan menghapus ${ids.length} item.`,
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya, hapus",
                cancelButtonText: "Batal",
              });

              if (confirm.isConfirmed) {
                onSubmitDelete(ids);
              }
            }}
            className="bg-red-600 text-white"
          >
            <Trash2 className="w-4 h-4 mr-2" />
            Hapus yang dipilih ({table.getSelectedRowModel().rows.length})
          </Button>
        </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 TableSPIT;
