"use client";

import { useState } from "react";
import { DataTable } from "../../../components/table/DataTable";
import { userColumns } from "../../../components/table/features/users/columns/userColumns";
import { UsersFilters } from "../../../components/table/features/users/components/UsersFilters";
import { RowSelectionState } from "@tanstack/react-table";
import { useAppPagination } from "../../../hooks/useAppPagination";
import { HeadingToolbar } from "../../../components/table/toolbars/HeadingToolbar";
import useUsersFetch, {
  AdminUser,
} from "../../../hooks/features/admin/users/useUsersFetch";
import SomethingWentWrong from "../../../components/SomethingWentWrong";

export default function AdminUsersPage() {
  const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
  const pagination = useAppPagination();

  const { data, loading, error, isError } = useUsersFetch(pagination);

  const fetchedUsers = data?.users ?? [];
  const paginationInfo = data?.pagination;

  return (
    <section className="w-full p-4 pt-6 2xl:pt-8 2xl:p-8">
      {isError ? (
        <SomethingWentWrong
          variant="section"
          title="Unable to load users"
          description="The users table failed to load. Please try again."
          onRetry={() => pagination.patch({})}
          buttonText=""
        />
      ) : (
        <DataTable<AdminUser>
          data={fetchedUsers}
          loading={loading}
          columns={userColumns}
          appearance="default"
          size="md"
          getRowId={(user) => user.email}
          rowSelection={rowSelection}
          sorting={pagination.sortingConfig}
          onRowSelectionChange={setRowSelection}
          onSelectedRowsChange={(rows) => {
            // console.log("Selected users:", rows);
          }}
          toolbar={
            <HeadingToolbar
              title="Users"
              subTitle={`${fetchedUsers.length} User(s) listed`}
              titleClassName=""
              subTitleClassName=""
            />
          }
          filters={
            <UsersFilters
              value={pagination.params.searchQuery}
              onSearch={(value) => {
                pagination.patch({
                  searchQuery: value,
                });
              }}
            />
          }
          classNames={{
            root: "",
            toolbar: "flex items-center gap-3",
            filters: "flex items-center gap-2",
            table: "min-w-full",
            tableThead: "bg-slate-100 border-t-2 border-slate-400  relative",
            tableTheadRow: "whitespace-nowrap",
            tableTheadCell:
              "px-3 py-2 2xl:p-3 text-left font-body text-sm 2xl:text-base font-medium text-heading relative",
            tableTbody: "border-t border-slate-300/50 relative",
            tableTbodyRow: `
              hover:bg-link-1/10 transition-colors
              [&>td]:border-b [&>td]:border-gray-200
            `,
            tableTbodyCell:
              "py-2 px-3 font-body text-[13px] 2xl:text-sm text-table-text relative",
            pagination: "",
          }}
          pagination={{
            controller: pagination,
            pageCount: paginationInfo?.totalPages,
            totalItems: paginationInfo?.total,
          }}
        />
      )}
    </section>
  );
}
