"use client";
import { PencilSquareIcon, TrashIcon } 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 Status from "@/components/ui/Status";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import TableSkeleton from "@/components/ui/TableSkeleton";
import { _TooltipDefaultParams } from "@/constants/tooltip";
import { TInquiries } from "@/lib/api";
import {
  formatPhoneNumber,
  getPaginatedRowNumber,
  unixToDate,
} from "@/utils/shared";
import { Tooltip } from "react-tooltip";
import ChangeStatusForm from "./ChangeStatusForm";
import InquiriesListFilters from "./InquiriesListFilters";
import useInquiriesListPresenter from "./useInquiriesListPresenter";

const InquiriesTable = () => {
  const {
    columns,
    inquiries,
    allInquiries,
    isPending,
    currentInquiry,
    isDeleteModalOpen,
    isChangeStatusModalOpen,
    setCurrentInquiry,
    setIsDeleteModalOpen,
    setIsChangeStatusModalOpen,
    deleteInquiry,
    handleChangeStatus,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
  } = useInquiriesListPresenter();

  return (
    <ListWrapper>
      <ListHeader hasFilter={false} hasCreate={false} />
      <InquiriesListFilters
        setValue={setFilterValue}
        filterRegister={filterRegister}
        handleFilterSubmit={handleFilterSubmit}
        isMutating={isMutating as number}
        search={search}
        watch={watch}
        onClearAll={clearAllFilters}
      />
      <div ref={tableSectionRef}>
        <Table>
          <TableHeader>
            <TableRow className="border-none uppercase [&>th]:text-start">
              {columns.map((column: string) => (
                <TableHead key={column} colSpan={100}>
                  {column}
                </TableHead>
              ))}
            </TableRow>
          </TableHeader>
          {isPending ? (
            <TableSkeleton ref={skeletonTbodyRef} column={columns.length} />
          ) : (
            <TableBody ref={dataTbodyRef}>
              <EmptyListWrapper
                columns={columns}
                list={inquiries ?? []}
                emptyMessage="No Inquiries were found"
                isLoading={false}
              >
                {inquiries?.map((inquiry: TInquiries, index: number) => (
                  <TableRow key={inquiry?.id ?? index}>
                    <TableCell className="text-start" colSpan={100}>
                      {getPaginatedRowNumber({
                        index,
                        page: allInquiries?.meta?.page,
                        limit: allInquiries?.meta?.limit,
                      })}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {inquiry?.company_name}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {inquiry?.full_name}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {formatPhoneNumber(inquiry?.phone_number)}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      <Status status={inquiry?.status ?? "pending"}>
                        {inquiry?.status}
                      </Status>
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {unixToDate({ unix: inquiry.created_at, hasTime: true })}
                    </TableCell>
                    <TableCell className="text-start xl:pr-7.5">
                      <div className="flex items-center justify-start gap-x-3.5">
                        <button
                          type="button"
                          data-tooltip-id="change-status"
                          data-tooltip-content="Change Status"
                          data-tooltip-place="top"
                          className="hover:text-primary"
                          onClick={() => {
                            setCurrentInquiry(inquiry);
                            setIsChangeStatusModalOpen(true);
                          }}
                        >
                          <Tooltip
                            {..._TooltipDefaultParams({ id: "change-status" })}
                          />
                          <span className="sr-only">Change Status</span>
                          <PencilSquareIcon />
                        </button>
                        <button
                          type="button"
                          data-tooltip-id="delete"
                          data-tooltip-content="Delete"
                          data-tooltip-place="top"
                          className="hover:text-red-500"
                          onClick={() => {
                            setCurrentInquiry(inquiry);
                            setIsDeleteModalOpen(true);
                          }}
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "delete" })} />
                          <span className="sr-only">Delete Contact Us </span>
                          <TrashIcon />
                        </button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </EmptyListWrapper>
            </TableBody>
          )}
        </Table>
      </div>
      <Modal
        isOpen={isChangeStatusModalOpen}
        onClose={() => setIsChangeStatusModalOpen(false)}
        classNames="w-full xl:w-1/2"
        showButtons={false}
      >
        <div className="mb-4">
          <h3 className="text-xl font-semibold text-dark dark:text-white">
            Change Status - {currentInquiry?.full_name}
          </h3>
        </div>
        <ChangeStatusForm
          onSubmit={handleChangeStatus}
          onCancel={() => setIsChangeStatusModalOpen(false)}
          currentStatus={currentInquiry?.status ?? "pending"}
        />
      </Modal>
      <IsVisible condition={shouldShowPagination}>
        <Pagination
          currentPage={pagination.currentPage}
          totalPages={pagination.totalPages}
          onPageChange={handlePaginationChange}
        />
      </IsVisible>
      {isDeleteModalOpen && (
        <ConfirmationModal
          isOpen={isDeleteModalOpen}
          title={`Deleting ${currentInquiry?.full_name}`}
          message={`Are you sure?`}
          variant={"default"}
          size={"lg"}
          confirmText={"Delete"}
          cancelText={"Cancel"}
          onConfirm={() => {
            deleteInquiry();
          }}
          onCancel={() => setIsDeleteModalOpen(false)}
        />
      )}
    </ListWrapper>
  );
};

export default InquiriesTable;
