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

import { DataTable } from "@/record-management/common/DataTable";
import { Button } from "@/shared/common/ui/button";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { useInternalIncomingRecords } from "@/record-management/components/hooks/useInternalIncomingRecords";
import Loader from "@/record-management/components/Loader/loader";
import HeaderSection from "../headerSection";
import { InternalIncomingRecordsColumns } from "./incomingInternalRecordsColumns";
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 DelegationView from "@/record-management/common/DelegationView";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { FilterParams } from "@/shared/utils/filterParams";

const InternalIncomingRecords = () => {
  const localizedName = useLocalizedName();
  const { t } = useTranslation();
  const { userDetails } = useAuthUser();
  const { permissionKeys } = useUserDetail(userDetails as MeDto);
  const selfFilters = useCombinedFilters<FilterParams>();
  const parentFilters = useCombinedFilters<FilterParams>();
  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 [statusFilter, setStatusFilter] = useState<string>("");
  const isSecretary = permissionKeys.includes("can:viewParentPositionRecord");
  const [searchParamsUrl, setSearchParamsUrl] = useSearchParams();
  const urlPage = Number(searchParamsUrl.get("page") || 1);
  const initialView = searchParamsUrl.get("view") || "self";
  const [pagination, setPagination] = useState({
    pageIndex: urlPage - 1,
    pageSize: 10,
  });
  const isDelegated = userDetails?.employee?.some((emp) =>
    emp.positions.some((pos) => pos.hasDelegated),
  );
  const [secretaryView, setSecretaryView] = useState(isSecretary ? initialView : "self");

  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 filterFields = useMemo<CombinedFilterField[]>(
    () => [
      {
        key: "sendingPosition",
        label: t("userIncoming.Department"),
        type: "text",
      },
      { key: "subject", label: t("userIncoming.Subject"), type: "text" },
      {
        key: "dispatchedDate",
        label: t("userIncoming.Dispatched Date"),
        type: "dateRange",
        fromKey: "fromDispatchedDate",
        toKey: "toDispatchedDate",
      },
      {
        key: "referenceNumber",
        label: t("userIncoming.Reference Number"),
        type: "text",
      },
    ],
    [t],
  );

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

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

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

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

  const {
    internalRecords,
    isLoading,
    isError,
    refetch,
    InternalCount,
    internalParent,
    internalParentCount,
    refetchParent,
    isErrorParent,
    isLoadingParent,
  } = useInternalIncomingRecords({
    pageIndex: pagination.pageIndex * pagination.pageSize,
    pageSize: pagination.pageSize,
    status: statusFilter || undefined,
    ...activeFilterStore.filters,
    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 ? InternalCount || 1 : internalParentCount || 1,
    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") },
  ];

  useEffect(() => {
    if (isSelf) refetch();
    else refetchParent?.();
  }, [
    activeFilterStore.filters,
    pagination.pageIndex,
    pagination.pageSize,
    statusFilter,
    refetch,
    isSelf,
    refetchParent,
  ]);

  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(
    () =>
      InternalIncomingRecordsColumns(
        isSelf ? refetch : refetchParent ? refetchParent : () => {},
        localizedName,
        isSecretary,
        isSelf,
        pagination?.pageIndex + 1,
        openDropdownId,
        setOpenDropdownId,
      ),
    [refetch, refetchParent, localizedName, isSecretary, isSelf, pagination, openDropdownId, setOpenDropdownId],
  );

  return isDelegated ? (
    <DelegationView />
  ) : (
    <div className="flex flex-col gap-2 bg-background text-foreground">
      <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")}

      <div className="flex flex-wrap gap-2">
        {statusOptions.map((option) => (
          <Button
            key={option.value}
            variant={statusFilter === option.value ? "linkActive" : "link"}
            onClick={() => setStatusFilter(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 className="text-red-600 dark:text-red-400">
          {t("userIncoming.errDelegation")}
        </p>
      )}
      {Error && !isDelegated && (
        <p className="text-red-600 dark:text-red-400">
          {t("userIncoming.Error loading records.")}
        </p>
      )}
      {!loading && !Error && (
        <DataTable
          tableName="Internal Incoming Records"
          columns={columns}
          data={isSelf ? internalRecords : internalParent ? internalParent : []}
          totalCount={safeTotalCount}
          pagination={pagination}
          setPagination={setPagination}
          toolBarPosition="right"
          refresh={isSelf ? refetch : refetchParent}
        />
      )}
    </div>
  );
};

export default InternalIncomingRecords;
