import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";

import Loader from "@/record-management/components/Loader/loader";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import { cleanFilterParams, FilterParams } from "@/shared/utils/filterParams";
import { PendingRecordsColumns } from "./pendingRecordColumns";
import { usePendingRecords } from "../hooks/usePendingRecords";

const PendingRecords = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const urlPage = Number(searchParams.get("page") || 1);
  const [pageIndex, setPageIndex] = useState(urlPage - 1);
  const pageSize = 10;
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const { userDetails } = useAuthUser();
  const combinedFilters = useCombinedFilters<FilterParams>();
  const [liveSearch, setLiveSearch] = useState<{
    key: string;
    value: string;
  } | null>(null); // ← add
  const unitId = userDetails?.employee?.[0]?.unitId ?? "";
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: !!unitId,
  });
  const canROReturn = unitConfigData?.data?.items?.[0]?.canROReturn ?? false;

  const filterFields = useMemo<CombinedFilterField[]>(
    () => [
      { key: "letterName", label: t("viewDetail.fileName"), type: "text" },
      { key: "receiver", label: t("userRecord.To"), type: "text" },
      {
        key: "sendingPosition",
        label: t("userIncoming.Sending Department"),
        type: "text",
      },
      { key: "subject", label: t("userRecord.Subject"), type: "text" },
      {
        key: "approvedAt",
        label: t("userRecord.Date"),
        type: "dateRange",
        fromKey: "fromApprovedAt",
        toKey: "toApprovedAt",
      },
    ],
    [t],
  );

  useEffect(() => {
    setPageIndex(urlPage - 1);
  }, [combinedFilters.filters, urlPage]);

  const baseParams = useMemo(() => {
    const cleaned = cleanFilterParams({
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "updatedAt:DESC",
      ...combinedFilters.filters,
    });

    // Apply live search AFTER cleanFilterParams so it doesn't get stripped
    return liveSearch
      ? { ...cleaned, [liveSearch.key]: liveSearch.value }
      : cleaned;
  }, [combinedFilters.filters, pageIndex, liveSearch]);

  const { isLoading, isError, records, refetch, pendingRecordsCount } =
    usePendingRecords(baseParams);

  const handlePageChange = (newPage: number) => {
    setPageIndex(newPage);
  };

  const handlePageChangeInc = () => {
    const newPage = pageIndex + 1;
    setPageIndex(newPage);

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

  const handleLiveSearch = (key: string, value: string) => {
    if (!key || !value) {
      setLiveSearch(null);
      return;
    }
    setLiveSearch({ key, value });
    setPageIndex(0);
  };

  const totalPages = pendingRecordsCount
    ? Math.ceil(pendingRecordsCount / pageSize)
    : 1;

  useEffect(() => {
    if (!pendingRecordsCount) return;

    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, pendingRecordsCount]);

  return (
    <div className="w-full mx-auto py-6 space-y-6">
      <div className="flex flex-col sm:flex-row justify-between items-start w-full gap-4 mb-4">
        <h4 className="text-xl font-medium">{t("userRecord.Letters")}</h4>

        <CombinedFilterBar
          fields={filterFields}
          filters={combinedFilters.filters}
          setFilter={combinedFilters.setFilter}
          setFilters={combinedFilters.setFilters}
          removeFilter={combinedFilters.removeFilter}
          removeFilters={combinedFilters.removeFilters}
          onFilterChange={() => setPageIndex(0)}
          onLiveSearch={handleLiveSearch}
        />
      </div>

      {isLoading && <Loader />}
      {isError && <p>{t("userRecord.Error loading records.")}</p>}
      {!isLoading && !isError && (
        <AdvancedTable
          columns={PendingRecordsColumns(
            localizedName,
            pageIndex + 1,
            canROReturn,
          )}
          data={records || []}
          tableName="Pending Records"
          toolBarPosition="right"
          hideToolbarFilter
          extraToolbar={<div className="flex gap-2"></div>}
          itemCount={pendingRecordsCount || 2}
          pageIndex={pageIndex}
          onPageChange={handlePageChange}
          nextFunction={handlePageChangeInc}
          prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
          refresh={refetch}
        />
      )}
    </div>
  );
};

export default PendingRecords;
