"use client";
import {
  ExclamationIcon,
  KeyIcon,
  PencilSquareIcon,
  TrashIcon,
} from "@/assets/icons";
import { Building } from "@/components/Layouts/sidebar/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 { _TooltipDefaultParams } from "@/constants/tooltip";
import { getPaginatedRowNumber, unixToDate } from "@/utils/shared";
import { toast } from "react-toastify";
import { Tooltip } from "react-tooltip";
import AssignToCompanyModalContent from "./AssignToCompanyModalContent";
import CustomerListFilters from "./CustomerListFilters";
import useCustomerListPresenter from "./useCustomerListPresenter";

const CustomersTable = () => {
  const {
    isPending,
    pathName,
    router,
    columns,
    columnSortKeys,
    columnDefaultOrder,
    sortBy,
    sortOrder,
    handleSortChange,
    allCustomers,
    metadata,
    isModalOpen,
    assignSelectedCompanies,
    selectedCompanies,
    currentCustomer,
    setSelectedCompanies,
    setIsModalOpen,
    onConfirmDelete,
    setCurrentCustomer,
    isAssignCompanyModalOpen,
    setIsAssignCompanyModalOpen,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    assignCompanyCompaniesQuery,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
    isResetPasswordModalOpen,
    closeResetPasswordModal,
    openResetPasswordModalForCustomer,
    generatedPassword,
    isResettingPassword,
    companyItems,
    onCompanySearch,
    onCompanyLoadMore,
    companyHasMore,
    companyIsLoading,
    companyIsLoadingMore,
  } = useCustomerListPresenter();

  return (
    <ListWrapper>
      <ListHeader hasFilter={false} createButtonText="Create Customer" />
      <CustomerListFilters
        setValue={setFilterValue}
        filterRegister={filterRegister}
        handleFilterSubmit={handleFilterSubmit}
        isMutating={isMutating as number}
        search={search}
        watch={watch}
        onClearAll={clearAllFilters}
        companyItems={companyItems}
        onCompanySearch={onCompanySearch}
        onCompanyLoadMore={onCompanyLoadMore}
        companyHasMore={companyHasMore}
        companyIsLoading={companyIsLoading}
        companyIsLoadingMore={companyIsLoadingMore}
      />
      <div ref={tableSectionRef}>
        <TableSortProvider
          sortKey={sortBy}
          sortOrder={sortOrder}
          onSortChange={handleSortChange}
        >
        <Table>
          <TableHeader>
            <TableRow>
              {columns.map((col) => {
                const sortKey = columnSortKeys[col];
                return (
                  <TableHead
                    colSpan={100}
                    className="text-start font-extrabold uppercase"
                    key={col}
                    sortable={Boolean(sortKey)}
                    sortKey={sortKey}
                    defaultSortOrder={columnDefaultOrder[col]}
                  >
                    {col}
                  </TableHead>
                );
              })}
            </TableRow>
          </TableHeader>
          {isPending ? (
            <TableSkeleton ref={skeletonTbodyRef} column={columns.length} />
          ) : (
            <TableBody ref={dataTbodyRef}>
              <EmptyListWrapper
                list={allCustomers ?? []}
                columns={columns}
                emptyMessage="No Customers were found"
                isLoading={false}
              >
                {allCustomers?.map((customer, index) => (
                  <TableRow key={customer?.id ?? index}>
                    <TableCell colSpan={100}>
                      {getPaginatedRowNumber({
                        index,
                        page: metadata?.page,
                        limit: metadata?.limit,
                      })}
                    </TableCell>
                    <TableCell colSpan={100}>{customer?.full_name}</TableCell>
                    <TableCell colSpan={100}>{customer?.email}</TableCell>
                    <TableCell colSpan={100}>
                      {unixToDate({ unix: customer?.created_at, hasTime: true })}
                    </TableCell>

                    <TableCell colSpan={100} className="uppercase">
                      {customer?.type}
                    </TableCell>
                    <TableCell colSpan={100}>
                      <Status status={customer?.status}>{customer?.status}</Status>
                    </TableCell>
                    <TableCell colSpan={100}>
                      {customer?.companies?.length ? (
                        <div className="flex max-w-[260px] flex-wrap items-center gap-1.5">
                          {customer.companies.slice(0, 2).map((c) => (
                            <span
                              key={c.id}
                              data-tooltip-id={`company-${customer.id}-${c.id}`}
                              data-tooltip-content={c.name}
                              className="inline-flex max-w-[140px] items-center gap-1.5 rounded-full border border-primary/20 bg-primary/10 px-2.5 py-1 text-xs font-medium text-primary transition-colors hover:bg-primary/20 dark:border-primary/30 dark:bg-primary/20 dark:text-white"
                            >
                              <Building className="h-3 w-3 shrink-0" />
                              <span className="truncate">{c.name}</span>
                              <Tooltip
                                {..._TooltipDefaultParams({
                                  id: `company-${customer.id}-${c.id}`,
                                })}
                              />
                            </span>
                          ))}
                          {customer.companies.length > 2 && (
                            <>
                              <span
                                data-tooltip-id={`company-more-${customer.id}`}
                                data-tooltip-content={customer.companies
                                  .slice(2)
                                  .map((c) => c.name)
                                  .join(", ")}
                                className="inline-flex cursor-default items-center rounded-full border border-stroke bg-gray-2 px-2.5 py-1 text-xs font-semibold text-dark transition-colors hover:bg-gray-3 dark:border-dark-3 dark:bg-dark-3 dark:text-white"
                              >
                                +{customer.companies.length - 2}
                              </span>
                              <Tooltip
                                {..._TooltipDefaultParams({
                                  id: `company-more-${customer.id}`,
                                })}
                              />
                            </>
                          )}
                        </div>
                      ) : (
                        <span className="inline-flex items-center gap-1 rounded-full border border-dashed border-stroke px-2.5 py-1 text-xs font-medium text-dark-5 dark:border-dark-3 dark:text-dark-6">
                          None
                        </span>
                      )}
                    </TableCell>
                    <TableCell colSpan={100} className="uppercase">
                      {customer?.role ?? "-"}
                    </TableCell>
                    <TableCell className="text-start xl:pr-7.5">
                      <div className="flex items-center justify-start gap-x-3.5">
                        <button
                          data-tooltip-id="delete"
                          data-tooltip-content="Delete"
                          data-tooltip-place="top"
                          className="hover:text-red-500"
                          onClick={() => {
                            setCurrentCustomer(customer);
                            setIsModalOpen(true);
                          }}
                        >
                          <span className="sr-only">Delete Company </span>
                          <TrashIcon />
                        </button>
                        <button
                          data-tooltip-id="edit"
                          data-tooltip-content="Edit"
                          data-tooltip-place="top"
                          className="hover:text-primary"
                          onClick={() =>
                            router.push(`${pathName}/edit/${customer.id}`)
                          }
                        >
                          <span className="sr-only">Edit Company </span>
                          <PencilSquareIcon />
                        </button>
                        <button
                          data-tooltip-id="assign-company"
                          data-tooltip-content="Assign to company"
                          data-tooltip-place="top"
                          className="hover:text-green-dark"
                          onClick={() => {
                            setCurrentCustomer(customer);
                            setIsAssignCompanyModalOpen(true);
                            setSelectedCompanies({
                              companies:
                                customer?.companies?.map((c) => c.id) ?? [],
                            });
                          }}
                        >
                          <span className="sr-only">Assign To Company </span>
                          <Building />
                        </button>
                        <button
                          type="button"
                          data-tooltip-id="reset-password"
                          data-tooltip-content="Reset password"
                          data-tooltip-place="top"
                          className="hover:text-primary"
                          onClick={() =>
                            openResetPasswordModalForCustomer(customer)
                          }
                        >
                          <span className="sr-only">
                            Reset Customer Password
                          </span>
                          <KeyIcon />
                        </button>
                        <button
                          data-tooltip-id="feedback"
                          data-tooltip-content="Feedback"
                          data-tooltip-place="top"
                          className="text-gray-40 rounded-full bg-gray-dark bg-opacity-5 hover:text-green-dark dark:bg-gray dark:bg-opacity-5"
                          onClick={() => {
                            router.push(`${pathName}/feedback/${customer.id}`);
                          }}
                        >
                          <ExclamationIcon />
                        </button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </EmptyListWrapper>
            </TableBody>
          )}
        </Table>
        </TableSortProvider>
      </div>
      <IsVisible condition={shouldShowPagination}>
        <Pagination
          currentPage={pagination.currentPage}
          totalPages={pagination.totalPages}
          onPageChange={handlePaginationChange}
        />
      </IsVisible>
      <div className="w-1/12">
        <Modal
          classNames="w-full xl:w-1/2"
          onConfirm={() => {
            if (
              !currentCustomer ||
              !selectedCompanies?.companies?.length
            ) {
              toast.error("Please select at least one company");
              return;
            }
            assignSelectedCompanies({
              credentials: { companies: selectedCompanies.companies },
              id: currentCustomer?.id ?? "",
            });
          }}
          isOpen={isAssignCompanyModalOpen}
          onClose={() => setIsAssignCompanyModalOpen(false)}
        >
          <AssignToCompanyModalContent
            companiesQuery={assignCompanyCompaniesQuery}
            setCompanies={setSelectedCompanies}
            defaultValues={selectedCompanies}
          />
        </Modal>
      </div>
      <Modal
        isOpen={isResetPasswordModalOpen}
        onClose={closeResetPasswordModal}
        showButtons={false}
      >
        <ResetPasswordModalContent
          subjectName={currentCustomer?.full_name}
          subjectLabel="customer"
          password={generatedPassword}
          isLoading={isResettingPassword}
          isOpen={isResetPasswordModalOpen}
        />
      </Modal>
      {isModalOpen && (
        <ConfirmationModal
          isOpen={isModalOpen}
          title={"Confirm"}
          message={"Are you sure?"}
          variant={"default"}
          size={"md"}
          confirmText={"Confirm"}
          cancelText={"Cancel"}
          onConfirm={() => {
            onConfirmDelete();
          }}
          onCancel={() => setIsModalOpen(false)}
        />
      )}
      <Tooltip {..._TooltipDefaultParams({ id: "delete" })} />
      <Tooltip {..._TooltipDefaultParams({ id: "edit" })} />
      <Tooltip {..._TooltipDefaultParams({ id: "assign-company" })} />
      <Tooltip {..._TooltipDefaultParams({ id: "reset-password" })} />
      <Tooltip {..._TooltipDefaultParams({ id: "feedback" })} />
    </ListWrapper>
  );
};

export default CustomersTable;
