"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 { cn, getCookiesDecrypt } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./management-user-internal-column-table";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Checkbox } from "@/components/ui/checkbox";
import { close, loading } from "@/config/swal";
import { Link, useRouter } from "@/i18n/routing";
import { getAllUsers } from "@/service/management-user/management-user";

// ✅ Import service baru dari Swagger

const UserInternalTable = () => {
  const router = useRouter();
  const levelId = getCookiesDecrypt("ulie");

  const searchParams = useSearchParams();
  const dataChange = searchParams?.get("dataChange");
  const [showData, setShowData] = React.useState("10");
  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 [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: Number(showData),
  });
  const [search, setSearch] = React.useState("");
  const [categoryFilter, setCategoryFilter] = React.useState<number[]>([]);
  const [statusFilter, setStatusFilter] = React.useState<number[]>([]);
  const [page, setPage] = React.useState(1);
  const [totalPage, setTotalPage] = React.useState(1);

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

  let typingTimer: any;
  const doneTypingInterval = 1500;

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

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

  async function doneTyping() {
    fetchData();
  }

  React.useEffect(() => {
    fetchData();
    router.push("/admin/management-user");
  }, [dataChange]);

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

  React.useEffect(() => {
    fetchData();
    setPagination({
      pageIndex: 0,
      pageSize: Number(showData),
    });
  }, [page, showData]);

  // === 🔥 Implementasi service getAllUsers dari Swagger ===
  async function fetchData() {
    try {
      loading();

      const res = await getAllUsers({
        count: 1,
        limit: Number(showData),
        nextPage: page + 1,
        page: page,
        previousPage: page - 1,
        sort: "desc",
        sortBy: "id",
        totalPage: 10,
      });

      const data = res?.data?.data;
      const contentData = Array.isArray(data)
        ? data
        : data?.content || data?.items || [];

      // Tambahkan nomor urut
      contentData.forEach((item: any, index: number) => {
        item.no = (page - 1) * Number(showData) + index + 1;
      });

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

      setDataTable(contentData);
      setTotalData(data?.totalElements ?? contentData.length ?? 0);
      setTotalPage(data?.totalPages ?? 1);
      close();
    } catch (error) {
      console.error("❌ Error fetching users:", error);
      close();
    }
  }

  const handleChange = (type: string, id: number, checked: boolean) => {
    if (type === "category") {
      if (checked) {
        const temp: number[] = [...categoryFilter];
        temp.push(id);
        setCategoryFilter(temp);
      } else {
        const temp = categoryFilter.filter((a) => a !== id);
        setCategoryFilter(temp);
      }
    } else {
      if (checked) {
        const temp: number[] = [...statusFilter];
        temp.push(id);
        setStatusFilter(temp);
      } else {
        const temp = statusFilter.filter((a) => a !== id);
        setStatusFilter(temp);
      }
    }
  };

  return (
    <div className="bg-white dark:bg-black">
      <div className="flex justify-between py-3">
        <Input
          type="text"
          placeholder="Search"
          onKeyUp={handleKeyUp}
          onKeyDown={handleKeyDown}
          onChange={(e) => setSearch(e.target.value)}
          className="max-w-[300px]"
        />
        <div className="flex flex-row gap-2">
          <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="20">
                  1 - 20 Data
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="25">
                  1 - 25 Data
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="50">
                  1 - 50 Data
                </DropdownMenuRadioItem>
              </DropdownMenuRadioGroup>
            </DropdownMenuContent>
          </DropdownMenu>
          <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>Admin</p>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(3)}
                      onCheckedChange={(e) =>
                        handleChange("status", 3, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Approver
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(4)}
                      onCheckedChange={(e) =>
                        handleChange("status", 4, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Kontributor
                    </label>
                  </div>
                  <p className="mt-3">Kurator</p>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(11)}
                      onCheckedChange={(e) =>
                        handleChange("status", 11, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Koordinator
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(12)}
                      onCheckedChange={(e) =>
                        handleChange("status", 12, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Kurator
                    </label>
                  </div>
                  <p className="mt-3">Feedback Center</p>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(9)}
                      onCheckedChange={(e) =>
                        handleChange("status", 9, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Supervisor
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(10)}
                      onCheckedChange={(e) =>
                        handleChange("status", 10, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Operator
                    </label>
                  </div>
                </div>
              </div>
            </PopoverContent>
          </Popover>
        </div>
      </div>

      {/* === TABLE === */}
      <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 UserInternalTable;
