"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 { useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./column";

import { listEnableCategory } from "@/service/content/content";
import { Checkbox } from "@/components/ui/checkbox";
import { close, loading } from "@/config/swal";
import { Link, useRouter } from "@/i18n/routing";
import { NewCampaignIcon } from "@/components/icon";
import { getCategories } from "@/service/settings/settings";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { useTranslations } from "next-intl";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import useTableColumns from "./column";
import { UploadIcon } from "lucide-react";

const AdminSettingTrackingTable = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useTranslations("Menu");
  const dataChange = searchParams?.get("dataChange");
  const [openModal, setOpenModal] = React.useState(false);
  const [dataTable, setDataTable] = React.useState<any[]>([]);
  const [totalData, setTotalData] = React.useState<number>(1);
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [region, setRegion] = React.useState<any>();
  const [regionFilter, setRegionFilter] = React.useState<string[]>([]);
  const [statusFilter, setStatusFilter] = React.useState<string[]>([]);
  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 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,
    },
  });

  const manualRegions = [
    { id: "semua", label: "Semua" },
    { id: "mabes", label: "Mabes" },
    { id: "polda", label: "Polda" },
    { id: "satker", label: "Satker" },
    { id: "internasional", label: "Internasional" },
  ];

  React.useEffect(() => {
    if (dataChange) {
      router.push("/admin/settings/category");
    }
    fetchData();
  }, [dataChange]);

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

  React.useEffect(() => {
    fetchData();
  }, [page, regionFilter]);

  async function fetchData() {
    try {
      loading();

      const regionQuery = regionFilter.length
        ? `&publishedLocation=${regionFilter.join(",")}`
        : "";

      const statusQuery = statusFilter.length
        ? `&isPublish=${statusFilter.join(",")}`
        : "";

      const response = await getCategories(
        page - 1,
        `${regionQuery}${statusQuery}`
      );

      const data = response?.data?.data;
      const contentData = data?.content;

      contentData.forEach((item: any, index: number) => {
        item.no = (page - 1) * 10 + index + 1;
      });

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

  const handleChange = (type: string, id: string, checked: boolean) => {
    if (type === "region") {
      if (id === "semua") {
        if (checked) {
          // Pilih semua (kecuali 'semua' itu sendiri)
          setRegionFilter(["mabes", "polda", "satker", "internasional"]);
        } else {
          setRegionFilter([]);
        }
      } else {
        let updated = checked
          ? [...regionFilter, id]
          : regionFilter.filter((val) => val !== id);

        // Jika semua sudah tercentang, maka otomatis centang "semua"
        const allIds = ["mabes", "polda", "satker", "internasional"];
        const allSelected = allIds.every((val) => updated.includes(val));

        setRegionFilter(allSelected ? allIds : updated);
      }
    } else {
      if (checked) {
        setStatusFilter([...statusFilter, id]);
      } else {
        setStatusFilter(statusFilter.filter((val: any) => val !== id));
      }
    }
  };

  return (
    <div className="w-full overflow-x-auto bg-white p-4 rounded-sm space-y-3">
      <div className="flex items-end justify-between">
        {/* <CreateSettingTracking /> */}
        <div className="flex-none">
          <Link href={"/admin/settings/setting-tracking/create"}>
            <Button color="primary" className="text-white" size="md">
              <UploadIcon size={18} className="mr-2" />
              Tambah Setting Tracking
            </Button>
          </Link>
        </div>
        <Popover>
          <PopoverTrigger asChild>
            <Button size="md" variant="outline">
              Filter
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-80 ">
            <div className="flex flex-col gap-2 px-2">
              <div className="flex justify-between text-sm">
                <p>Filter</p>
                <a
                  onClick={() => fetchData()}
                  className="cursor-pointer text-primary"
                >
                  Simpan
                </a>
              </div>
              <div className="flex flex-col gap-1 overflow-auto max-h-[300px] text-xs custom-scrollbar-table">
                <p>Wilayah</p>
                {manualRegions.map((region) => (
                  <div key={region.id} className="flex items-center space-x-2">
                    <Checkbox
                      id={region.id}
                      checked={
                        region.id === "semua"
                          ? ["mabes", "polda", "satker", "internasional"].every(
                              (val) => regionFilter.includes(val)
                            )
                          : regionFilter.includes(region.id)
                      }
                      onCheckedChange={(e) =>
                        handleChange("region", region.id, Boolean(e))
                      }
                    />
                    <label
                      htmlFor={region.id}
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      {region.label}
                    </label>
                  </div>
                ))}
                <p className="mt-3">Status</p>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="aktif"
                    checked={statusFilter.includes("true")}
                    onCheckedChange={(e) =>
                      handleChange("status", "true", Boolean(e))
                    }
                  />
                  <label
                    htmlFor="aktif"
                    className="text-xs font-medium leading-none"
                  >
                    Aktif
                  </label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="nonaktif"
                    checked={statusFilter.includes("false")}
                    onCheckedChange={(e) =>
                      handleChange("status", "false", Boolean(e))
                    }
                  />
                  <label
                    htmlFor="nonaktif"
                    className="text-xs font-medium leading-none"
                  >
                    Non Aktif
                  </label>
                </div>
              </div>
            </div>
          </PopoverContent>
        </Popover>
      </div>
      <Table className="overflow-hidden">
        <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 AdminSettingTrackingTable;
