import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import MyApprovalColumns from "./myApprovalColumns";
import Loader from "@/record-management/components/Loader/loader";
import {
  useMyApprovals,
  useMyProcessedApprovals,
} from "../../hooks/useApprovalTasks";
import { ApprovalRecordQueryParams } from "@/record-management/services/api/approvalService";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useEffect, useMemo, useState } from "react";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useLocalizedName } from "@/shared/common/localizedName";
import { cleanFilterParams, FilterParams } from "@/shared/utils/filterParams";

interface Props {
  status: "approve" | "reject" | "send_back" | "send_to_ro" | "active" | "all";
  filters: Partial<FilterParams>;
  liveSearch?: { key: string; value: string } | null;
}

export default function MyApprovalsTable({
  status,
  filters,
  liveSearch,
}: Props) {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { userDetails } = useAuthUser();
  const localizedName = useLocalizedName();
  const [searchParams, setSearchParams] = useSearchParams();
  const urlPage = Number(searchParams.get("page") || 1);
  const [pageIndex, setPageIndex] = useState(urlPage - 1);
  const pageSize = 10;

  /* build params */
  const filterParams = useMemo(() => {
    const baseParams: ApprovalRecordQueryParams = {
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "createdAt:DESC",
      ...(status &&
        status !== "active" &&
        status !== "all" && { action: status }),
      ...filters,
    };

    const cleaned = cleanFilterParams(baseParams) as ApprovalRecordQueryParams;

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

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

  const { data, isLoading, isError, refetch } =
    useMyProcessedApprovals(filterParams);
  const isDelegated = userDetails?.employee?.some((emp) =>
    emp.positions.some((pos) => pos.hasDelegated),
  );
  const totalPages = data?.count ? Math.ceil(data?.count / pageSize) : 1;
  useEffect(() => {
    if (!data?.count) 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, data?.count]);
  const handlePageChange = () => {
    const newPage = pageIndex + 1;

    setPageIndex(newPage);

    setSearchParams((prev) => {
      prev.set("page", 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.Error loading records.")}
        </p>
      </div>
    );
  }

  return (
    <AdvancedTable
      columns={MyApprovalColumns(navigate, localizedName, pageIndex + 1)}
      data={data?.items || []}
      tableName="My Approval Records"
      toolBarPosition="right"
      itemCount={data?.count || 0}
      pageIndex={pageIndex}
      onPageChange={setPageIndex}
      nextFunction={handlePageChange}
      prevFunction={() => setPageIndex(Math.max(0, pageIndex - 1))}
      refresh={refetch}
      initialColumnVisibility={{
        Receiver: false,
      }}
    />
  );
}
