"use client";
import {
  ExclamationIcon,
  EyeIcon,
  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 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 { formatPhoneNumber, getPaginatedRowNumber } from "@/utils/shared";
import { Tooltip } from "react-tooltip";
import CompanyListFilters from "./CompanyListFilters";
import { useCompanyListPresenter } from "./useCompanyListPresenter";

const CURRENCY_META: Record<string, { symbol: string; label: string }> = {
  USD: { symbol: "$", label: "US Dollar" },
  EUR: { symbol: "€", label: "Euro" },
  GBP: { symbol: "£", label: "British Pound" },
  JPY: { symbol: "¥", label: "Japanese Yen" },
  CAD: { symbol: "C$", label: "Canadian Dollar" },
  AUD: { symbol: "A$", label: "Australian Dollar" },
  CHF: { symbol: "₣", label: "Swiss Franc" },
  CNY: { symbol: "¥", label: "Chinese Yuan" },
  INR: { symbol: "₹", label: "Indian Rupee" },
  BRL: { symbol: "R$", label: "Brazilian Real" },
};

const LANGUAGE_META: Record<string, { flag: string; label: string }> = {
  en: { flag: "🇺🇸", label: "English" },
  ar: { flag: "🇦🇪", label: "Arabic" },
  fr: { flag: "🇫🇷", label: "French" },
  es: { flag: "🇪🇸", label: "Spanish" },
  de: { flag: "🇩🇪", label: "German" },
  zh: { flag: "🇨🇳", label: "Chinese" },
  ja: { flag: "🇯🇵", label: "Japanese" },
  ko: { flag: "🇰🇷", label: "Korean" },
};

const CompaniesTable = () => {
  const {
    isPending,
    pathName,
    columns,
    columnSortKeys,
    columnDefaultOrder,
    sortBy,
    sortOrder,
    handleSortChange,
    allCompanies,
    setIsModalOpen,
    router,
    isModalOpen,
    setCurrentCompany,
    onConfirmDelete,
    modalConfig,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    metadata,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
  } = useCompanyListPresenter();
  const companies = allCompanies.filter(
    (c): c is NonNullable<typeof c> => c != null,
  );
  return (
    <ListWrapper>
      <ListHeader hasFilter={false} createButtonText="Create Company" />
      <CompanyListFilters
        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>
          <TableHeader>
            <TableRow>
              {columns.map((col) => {
                const sortKey = columnSortKeys[col];
                return (
                  <TableHead
                    colSpan={100}
                    className="text-start 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={companies}
                columns={columns}
                emptyMessage="No companies were found"
                isLoading={false}
              >
                {companies.map((company, index) => (
                  <TableRow
                    key={company.id}
                    className="odd:bg-gray-2 dark:odd:bg-gray-7"
                  >
                    <TableCell className="text-start" colSpan={100}>
                      {getPaginatedRowNumber({
                        index,
                        page: metadata?.page,
                        limit: metadata?.limit,
                      })}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {company.name}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {company.email}
                    </TableCell>
                    <TableCell className="w-full text-start" colSpan={100}>
                      {formatPhoneNumber(company.phone)}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {company.address.country}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {company.address.state}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {(() => {
                        const code = company.language?.toLowerCase?.() ?? "";
                        const meta = LANGUAGE_META[code];
                        if (!meta) {
                          return (
                            <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">
                              —
                            </span>
                          );
                        }
                        return (
                          <span
                            data-tooltip-id={`lang-${company.id}`}
                            data-tooltip-content={meta.label}
                            className="inline-flex items-center gap-1.5 rounded-full border border-indigo-500/20 bg-indigo-500/10 px-2.5 py-1 text-xs font-semibold uppercase tracking-wide text-indigo-600 transition-colors hover:bg-indigo-500/20 dark:border-indigo-400/30 dark:bg-indigo-400/15 dark:text-indigo-200"
                          >
                            <span className="text-sm leading-none">
                              {meta.flag}
                            </span>
                            {code}
                            <Tooltip
                              {..._TooltipDefaultParams({
                                id: `lang-${company.id}`,
                              })}
                            />
                          </span>
                        );
                      })()}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {(() => {
                        const code = company.currency?.toUpperCase?.() ?? "";
                        const meta = CURRENCY_META[code];
                        if (!meta) {
                          return (
                            <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">
                              —
                            </span>
                          );
                        }
                        return (
                          <span
                            data-tooltip-id={`currency-${company.id}`}
                            data-tooltip-content={meta.label}
                            className="inline-flex items-center gap-1.5 rounded-full border border-emerald-500/20 bg-emerald-500/10 px-2.5 py-1 text-xs font-semibold tracking-wide text-emerald-600 transition-colors hover:bg-emerald-500/20 dark:border-emerald-400/30 dark:bg-emerald-400/15 dark:text-emerald-200"
                          >
                            <span className="flex h-4 w-4 items-center justify-center rounded-full bg-emerald-500/20 text-[10px] font-bold leading-none dark:bg-emerald-400/25">
                              {meta.symbol}
                            </span>
                            {code}
                            <Tooltip
                              {..._TooltipDefaultParams({
                                id: `currency-${company.id}`,
                              })}
                            />
                          </span>
                        );
                      })()}
                    </TableCell>
                    <TableCell className="text-start" colSpan={100}>
                      {company.employee_count}
                    </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={() => {
                            setCurrentCompany(company);
                            setIsModalOpen(true);
                          }}
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "delete" })} />
                          <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/${company.id}`)
                          }
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "edit" })} />
                          <span className="sr-only">Edit Company </span>
                          <PencilSquareIcon />
                        </button>
                        <button
                          data-tooltip-id="details"
                          data-tooltip-content="Details"
                          data-tooltip-place="top"
                          onClick={() => {
                            router.push(`${pathName}/details/${company.id}`);
                          }}
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "details" })} />
                          <EyeIcon />
                        </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/${company.id}`);
                          }}
                        >
                          <Tooltip {..._TooltipDefaultParams({ id: "feedback" })} />
                          <ExclamationIcon />
                        </button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </EmptyListWrapper>
            </TableBody>
          )}
        </Table>
        </TableSortProvider>
      </div>
      {isModalOpen && (
        <ConfirmationModal
          isOpen={isModalOpen}
          title={modalConfig.title || "Confirm"}
          message={modalConfig.message || "Are you sure?"}
          variant={modalConfig.variant || "default"}
          size={modalConfig.size || "md"}
          confirmText={modalConfig.confirmText ?? "Confirm"}
          cancelText={modalConfig.cancelText ?? "Cancel"}
          onConfirm={() => {
            onConfirmDelete();
          }}
          onCancel={() => setIsModalOpen(false)}
        />
      )}
      <IsVisible condition={shouldShowPagination}>
        <Pagination
          currentPage={pagination.currentPage}
          totalPages={pagination.totalPages}
          onPageChange={handlePaginationChange}
        />
      </IsVisible>
    </ListWrapper>
  );
};

export default CompaniesTable;
