import * as React from "react";
import { useTranslation } from "react-i18next";

import Loader from "../../components/Loader/loader";

import { Button } from "@/shared/common/ui/button";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { useMyCollaborations } from "../hooks/useMyCollaborations";
import CollaborationsColumns from "./collaborationColumns";
import { MyCollaborationsQuery } from "@/record-management/services/api/collaborationService";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import DelegationView from "@/record-management/common/DelegationView";
import { useLocalizedName } from "@/shared/common/localizedName";
import { cleanFilterParams, FilterParams } from "@/shared/utils/filterParams";
import { useState } from "react";

const Collaborations = () => {
  const { t } = useTranslation();
  const [pageIndex, setPageIndex] = React.useState(0);
  const pageSize = 10;
  const localizedName = useLocalizedName();
  const [statusFilter, setStatusFilter] = React.useState("All");
  const combinedFilters = useCombinedFilters<FilterParams>();
  const [liveSearch, setLiveSearch] = useState<{
    key: string;
    value: string;
  } | null>(null); // ← add

  const handleLiveSearch = (key: string, value: string) => {
    if (!key || !value) {
      setLiveSearch(null);
      return;
    }
    setLiveSearch({ key, value });
  };
  const { userDetails } = useAuthUser();
  const isDelegated = userDetails?.employee?.some((emp) =>
    emp.positions.some((pos) => pos.hasDelegated),
  );
  const unitId = userDetails?.employee?.[0]?.unitId ?? "";
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: !!unitId,
  });
  const canRecordBeEditedByCollaborators =
    unitConfigData?.data?.items?.[0]?.canRecordBeEditedByCollaborators ?? false;

  const filterFields = React.useMemo<CombinedFilterField[]>(
    () => [
      {
        key: "receiverPosition",
        label: t("userRecord.ReceiverPosition"),
        type: "text",
      },
      {
        key: "receiverEmployee",
        label: t("userRecord.ReceiverEmployee"),
        type: "text",
      },
      { key: "subject", label: t("userRecord.Subject"), type: "text" },
      { key: "reference", label: t("userRecord.Reference"), type: "text" },
      { key: "letterName", label: t("viewDetail.fileName"), type: "text" },
      {
        key: "createdAt",
        label: t("userRecord.Date"),
        type: "dateRange",
        fromKey: "fromCreatedAt",
        toKey: "toCreatedAt",
      },
    ],
    [t],
  );

  const filterParams = React.useMemo(() => {
    const baseParams: MyCollaborationsQuery = {
      skip: pageIndex * pageSize,
      take: pageSize,
      ...(combinedFilters.filters as MyCollaborationsQuery),
    };

    if (statusFilter !== "All") baseParams.signStatus = statusFilter;

    const cleaned = cleanFilterParams(baseParams);

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

  const { data, isLoading, isError, refetch } =
    useMyCollaborations(filterParams);

  const statusOptions = React.useMemo(
    () => [
      { value: "All", label: t("statusBar.All") },
      { value: "draft", label: t("statusBar.InProgress") },
      { value: "signed", label: t("statusBar.Accepted") },
      { value: "rejected", label: t("statusBar.Rejected") },
    ],
    [t],
  );

  return isDelegated ? (
    <DelegationView />
  ) : (
    <div className="flex flex-col gap-2 w-full overflow-x-auto">
      <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4 mb-4 w-full mt-5">
        <h4 className="text-xl font-medium">
          {t("header.navigation.collaborations")}
        </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-2 mb-4">
        {statusOptions.map((opt) => (
          <Button
            key={opt.value}
            variant={statusFilter === opt.value ? "linkActive" : "link"}
            onClick={() => {
              setStatusFilter(opt.value);
              setPageIndex(0);
            }}
            className="rounded-md text-sm sm:text-base">
            {opt.label}
          </Button>
        ))}
      </div>

      <div className="w-full overflow-x-auto">
        {isLoading ? (
          <Loader />
        ) : isError ? (
          <div className="flex flex-col items-center justify-center h-full p-6 bg-red-50 border border-red-200 rounded-lg">
            <p className="mt-2 text-lg text-red-600 text-center max-w-sm">
              {t("userIncoming.Error loading records.")}
            </p>
          </div>
        ) : (
          <AdvancedTable
            columns={CollaborationsColumns(
              refetch,
              localizedName,
              canRecordBeEditedByCollaborators,
            )}
            data={data?.items || []}
            tableName="Collaborations"
            toolBarPosition="right"
            itemCount={data?.count || 0}
            pageIndex={pageIndex}
            onPageChange={setPageIndex}
            nextFunction={() => setPageIndex(pageIndex + 1)}
            prevFunction={() => setPageIndex(Math.max(0, pageIndex - 1))}
            refresh={refetch}
            initialColumnVisibility={{
              referenceNumber: false,
            }}
          />
        )}
      </div>
    </div>
  );
};

export default Collaborations;
