import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { FilterParams } from "@/shared/utils/filterParams";
import { IncomingDraftRecordsColumns } from "./incomingDraftRecordsColumns";
import Loader from "../../Loader/loader";
import { useState, useMemo, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useCreateIncomingRecords } from "../../hooks/useCreateIncomingRecord";
import { Button } from "@/shared/common/ui/button";
import HeaderSection from "./headerSection";
import { useSearchParams } from "react-router-dom";

const IncomingRecordsDraft = () => {
  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 type = "externalNonSmart";

  const combinedFilters = useCombinedFilters<FilterParams>();
  const [liveSearch, setLiveSearch] = useState<{
    key: string;
    value: string;
  } | null>(null);
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [openDropdownId, setOpenDropdownId] = useState<string | null>(null);

  const filterFields = useMemo<CombinedFilterField[]>(
    () => [
      {
        key: "letterNumber",
        label: t("userRecord.Letter Number"),
        type: "text",
      },
      {
        key: "sendingOrganization",
        label: t("userRecord.sendingOrganization"),
        type: "text",
      },
      { key: "subject", label: t("userRecord.Subject"), type: "text" },
      { key: "letterName", label: t("viewDetail.fileName1"), type: "text" },
      {
        key: "dispatchedDate",
        label: t("userRecord.Date"),
        type: "dateRange",
        fromKey: "from",
        toKey: "to",
      },
    ],
    [t],
  );

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

  const filterParams = useMemo(() => {
    const base = {
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "record.createdAt:DESC",
      recordTypeKey: "external_non_smart_user",
      ...(statusFilter && { nonSmartOfficeRecordStatus: statusFilter }),
      ...combinedFilters.filters,
    };

    // Apply live search after spread so cleanFilterParams doesn't strip it
    return liveSearch ? { ...base, [liveSearch.key]: liveSearch.value } : base;
  }, [pageIndex, statusFilter, combinedFilters.filters, liveSearch]);

  const {
    externalRecords,
    externalRecordsCount,
    isExternalRecordIncoming,
    isExternalRecordIncomingError,
    refetch1,
    refetch,
  } = useCreateIncomingRecords(filterParams);

  const statusOptions = [
    { value: "", label: t("statusBar.All") },
    { value: "not_assigned", label: t("statusBar.not_assigned") },
    { value: "assigned", label: t("statusBar.assigned") },
  ];

  const Refresh = async (): Promise<void> => {
    await refetch();
    await refetch1();
  };

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

  useEffect(() => {
    if (!externalRecordsCount) 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, externalRecordsCount]);

  const handlePageChangeInc = () => {
    const newPage = pageIndex + 1;
    setPageIndex(newPage);
    setSearchParams((prev) => {
      prev.set("page", newPage.toString());
      return prev;
    });
  };

  return (
    <div className="w-full mx-auto py-6 space-y-6">
      <div className="flex w-full min-w-0 flex-col gap-4">
        <h4 className="text-xl font-medium text-gray-900 dark:text-gray-100">
          {t("userIncoming.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}
          className="w-full min-w-0"
        />
      </div>
      <HeaderSection />

      <div className="flex flex-wrap gap-2 mb-4 mt-5">
        {statusOptions.map((opt) => (
          <Button
            key={opt.value}
            variant={statusFilter === opt.value ? "linkActive" : "link"}
            onClick={() => {
              setStatusFilter(opt.value);
              setPageIndex(0);
            }}
            className="rounded-md text-base base:text-base">
            {opt.label}
          </Button>
        ))}
      </div>

      {isExternalRecordIncomingError && (
        <p>{t("userIncoming.Error loading records.")}</p>
      )}
      {isExternalRecordIncoming ? (
        <Loader />
      ) : (
        <AdvancedTable
          columns={IncomingDraftRecordsColumns(
            Refresh,
            localizedName as (name?: { am?: string; en?: string }) => string,
            type,
            pageIndex + 1,
            openDropdownId,
            setOpenDropdownId,
          )}
          data={externalRecords || []}
          tableName="incoming draft external"
          toolBarPosition="right"
          extraToolbar={<div className="flex gap-2"></div>}
          itemCount={externalRecordsCount || 2}
          pageIndex={pageIndex}
          onPageChange={setPageIndex}
          nextFunction={handlePageChangeInc}
          prevFunction={() => setPageIndex(Math.max(pageIndex - 1, 0))}
          refresh={Refresh}
        />
      )}
    </div>
  );
};

export default IncomingRecordsDraft;
