import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import ApproveRecordsColumns from "./approveRecordsColumns";
import Loader from "@/record-management/components/Loader/loader";
import { useApprovalTasks } from "../../hooks/useApprovalTasks";
import { useTranslation } from "react-i18next";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import { useLocalizedName } from "@/shared/common/localizedName";
import ApproveRecordPage from "../approve/approveRecordPage";
import { PendingApprovalDto } from "@/record-management/dto/approval/approvalRecordsDto";
import { ApprovalRecordQueryParams } from "@/record-management/services/api/approvalService";
import { cleanFilterParams, FilterParams } from "@/shared/utils/filterParams";
interface Props {
  filters: Partial<FilterParams>;
  onReview?: boolean;
  liveSearch?: { key: string; value: string } | null;
}

export default function TasksTable({ onReview, filters, liveSearch }: Props) {
  const { userDetails } = useAuthUser();
  const localizedName = useLocalizedName();
  const unitId = userDetails?.employee?.[0]?.unitId ?? "";
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: !!unitId,
  });
  const canRecordBeEditedOnWorkflow =
    unitConfigData?.data?.items?.[0]?.canRecordBeEditedOnWorkflow ?? false;
  const [searchParams, setSearchParams] = useSearchParams();
  const urlPage = Number(searchParams.get("pageT") || 1);
  const [pageIndex, setPageIndex] = useState(urlPage - 1);
  const pageSize = 10;

  const filterParams = useMemo(() => {
    const { fromCreatedAt, toCreatedAt, ...restFilters } = filters;
    const baseParams = {
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "record.updatedAt:DESC",
      onReview,
      ...restFilters,
      fromUpdatedAt:
        typeof fromCreatedAt === "string" ? fromCreatedAt : undefined,
      toUpdatedAt: typeof toCreatedAt === "string" ? toCreatedAt : undefined,
    };

    const cleaned = cleanFilterParams(baseParams) as ApprovalRecordQueryParams;

    return liveSearch
      ? { ...cleaned, [liveSearch.key]: liveSearch.value }
      : cleaned;
  }, [pageIndex, filters, onReview, liveSearch]);

  // Snap back to page 1 whenever any filter changes
  useEffect(() => {
    setPageIndex(0);
    setSearchParams(
      (prev) => {
        const params = new URLSearchParams(prev);
        params.set("pageT", "1");
        return params;
      },
      { replace: true },
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, onReview]);

  const { approvalRecords, approvalCount, isLoading, isError, refetch } =
    useApprovalTasks(filterParams);
  const { t } = useTranslation();
  const isDelegated = userDetails?.employee?.some((emp) =>
    emp.positions.some((pos) => pos.hasDelegated),
  );
  const totalPages = approvalCount ? Math.ceil(approvalCount / pageSize) : 1;
  useEffect(() => {
    if (!approvalCount) return; // wait until data is loaded

    let newPage = pageIndex + 1;

    if (newPage > totalPages) {
      newPage = 1;
      setPageIndex(0);
    }

    setSearchParams((prev) => {
      const params = new URLSearchParams(prev);
      params.set("page", newPage.toString());
      return params;
    });
  }, [pageIndex, totalPages, setSearchParams, approvalCount]);
  const handlePageChange = () => {
    const newPage = pageIndex + 1;

    setPageIndex(newPage);

    setSearchParams((prev) => {
      prev.set("pageT", newPage.toString());
      return prev;
    });
  };

  if (isLoading) return <Loader />;
  if (isError && isDelegated) {
    return (
      <div className="flex flex-col items-center justify-center h-full p-6 bg-red-50 border border-red-200 rounded-lg">
        <h2 className="text-xl font-semibold text-red-700">
          {t("msg.accessDenied")}
        </h2>
        <p className="mt-2 text-lg text-red-600 text-center max-w-sm">
          {t("userIncoming.errDelegation")}
        </p>
      </div>
    );
  }
  if (isError) {
    return (
      <div className="flex flex-col items-center justify-center h-full p-6 bg-red-50 border border-red-200 rounded-lg">
        <h2 className="text-xl font-semibold text-red-700">{t("msg.error")}</h2>
        <p className="mt-2 text-lg text-red-600 text-center max-w-sm">
          {t("userRecord.errorLoadingRecords.")}
        </p>
      </div>
    );
  }
  // Lift the Approve modal state to the table so it survives row remounts.
  // Each row's <ApproveRecordsActions> can be torn down and rebuilt by
  // TanStack Table without affecting the modal that's already open.
  const [approveTarget, setApproveTarget] = useState<PendingApprovalDto | null>(
    null,
  );
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  const handleApproveClick = useCallback((row: PendingApprovalDto) => {
    setApproveTarget(row);
  }, []);

  const handleApproveClose = useCallback(() => {
    setApproveTarget(null);
    refetch();
    queryClient.invalidateQueries({ queryKey: ["approvalRecord"] });
    queryClient.invalidateQueries({ queryKey: ["pendingRecords"] });
    queryClient.invalidateQueries({ queryKey: ["dashbordReport"] });
  }, [refetch, queryClient]);

  const handleApproveSuccess = useCallback(() => {
    setApproveTarget(null);
    navigate(`/record-management/approval`);
  }, [navigate]);

  // Memoize columns: recreating this array on every render hands a new
  // reference to AdvancedTable, which forces TanStack Table to rebuild
  // every cell. That caused all <ApproveRecordsActions> rows to unmount.
  const columns = useMemo(
    () =>
      ApproveRecordsColumns(
        refetch,
        localizedName,
        pageIndex + 1,
        canRecordBeEditedOnWorkflow,
        handleApproveClick,
      ),
    [
      refetch,
      localizedName,
      pageIndex,
      canRecordBeEditedOnWorkflow,
      handleApproveClick,
    ],
  );

  return (
    <>
      <AdvancedTable
        columns={columns}
        data={approvalRecords || []}
        tableName="Pending Approval Tasks"
        toolBarPosition="right"
        itemCount={approvalCount || 0}
        pageIndex={pageIndex}
        onPageChange={setPageIndex}
        nextFunction={handlePageChange}
        prevFunction={() => setPageIndex(Math.max(0, pageIndex - 1))}
        refresh={refetch}
        initialColumnVisibility={{
          Receiver: false,
        }}
      />
      {approveTarget && (
        <ApproveRecordPage
          recordId={approveTarget.record?.id ?? ""}
          recordTypeKey={approveTarget.record?.recordTypeKey}
          referenceNumber={approveTarget.record?.referenceNumber ?? ""}
          isWithTeamSignature={approveTarget.record?.isWithTeamSignature}
          open={true}
          onSuccess={handleApproveSuccess}
          onClose={handleApproveClose}
          preferredLanguage={
            approveTarget.record?.preferredLanguage ??
            (approveTarget as any).preferredLanguage
          }
        />
      )}
    </>
  );
}
