import { IncomingDraftRecordsColumns } from "./incomingDraftRecordsColumns";
import Loader from "../../Loader/loader";
import { PlusCircle } from "lucide-react";
import { useState, useMemo, useEffect, useCallback } from "react";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { useTranslation } from "react-i18next";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useCreateIncomingRecords } from "../../hooks/useCreateIncomingRecord";
import { Link, useSearchParams } from "react-router-dom";
import { Button } from "@/shared/common/ui/button";
import HeaderSection from "./headerSection";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { FilterParams } from "@/shared/utils/filterParams";
import { CorrespondenceDto } from "@/record-management/dto/IncomingRecords/RecordOfficerIncoming";
import { AssignRecordDto } from "@/record-management/dto/userRecords/usersDto";
import AssigneRecordExternal from "./AssigneIncomingExternalRecord";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";

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 queryClient = useQueryClient();
  const type = "draft";

  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 [assignRecord, setAssignRecord] = useState<CorrespondenceDto | 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: "date",
        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: any = {
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "record.createdAt:DESC",
      recordTypeKey: "non_smart_user",
      ...(statusFilter && { nonSmartOfficeRecordStatus: statusFilter }),
      ...combinedFilters.filters,
    };

    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 = useCallback(async (): Promise<void> => {
    await refetch();
    await refetch1();
  }, [refetch, refetch1]);

  const handleAssignExternal = useCallback((record: CorrespondenceDto) => {
    setAssignRecord(record);
  }, []);

  const columns = useMemo(
    () =>
      IncomingDraftRecordsColumns(
        Refresh,
        localizedName as (name?: { am?: string; en?: string }) => string,
        type,
        pageIndex + 1,
        openDropdownId,
        setOpenDropdownId,
        handleAssignExternal,
      ),
    [
      Refresh,
      localizedName,
      type,
      pageIndex,
      openDropdownId,
      handleAssignExternal,
    ],
  );

  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-2">
      <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 />

      <Link
        to="/record-management/recordOfficer/incoming/add"
        state={{ shouldRefetch: true }}>
        <Button
          size="default"
          className="flex items-center gap-2 bg-primary-600 text-white hover:bg-primary-700 active:bg-primary-800 font-medium rounded-xl shadow-sm hover:shadow-md transition-all duration-200 px-4 py-2">
          <PlusCircle className="h-4 w-4" />
          {t("userRecord.addRecordRO")}
        </Button>
      </Link>

      <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={columns}
            data={externalRecords || []}
            tableName="incoming draft"
            toolBarPosition="right"
            hideToolbarFilter
            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}
          />

          {assignRecord && (
            <AssigneRecordExternal
              record={assignRecord as unknown as AssignRecordDto}
              onClose={() => {
                setAssignRecord(null);
              }}
              onSuccess={() => {
                toast.success(t("msg.successassign"));
                queryClient.invalidateQueries({
                  queryKey: ["external-record-incoming"],
                });
                queryClient.invalidateQueries({
                  queryKey: ["record-incoming"],
                });
                queryClient.invalidateQueries({
                  queryKey: ["dashbordReportRO"],
                });
                setAssignRecord(null);
                void Refresh();
              }}
              isOpen={true}
            />
          )}
        </>
      )}
    </div>
  );
};

export default IncomingRecordsDraft;
