"use client";

import {
  KeyIcon,
  PencilSquareIcon,
  TrashIcon,
  UserSettingIcon,
} from "@/assets/icons";
import EmptyListWrapper from "@/components/HOC/EmptyListWrapper";
import ConfirmationModal from "@/components/ui/ConfirmationModal";
import IsVisible from "@/components/ui/IsVisible";
import ListHeader from "@/components/ui/ListHeader";
import ListWrapper from "@/components/ui/ListWrapper";
import Modal from "@/components/ui/modal";
import Pagination from "@/components/ui/pagination";
import ResetPasswordModalContent from "@/components/ui/ResetPasswordModalContent";
import Status from "@/components/ui/Status";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  TableSortProvider,
} from "@/components/ui/table";
import TableSkeleton from "@/components/ui/TableSkeleton";
import { AdminStatus } from "@/constants/enums";
import { _TooltipDefaultParams } from "@/constants/tooltip";
import { Tooltip } from "react-tooltip";
import AdminListFilters from "./AdminListFilters";
import ChangeStatusModalContent from "./ChangeStatusModalContent";
import { useAdminsPresenter } from "./useAdminsPresenter";

const AdminsTable = () => {
  const {
    usersList,
    isPending,
    onConfirmDelete,
    isModalOpen,
    setIsModalOpen,
    isChangeStatusModalOpen,
    setIsChangeStatusModalOpen,
    columns,
    columnSortKeys,
    columnDefaultOrder,
    sortBy,
    sortOrder,
    handleSortChange,
    changeStatus,
    currentUser,
    setStatus,
    status,
    setFilterValue,
    handleFilterSubmit,
    search,
    filterRegister,
    isMutating,
    watch,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    getRowNumber,
    pagination,
    handlePaginationChange,
    navigateToEditAdmin,
    openDeleteModalForUser,
    openChangeStatusModalForUser,
    isResetPasswordModalOpen,
    closeResetPasswordModal,
    openResetPasswordModalForUser,
    generatedPassword,
    isResettingPassword,
  } = useAdminsPresenter();

  return (
    <ListWrapper data-cy="admins-page">
      <ListHeader
        hasFilter={false}
        createButtonText="Create Admin"
        dataCyPrefix="admins"
      />
      <AdminListFilters
        setValue={setFilterValue}
        filterRegister={filterRegister}
        handleFilterSubmit={handleFilterSubmit}
        isMutating={isMutating as number}
        search={search}
        watch={watch}
        onClearAll={clearAllFilters}
      />
      <div ref={tableSectionRef}>
        <TableSortProvider
          sortKey={sortBy}
          sortOrder={sortOrder}
          onSortChange={handleSortChange}
        >
        <Table data-cy="admins-table">
          <TableHeader>
            <TableRow className="border-none uppercase [&>th]:text-start">
              {columns.map((column, index) => {
                const sortKey = columnSortKeys[column];
                return (
                  <TableHead
                    key={column}
                    colSpan={100}
                    sortable={Boolean(sortKey)}
                    sortKey={sortKey}
                    defaultSortOrder={columnDefaultOrder[column]}
                    data-cy={`admins-table-header-${index}`}
                  >
                    {column}
                  </TableHead>
                );
              })}
            </TableRow>
          </TableHeader>

          {isPending ? (
            <TableSkeleton ref={skeletonTbodyRef} column={columns.length} />
          ) : (
            <TableBody ref={dataTbodyRef}>
              <EmptyListWrapper
                list={usersList}
                columns={columns}
                emptyMessage="No admins were found"
                isLoading={false}
              >
                {usersList.map((item, index) => (
                  <TableRow
                    key={item?.id || index}
                    className="odd:bg-gray-2 dark:odd:bg-gray-7"
                    data-cy={`admins-table-row-${item?.id ?? index}`}
                  >
                    <TableCell className="text-start" colSpan={100} data-cy="admins-row-number">
                      {getRowNumber(index)}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100} data-cy="admins-row-full-name">
                      {item?.full_name}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100} data-cy="admins-row-email">
                      {item?.email}
                    </TableCell>

                    <TableCell className="text-start" colSpan={100} data-cy="admins-row-username">
                      {item?.username}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100} data-cy="admins-row-status">
                      <Status status={item?.status ?? ""}>{item?.status}</Status>
                    </TableCell>

                    <TableCell className="text-start xl:pr-7.5" data-cy="admins-row-actions">
                      <div className="flex items-center justify-start gap-x-3.5">
                        <button
                          type="button"
                          data-tooltip-id="delete"
                          data-tooltip-content="Delete"
                          data-tooltip-place="top"
                          className="hover:text-red-500"
                          data-cy={`admins-row-delete-${item?.id ?? index}`}
                          onClick={() => openDeleteModalForUser(item)}
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "delete" })} />
                          <span className="sr-only">Delete Admin </span>
                          <TrashIcon />
                        </button>
                        <button
                          type="button"
                          data-tooltip-id="change-status"
                          data-tooltip-content="Change status"
                          data-tooltip-place="top"
                          className="hover:text-yellow-dark"
                          data-cy={`admins-row-manage-status-${item?.id ?? index}`}
                          onClick={() => openChangeStatusModalForUser(item)}
                        >
                          <Tooltip
                            {..._TooltipDefaultParams({ id: "change-status" })}
                          />
                          <span className="sr-only">Change Admin Status</span>
                          <UserSettingIcon />
                        </button>
                        <button
                          type="button"
                          data-tooltip-id="reset-password"
                          data-tooltip-content="Reset password"
                          data-tooltip-place="top"
                          className="hover:text-primary"
                          data-cy={`admins-row-reset-password-${item?.id ?? index}`}
                          onClick={() => openResetPasswordModalForUser(item)}
                        >
                          <Tooltip
                            {..._TooltipDefaultParams({
                              id: "reset-password",
                            })}
                          />
                          <span className="sr-only">Reset Admin Password</span>
                          <KeyIcon />
                        </button>
                        <button
                          type="button"
                          data-tooltip-id="edit"
                          data-tooltip-content="Edit"
                          data-tooltip-place="top"
                          className="hover:text-primary"
                          data-cy={`admins-row-edit-${item?.id ?? index}`}
                          onClick={() => navigateToEditAdmin(item.id)}
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "edit" })} />
                          <span className="sr-only">Edit Admin </span>
                          <PencilSquareIcon />
                        </button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </EmptyListWrapper>
            </TableBody>
          )}
        </Table>
        </TableSortProvider>
      </div>
      <Modal
        isOpen={isChangeStatusModalOpen}
        onClose={() => setIsChangeStatusModalOpen(false)}
        onConfirm={() => {
          changeStatus({ id: currentUser?.id!, credentials: { status } });
        }}
        confirmText="Save"
        cancelText="Cancel"
      >
        <ChangeStatusModalContent
          status={currentUser?.status as AdminStatus}
          setStatus={setStatus}
        />
      </Modal>

      <Modal
        isOpen={isResetPasswordModalOpen}
        onClose={closeResetPasswordModal}
        showButtons={false}
      >
        <ResetPasswordModalContent
          subjectName={currentUser?.full_name}
          subjectLabel="admin"
          password={generatedPassword}
          isLoading={isResettingPassword}
          isOpen={isResetPasswordModalOpen}
        />
      </Modal>

      {isModalOpen && (
        <ConfirmationModal
          isOpen={isModalOpen}
          title={"Confirm"}
          message={"Are you sure?"}
          variant={"warning"}
          size={"md"}
          confirmText={"Confirm"}
          cancelText={"Cancel"}
          onConfirm={() => {
            onConfirmDelete();
          }}
          onCancel={() => setIsModalOpen(false)}
        />
      )}
      <IsVisible condition={shouldShowPagination}>
        <Pagination
          currentPage={pagination.currentPage}
          totalPages={pagination.totalPages}
          onPageChange={handlePaginationChange}
        />
      </IsVisible>
    </ListWrapper>
  );
};

export default AdminsTable;
