import { useState, useEffect, useMemo, useCallback } from "react";
import { DataTable } from "@/record-management/common/DataTable";
import { Button } from "@/shared/common/ui/button";
import { useExternalIncomingRecords } from "@/record-management/components/hooks/useExternalIncomingRecords";
import Loader from "@/record-management/components/Loader/loader";
import React from "react";
import HeaderSection from "../headerSection";
import { t } from "i18next";
import { ExternalIncomingRecordsColumns } from "./externalIncomingRecordsColumns";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useUserDetail } from "../../hooks/useUserDetail";
import { MeDto } from "@/shared/dto/user/meDto";
import secretaryList from "@/record-management/common/secretaryViewList";
import { useSearchParams } from "react-router-dom";
import DelegationView from "@/record-management/common/DelegationView";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { FilterParams } from "@/shared/utils/filterParams";

  const ExternalIncomingRecords = () => {
  const localizedName = useLocalizedName();
  const { userDetails } = useAuthUser();
  const { permissionKeys } = useUserDetail(userDetails as MeDto);
  const selfFilters = useCombinedFilters<FilterParams>();
  const parentFilters = useCombinedFilters<FilterParams>();
  const [statusFilterMain, setStatusFilterMain] = useState<string[]>([
    "non_smart_user",
    "external_non_smart_user",
  ]);
  const [liveSearch, setLiveSearch] = useState<{
    key: string;
    value: string;
  } | null>(null); // ← add
  const [openDropdownId, setOpenDropdownId] = useState<string | null>(null);

  const handleLiveSearch = (key: string, value: string) => {
    if (!key || !value) {
      setLiveSearch(null);
      return;
    }
    setLiveSearch({ key, value });
  };
  const [tabFilters, setTabFilters] = useState<
    Record<string, { status: string }>
  >({
    non_smart_user: { status: "" },
    external: { status: "" },
  });
  const [tabFiltersSec, setTabFiltersSec] = useState<
    Record<string, { status: string }>
  >({
    non_smart_user: { status: "" },
    external: { status: "" },
  });
  const [searchParamsUrl, setSearchParamsUrl] = useSearchParams();
  const urlPage = Number(searchParamsUrl.get("page") || 1);
  const initialView = searchParamsUrl.get("view") || "self";
  const isSecretary = permissionKeys.includes("can:viewParentPositionRecord");
  const [secretaryView, setSecretaryView] = useState(isSecretary ? initialView : "self");
  const [pagination, setPagination] = React.useState({
    pageIndex: urlPage - 1,
    pageSize: 10,
  });
  const isDelegated = userDetails?.employee?.some((emp) =>
    emp.positions.some((pos) => pos.hasDelegated),
  );

  useEffect(() => {
    if (!isSecretary && secretaryView === "parent") {
      setSecretaryView("self");
    }
  }, [isSecretary, secretaryView]);

  const isSelf = secretaryView === "self";
  const syncViewParam = useCallback((params: URLSearchParams) => {
    if (secretaryView === "parent") {
      params.set("view", "parent");
    } else {
      params.delete("view");
    }
    return params;
  }, [secretaryView]);
  const activeFilterStore = isSelf ? selfFilters : parentFilters;
  const currentTab =
    statusFilterMain.length > 1 ? "non_smart_user" : "external";
  const statusFilter = isSelf
    ? tabFilters[currentTab]?.status || ""
    : tabFiltersSec[currentTab]?.status || "";

  const filterFields = useMemo<CombinedFilterField[]>(
    () => [
      {
        key: "receiverPosition",
        label: t("userRecord.sendingOrganization"),
        type: "text",
      },
      { key: "subject", label: t("userIncoming.Subject"), type: "text" },
      {
        key: "dispatchedDate",
        label: t("userIncoming.Date"),
        type: "dateRange",
        fromKey: "fromDispatchedDate",
        toKey: "toDispatchedDate",
      },
      {
        key: "referenceNumber",
        label: t("userIncoming.Reference Number"),
        type: "text",
      },
      { key: "letterName", label: t("viewDetail.fileName1"), type: "text" },
    ],
    [],
  );

  useEffect(() => {
    setPagination((prev) => ({ ...prev, pageIndex: 0 }));
    setSearchParamsUrl(
      (prev) => {
        const params = new URLSearchParams(prev);
        params.set("page", "1");
        return syncViewParam(params);
      },
      { replace: true },
    );
  }, [
    activeFilterStore.filters,
    statusFilter,
    statusFilterMain,
    setSearchParamsUrl,
    syncViewParam,
  ]);

  useEffect(() => {
    setPagination((prev) =>
      prev.pageIndex === urlPage - 1
        ? prev
        : { ...prev, pageIndex: urlPage - 1 },
    );
  }, [urlPage]);

  useEffect(() => {
    setSearchParamsUrl(
      (prev) => syncViewParam(new URLSearchParams(prev)),
      { replace: true },
    );
  }, [secretaryView, setSearchParamsUrl, syncViewParam]);

  const recordType = window.location.pathname.includes("external")
    ? "external"
    : window.location.pathname.includes("cc")
      ? "cc"
      : "internal";

  const {
    externalRecords,
    isLoading,
    isError,
    refetch,
    externalCount,
    externalParent,
    isLoadingParent,
    isErrorParent,
    refetchParent,
    externalParentCount,
  } = useExternalIncomingRecords({
    pageIndex: pagination.pageIndex * pagination.pageSize,
    pageSize: pagination.pageSize,
    status: statusFilter || undefined,
    ...activeFilterStore.filters,
    recordType: statusFilterMain,
    fetchParent: isSecretary,
    ...(liveSearch ? { [liveSearch.key]: liveSearch.value } : {}),
  });

  let Error, loading;
  if (isSelf) {
    Error = isError;
    loading = isLoading;
  } else {
    Error = isErrorParent;
    loading = isLoadingParent;
  }
  const safeTotalCount = Math.max(
    isSelf ? externalCount || 0 : externalParentCount || 0,
    1,
  );

  const statusOptions = [
    { value: "", label: t("statusBar.All") },
    { value: "draft", label: t("statusBar.In Progress") },
    { value: "accepted", label: t("statusBar.Accepted") },
    { value: "replied", label: t("statusBar.Replied") },
    { value: "re_assigned", label: t("statusBar.Reassigned") },
    { value: "rejected", label: t("statusBar.Rejected") },
  ];

  const handleStatusChange = (value: string) => {
    if (isSelf) {
      setTabFilters((prev) => ({
        ...prev,
        [currentTab]: { ...prev[currentTab], status: value },
      }));
    } else {
      setTabFiltersSec((prev) => ({
        ...prev,
        [currentTab]: { ...prev[currentTab], status: value },
      }));
    }
  };

  useEffect(() => {
    setLiveSearch(null);
  }, [secretaryView]);

  useEffect(() => {
    const radioElementExternal = document.getElementById(
      "externalradio",
    ) as HTMLInputElement;
    if (radioElementExternal) {
      radioElementExternal.checked = true;
    }
  }, []);

  const totalPages = Math.ceil(safeTotalCount / pagination.pageSize);

  React.useEffect(() => {
    if (safeTotalCount === 1) return;

    let newPage = pagination.pageIndex + 1;

    if (newPage > totalPages) {
      newPage = 1;
      setPagination((prev) => ({ ...prev, pageIndex: 0 }));
    }

    setSearchParamsUrl((prev) => {
      const params = new URLSearchParams(prev);
      params.set("page", newPage.toString());
      return syncViewParam(params);
    });
  }, [
    totalPages,
    safeTotalCount,
    pagination.pageIndex,
    setSearchParamsUrl,
    syncViewParam,
  ]);

  const columns = useMemo(
    () =>
      ExternalIncomingRecordsColumns(
        isSelf ? refetch : refetchParent ? refetchParent : () => {},
        localizedName as (name?: { am?: string; en?: string }) => string,
        isSecretary,
        isSelf,
        pagination.pageIndex + 1,
        openDropdownId,
        setOpenDropdownId,
      ),
    [
      refetch,
      refetchParent,
      isSelf,
      isSecretary,
      localizedName,
      pagination.pageIndex,
      openDropdownId,
      setOpenDropdownId,
    ],
  );
  return isDelegated ? (
    <DelegationView />
  ) : (
    <div className="flex flex-col gap-2">
      <div className="mt-4 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={activeFilterStore.filters}
          setFilter={activeFilterStore.setFilter}
          setFilters={activeFilterStore.setFilters}
          removeFilter={activeFilterStore.removeFilter}
          removeFilters={activeFilterStore.removeFilters}
          onFilterChange={() =>
            setPagination((prev) => ({ ...prev, pageIndex: 0 }))
          }
          onLiveSearch={handleLiveSearch}
          className="w-full min-w-0"
        />
      </div>

      <HeaderSection />
      {secretaryList(isSecretary, secretaryView, setSecretaryView, "SEC")}
      {secretaryList(
        isSecretary,
        statusFilterMain,
        setStatusFilterMain,
        "EXT",
        !isSelf,
      )}
      <div className="flex flex-wrap gap-2">
        {statusOptions.map((option) => (
          <Button
            key={option.value}
            variant={statusFilter === option.value ? "linkActive" : "link"}
            onClick={() => handleStatusChange(option.value)}
            className="rounded-md text-sm sm:text-base"
          >
            {option.label}
          </Button>
        ))}
      </div>

      {loading && (
        <div className="w-full h-full">
          <Loader />
        </div>
      )}
      {Error && isDelegated && <p>{t("userIncoming.errDelegation")}</p>}
      {Error && !isDelegated && (
        <p>{t("userIncoming.Error loading records.")}</p>
      )}

      {!loading && !Error && (
        <DataTable
          tableName={`${recordType.toUpperCase()} Incoming Records`}
          columns={columns}
          data={isSelf ? externalRecords : externalParent ? externalParent : []}
          totalCount={safeTotalCount}
          pagination={pagination}
          setPagination={setPagination}
          refresh={isSelf ? refetch : refetchParent}
        />
      )}
    </div>
  );
};

export default ExternalIncomingRecords;
