"use client";
import { PencilSquareIcon, TrashIcon } from "@/assets/icons";
import { Switch } from "@/components/FormElements/switch";
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 Pagination from "@/components/ui/pagination";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  TableSortProvider,
} from "@/components/ui/table";
import TableSkeleton from "@/components/ui/TableSkeleton";
import { _TooltipDefaultParams } from "@/constants/tooltip";
import { getPaginatedRowNumber, unixToDate } from "@/utils/shared";
import { startTransition } from "react";
import { Tooltip } from "react-tooltip";
import CompanyCategoryListFilters from "./CompanyCategoryListFilters";
import useCompanyCategoriesPresenter from "./useCompanyCategoriesPresenter";

const CompanyCategoriesTable = () => {
  const {
    optimisticCategories,
    addOptimisticPublished,
    isLoading,
    pathName,
    router,
    currentCategory,
    togglePublished,
    onConfirmDelete,
    setCurrentCategory,
    isModalOpen,
    setIsModalOpen,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    columns,
    columnSortKeys,
    columnDefaultOrder,
    sortBy,
    sortOrder,
    handleSortChange,
    isMutating,
    metadata,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
  } = useCompanyCategoriesPresenter();

  return (
    <ListWrapper data-cy="company-categories-page">
      <ListHeader
        hasFilter={false}
        createButtonText="Create Category"
        dataCyPrefix="company-categories"
      />
      <CompanyCategoryListFilters
        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="company-categories-table">
          <TableHeader>
            <TableRow className="border-none uppercase [&>th]:text-start">
              {columns.map((column) => {
                const sortKey = columnSortKeys[column];
                return (
                  <TableHead
                    key={column}
                    colSpan={100}
                    sortable={Boolean(sortKey)}
                    sortKey={sortKey}
                    defaultSortOrder={columnDefaultOrder[column]}
                  >
                    {column}
                  </TableHead>
                );
              })}
            </TableRow>
          </TableHeader>
          {isLoading ? (
            <TableSkeleton ref={skeletonTbodyRef} column={columns.length} />
          ) : (
            <TableBody ref={dataTbodyRef}>
              <EmptyListWrapper
                list={optimisticCategories}
                columns={columns}
                emptyMessage="No categories were found"
                isLoading={false}
              >
                {optimisticCategories.map((category, index) => (
                  <TableRow
                    key={category.id}
                    data-cy={`company-categories-table-row-${category.id}`}
                    className="odd:bg-gray-2 dark:odd:bg-gray-7"
                  >
                    <TableCell colSpan={100}>
                      {getPaginatedRowNumber({
                        index,
                        page: metadata?.page,
                        limit: metadata?.limit,
                      })}
                    </TableCell>
                    <TableCell colSpan={100}>{category.name}</TableCell>
                    <TableCell colSpan={100}>{category.description}</TableCell>
                    <TableCell colSpan={100}>
                      {unixToDate({ unix: category.created_at, hasTime: true })}
                    </TableCell>
                    <TableCell colSpan={100}>
                      <Switch
                        withIcon
                        dataCy={`company-categories-published-toggle-${category.id}`}
                        onToggle={() => {}}
                        onChange={() => {
                          const nextPublished = !category.published;
                          startTransition(async () => {
                            addOptimisticPublished({
                              id: category.id,
                              published: nextPublished,
                            });
                            try {
                              await togglePublished(category.id);
                            } catch {
                              // useOptimistic automatically reverts when the transition ends
                            }
                          });
                        }}
                        checked={category.published}
                      />
                    </TableCell>
                    <TableCell className="text-start xl:pr-7.5">
                      <div className="flex items-center justify-start gap-x-3.5">
                        <button
                          type="button"
                          data-cy={`company-categories-row-delete-${category.id}`}
                          data-tooltip-id="delete"
                          data-tooltip-content="Delete"
                          data-tooltip-place="top"
                          className="hover:text-red-500"
                          onClick={() => {
                            setCurrentCategory(category);
                            setIsModalOpen(true);
                          }}
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "delete" })} />
                          <span className="sr-only">Delete Admin </span>
                          <TrashIcon />
                        </button>
                        <button
                          type="button"
                          data-cy={`company-categories-row-edit-${category.id}`}
                          data-tooltip-id="edit"
                          data-tooltip-content="Edit"
                          data-tooltip-place="top"
                          className="hover:text-primary"
                          onClick={() =>
                            router.push(`${pathName}/edit/${category.id}`)
                          }
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "edit" })} />
                          <span className="sr-only">Edit Category</span>
                          <PencilSquareIcon />
                        </button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </EmptyListWrapper>
            </TableBody>
          )}
        </Table>
        </TableSortProvider>
      </div>
      {isModalOpen && (
        <ConfirmationModal
          isOpen={isModalOpen}
          title={`Deleting ${currentCategory?.name}`}
          message={`Are you sure?`}
          variant={"default"}
          size={"md"}
          confirmText={"Delete"}
          cancelText={"Cancel"}
          onConfirm={() => {
            onConfirmDelete();
          }}
          onCancel={() => setIsModalOpen(false)}
        />
      )}
      <IsVisible condition={shouldShowPagination}>
        <Pagination
          currentPage={pagination.currentPage}
          totalPages={pagination.totalPages}
          onPageChange={handlePaginationChange}
        />
      </IsVisible>
    </ListWrapper>
  );
};

export default CompanyCategoriesTable;
