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

import { OutgoingRecordsColumns } from "./outgoingRecordsColumns";
import { useOutgoingRecords } from "@/record-management/components/hooks/useOutgoingRecords";
import Loader from "../../../components/Loader/loader";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { useLocalizedName } from "@/shared/common/localizedName";
import { OutgoingRecordQueryParams } from "@/record-management/services/api/recordOfficerService";
import { cleanFilterParams, FilterParams } from "@/shared/utils/filterParams";
import { cn } from "@/shared/common/ui/fileUploader/utils";

const OutgoingRecords = () => {
  const pageSize = 10;
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const combinedFilters = useCombinedFilters<FilterParams>();
  const [searchParams, setSearchParams] = useSearchParams();
  const urlPage = Number(searchParams.get("page") || 1);
  const [pageIndex, setPageIndex] = useState(urlPage - 1);
  const [lettertypes, setLettertypes] = useState("All");
  const [liveSearch, setLiveSearch] = useState<{
    key: string;
    value: string;
  } | null>(null);
  const columns = useMemo(
    () => OutgoingRecordsColumns(localizedName, pageIndex + 1),
    [localizedName, pageIndex],
  );

  const filterFields = useMemo<CombinedFilterField[]>(
    () => [
      {
        key: "referenceNumber",
        label: t("userRecord.Reference Number"),
        type: "text",
      },
      { key: "receiver", label: t("userRecord.To"), type: "text" },
      {
        key: "sendingPosition",
        label: t("userIncoming.Sending Department"),
        type: "text",
      },
      { key: "subject", label: t("userIncoming.Subject"), type: "text" },
      {
        key: "dispatchedBy",
        label: t("userIncoming.ConvertedBy"),
        type: "text",
      },
      {
        key: "dispatchedDate",
        label: t("userRecord.Date"),
        type: "dateRange",
        fromKey: "fromDispatchedDate",
        toKey: "toDispatchedDate",
      },
    ],
    [t],
  );

  const filterParams = useMemo(() => {
    const cleaned = cleanFilterParams({
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "dispatchedDate:DESC,createdAt:DESC",
      recordTypeKey: lettertypes === "All" ? undefined : lettertypes,
      ...combinedFilters.filters,
    }) as OutgoingRecordQueryParams;

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

  const { recordsResponse, isLoading, isError, refetch } =
    useOutgoingRecords(filterParams);

  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 = recordsResponse?.count
    ? Math.ceil(recordsResponse?.count / pageSize)
    : 1;

  useEffect(() => {
    if (!recordsResponse?.count) 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, recordsResponse?.count]);
  const recordTypes = useMemo(
    () => [
      { value: "All", label: t("userRecord.All") },
      { value: "external", label: t("nav.external") },
      { value: "internal", label: t("nav.internal") },
    ],
    [t],
  );
  return (
    <div className="w-full mx-auto py-6 space-y-6">
      <div className="flex flex-col sm:flex-row justify-between items-start gap-4 w-full">
        <h4 className="text-xl font-medium mt-2">
          {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}
        />
      </div>
      <div className="flex flex-wrap gap-1 sm:gap-1 md:gap-2">
        {recordTypes.map((item) => (
          <button
            key={item.value}
            onClick={() => setLettertypes(item.value)}
            className={cn(
              "flex items-center justify-center gap-1 sm:gap-2 text-base base:text-base border min-w-[90px] sm:min-w-[120px] md:min-w-[180px] rounded-md px-2 py-1.5 relative transition-colors cursor-pointer",
              lettertypes === item.value
                ? "text-primary-700 dark:text-primary-foreground border-primary dark:border-primary bg-primary-50 dark:bg-primary/30"
                : "text-gray-600 dark:text-gray-300 border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700",
            )}
          >
            {item.label}
          </button>
        ))}
      </div>

      {isError && <p>{t("userIncoming.Error loading records.")}</p>}
      {isLoading ? (
        <Loader />
      ) : (
        <AdvancedTable
          columns={columns}
          data={recordsResponse?.items || []}
          tableName="Outgoing Records"
          toolBarPosition="right"
          hideToolbarFilter
          extraToolbar={<div className="flex gap-2"></div>}
          itemCount={recordsResponse?.count || 2}
          pageIndex={pageIndex}
          onPageChange={handlePageChange}
          nextFunction={handlePageChangeInc}
          prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
          refresh={refetch}
        />
      )}
    </div>
  );
};

export default OutgoingRecords;
