"use client";

import * as React from "react";
import {
  ColumnFiltersState,
  PaginationState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ChevronDown, Search } from "lucide-react";
import { getCookiesDecrypt } from "@/lib/utils";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import TablePagination from "@/components/table/table-pagination";
import { listDataAll, listDataSatker, listEnableCategory } from "@/service/content/content";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { format } from "date-fns";
import useTableColumns from "./columns";
import { Label } from "@/components/ui/label";
import { useRouter } from "@/i18n/routing";
import { useSearchParams } from "next/navigation";

const TableSatker = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const MySwal = withReactContent(Swal);

  const [dataTable, setDataTable] = React.useState<any[]>([]);
  const [totalData, setTotalData] = React.useState<number>(1);
  const [totalPage, setTotalPage] = React.useState(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 [page, setPage] = React.useState(1);
  const [search, setSearch] = React.useState("");

  // gunakan ref untuk debounce search
  const searchTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);

  // === FILTER STATES ===
  const [categories, setCategories] = React.useState<any[]>([]);
  const [selectedCategories, setSelectedCategories] = React.useState<number[]>(
    []
  );
  const [categoryFilter, setCategoryFilter] = React.useState<string>("");
  const [statusFilter, setStatusFilter] = React.useState<any[]>([]);
  const [startDate, setStartDate] = React.useState("");
  const [endDate, setEndDate] = React.useState("");
  const [filterByCreator, setFilterByCreator] = React.useState("");
  const [filterBySource, setFilterBySource] = React.useState("");
  const [filterByCreatorGroup, setFilterByCreatorGroup] = React.useState("");
  const [typeId, setTypeId] = React.useState<string>(""); // 1=image, 2=video, 3=text, 4=audio

  const userLevelId = getCookiesDecrypt("ulie");
  const roleId = getCookiesDecrypt("urie");

  const columns = useTableColumns();

  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: Number(showData),
  });

  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,
    },
  });

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

  // Ambil kategori sekali di awal
  React.useEffect(() => {
    getCategories();
  }, []);

  // Fetch data ketika filter/pagination berubah
  React.useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    categoryFilter,
    statusFilter,
    startDate,
    endDate,
    showData,
    page,
    typeId,
    filterByCreatorGroup,
  ]);

  async function getCategories() {
    try {
      // ini mengikuti kode awal, type "2" (misal: kategori video)
      const category = await listEnableCategory("2");
      const resCategory = category?.data?.data?.content;
      setCategories(resCategory || []);
    } catch (error) {
      console.error("Error fetching categories:", error);
    }
  }

  async function fetchData(showLoader = false, customSearch?: string) {
    const formattedStartDate = startDate
      ? format(new Date(startDate), "yyyy-MM-dd")
      : "";
    const formattedEndDate = endDate
      ? format(new Date(endDate), "yyyy-MM-dd")
      : "";

    try {
      if (showLoader) {
        MySwal.fire({
          title: "Memuat data...",
          html: "Mohon tunggu sebentar",
          allowOutsideClick: false,
          didOpen: () => MySwal.showLoading(),
        });
      }

      const isForSelf = Number(roleId) === 4;
      const isApproval = !isForSelf;

      const res = await listDataSatker(
        isForSelf,
        isApproval,
        page - 1, // page (0-based)
        parseInt(showData) || 10, // limit
        search, // search (kalau diperlukan di backend)
        typeId, // typeId: 1=image, 2=video, 3=text, 4=audio
        statusFilter?.join(","), // statusId
        statusFilter?.join(",")?.includes("1") ? userLevelId : "",
        filterByCreator,
        filterBySource,
        formattedStartDate,
        formattedEndDate,
        customSearch ?? search // title
      );

      const data = res?.data?.data;
      const contentData = data?.content || [];
      const newData = contentData.map((item: any, index: number) => ({
        ...item,
        no: (page - 1) * Number(showData) + index + 1,
      }));

      setDataTable([...newData]);
      setTotalData(data?.totalElements || 0);
      setTotalPage(data?.totalPages || 1);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      MySwal.close();
    }
  }

  // === HANDLERS ===
  const handleCheckboxChange = (categoryId: number) => {
    setSelectedCategories((prev) =>
      prev.includes(categoryId)
        ? prev.filter((id) => id !== categoryId)
        : [...prev, categoryId]
    );

    setCategoryFilter((prev) => {
      const updated = prev.split(",").filter(Boolean).map(Number);
      const newList = updated.includes(categoryId)
        ? updated.filter((id) => id !== categoryId)
        : [...updated, categoryId];
      return newList.join(",");
    });
  };

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

  // Search dengan debounce 2 detik
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearch(value);

    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    searchTimeoutRef.current = setTimeout(() => {
      // setiap kali search, reset ke page 1
      setPage(1);
      fetchData(true, value);
    }, 2000);
  };

  const handleSearchFilterByCreator = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const value = e.target.value;
    setFilterByCreator(value);
    setPage(1);
    fetchData(true);
  };

  const handleSearchFilterBySource = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const value = e.target.value;
    setFilterBySource(value);
    setPage(1);
    fetchData(true);
  };

  // 🧹 Reset semua filter
  const handleResetFilters = () => {
    setSelectedCategories([]);
    setCategoryFilter("");
    setStatusFilter([]);
    setStartDate("");
    setEndDate("");
    setFilterByCreator("");
    setFilterBySource("");
    setFilterByCreatorGroup("");
    setTypeId("");
    setPage(1);
    fetchData(true);
  };

  return (
    <div className="w-full overflow-x-auto">
      <div className="flex flex-col md:flex-row md:justify-between items-center md:px-5">
        {/* 🔍 Search bar */}
        <div className="w-full md:w-[200px] lg:w-[300px] px-2">
          <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="Cari 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>

        {/* Filter & Columns & ShowData */}
        <div className="flex flex-wrap items-center gap-3 mt-2 md:mt-0">
          {/* Show Data Dropdown */}
          <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>

          {/* Jenis Konten (typeId) */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="md">
                Jenis Konten <ChevronDown />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-56 text-sm">
              <DropdownMenuRadioGroup
                value={typeId}
                onValueChange={(value) => {
                  setTypeId(value);
                  setPage(1);
                  fetchData(true);
                }}
              >
                <DropdownMenuRadioItem value="">
                  Semua Jenis
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="1">
                  Gambar / Image
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="2">
                  Video
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="3">
                  Teks / Artikel
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="4">
                  Audio
                </DropdownMenuRadioItem>
              </DropdownMenuRadioGroup>
            </DropdownMenuContent>
          </DropdownMenu>

          {/* Filter Dropdown */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="md">
                Filter <ChevronDown />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent
              align="end"
              className="w-64 h-[380px] overflow-y-auto"
            >
              {/* 🧹 Reset All Button */}
              <div className="flex justify-end px-3 pt-2 pb-1">
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-xs text-gray-700 hover:bg-red-200 dark:text-white"
                  onClick={handleResetFilters}
                >
                  Reset Semua Filter
                </Button>
              </div>

              <Label className="ml-2">Kategori</Label>
              {categories.length > 0 ? (
                categories.map((category) => (
                  <div
                    key={category.id}
                    className="flex items-center px-4 py-1"
                  >
                    <input
                      type="checkbox"
                      id={`category-${category.id}`}
                      className="mr-2"
                      checked={selectedCategories.includes(category.id)}
                      onChange={() => handleCheckboxChange(category.id)}
                    />
                    <label
                      htmlFor={`category-${category.id}`}
                      className="text-sm"
                    >
                      {category.name}
                    </label>
                  </div>
                ))
              ) : (
                <p className="text-sm text-gray-500 px-4 py-2">
                  Tidak ada kategori.
                </p>
              )}

              <div className="mx-2 my-1">
                <Label>Tanggal Awal</Label>
                <Input
                  type="date"
                  value={startDate}
                  onChange={(e) => {
                    setStartDate(e.target.value);
                    setPage(1);
                  }}
                />
              </div>
              <div className="mx-2 my-1">
                <Label>Tanggal Akhir</Label>
                <Input
                  type="date"
                  value={endDate}
                  onChange={(e) => {
                    setEndDate(e.target.value);
                    setPage(1);
                  }}
                />
              </div>

              <div className="mx-2 my-1">
                <Label>Kreator</Label>
                <Input
                  placeholder="Nama kreator..."
                  value={filterByCreator}
                  onChange={handleSearchFilterByCreator}
                />
              </div>

              <div className="mx-2 my-1">
                <Label>Sumber</Label>
                <Input
                  placeholder="Nama sumber..."
                  value={filterBySource}
                  onChange={handleSearchFilterBySource}
                />
              </div>

              <Label className="ml-2 mt-2">Status</Label>
              {[1, 2, 3, 4].map((id) => {
                const label =
                  id === 1
                    ? "Menunggu Review"
                    : id === 2
                    ? "Diterima"
                    : id === 3
                    ? "Minta Update"
                    : "Ditolak";
                return (
                  <div key={id} className="flex items-center px-4 py-1">
                    <input
                      type="checkbox"
                      id={`status-${id}`}
                      className="mr-2"
                      checked={statusFilter.includes(id)}
                      onChange={() => handleStatusCheckboxChange(id)}
                    />
                    <label htmlFor={`status-${id}`} className="text-sm">
                      {label}
                    </label>
                  </div>
                );
              })}
            </DropdownMenuContent>
          </DropdownMenu>

          {/* Columns Toggle */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="md">
                Columns <ChevronDown />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {table
                .getAllColumns()
                .filter((column) => column.getCanHide())
                .map((column) => (
                  <DropdownMenuCheckboxItem
                    key={column.id}
                    className="capitalize"
                    checked={column.getIsVisible()}
                    onCheckedChange={(value) =>
                      column.toggleVisibility(!!value)
                    }
                  >
                    {column.id}
                  </DropdownMenuCheckboxItem>
                ))}
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* === TABLE === */}
      <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">
                Tidak ada hasil ditemukan.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>

      <TablePagination
        table={table}
        totalData={totalData}
        totalPage={totalPage}
      />
    </div>
  );
};

export default TableSatker;
