import * as React from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { CirclePlus } from "lucide-react";

import { Button } from "@/shared/common/ui/button";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import Loader from "@/record-management/components/Loader/loader";
import { DelegationsColumns } from "./DelegationColumns";
import { MydelegateeColumn } from "./MydelegateeColumn";
import { useDelegations } from "@/record-management/components/hooks/useDelegations";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { useCanDelegate } from "@/record-management/components/hooks/useCanDelegate";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { cleanFilterParams, FilterParams } from "@/shared/utils/filterParams";
import { useState } from "react";

const Delegations = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [statusFilter, setStatusFilter] = React.useState("myDelegation");
  const [pageIndex, setPageIndex] = React.useState(0);
  const pageSize = 10;

  const myDelegationFilters = useCombinedFilters<FilterParams>();
  const myDelegateeFilters = useCombinedFilters<FilterParams>();
  const activeFilterStore =
    statusFilter === "myDelegation" ? myDelegationFilters : myDelegateeFilters;
  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 filterFields = React.useMemo<CombinedFilterField[]>(
    () =>
      statusFilter === "myDelegation"
        ? [
            {
              key: "delegatedPosition",
              label: t("delegation.delegatedPosition"),
              type: "text",
            },
            {
              key: "delegatedEmployee",
              label: t("delegation.delegatedEmployee"),
              type: "text",
            },
            {
              key: "startDate",
              label: t("delegation.startDate"),
              type: "dateRange",
              fromKey: "fromStartDate",
              toKey: "endDate",
            },
          ]
        : [
            {
              key: "delegatorPosition",
              label: t("delegation.delegatedPosition"),
              type: "text",
            },
            {
              key: "delegatorEmployee",
              label: t("delegation.delegatedEmployee"),
              type: "text",
            },
            {
              key: "startDate",
              label: t("delegation.startDate"),
              type: "dateRange",
              fromKey: "fromStartDate",
              toKey: "endDate",
            },
          ],
    [statusFilter, t],
  );

  const filterParams = React.useMemo(() => {
    const base = {
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "employeePosition.createdAt:DESC",
      to: "",
      ...(statusFilter === "myDelegation"
        ? myDelegationFilters.filters
        : myDelegateeFilters.filters),
    };

    const cleaned = cleanFilterParams(base);

    return liveSearch
      ? { ...cleaned, [liveSearch.key]: liveSearch.value }
      : cleaned;
  }, [
    myDelegateeFilters.filters,
    myDelegationFilters.filters,
    pageIndex,
    statusFilter,
    liveSearch,
  ]);
  const { data: canDelegateResponse } = useCanDelegate();
  const canDelegate = canDelegateResponse?.status === true;

  const { delegations, isLoading, isError, refetch, myDelegated } =
    useDelegations(filterParams);

  const activeDelegationMessage = t(
    "delegation.activeDelegationExists",
    "active delegation exists and either edit the active delegation or delete and create again",
  );

  const statusOptions = React.useMemo(
    () => [
      { value: "myDelegation", label: t("delegation.myDelegations") },
      { value: "myDelegatee", label: t("delegation.myDelegatee") },
    ],
    [t],
  );

  return (
    <div className="w-full">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 w-full">
        <h4 className="text-xl font-medium mb-5">{t("delegation.title")}</h4>

        <div className="flex flex-col items-end gap-2 w-full sm:w-auto">
          <Tooltip>
            <TooltipTrigger asChild>
              <span tabIndex={!canDelegate ? 0 : -1}>
                <Button
                  variant="addRecordBtn"
                  size="default"
                  disabled={!canDelegate}
                  onClick={() => navigate("/record-management/delegation/new")}>
                  <CirclePlus className="h-4 w-6 mr-2" />
                  {t("delegation.addDelegation")}
                </Button>
              </span>
            </TooltipTrigger>
            {!canDelegate && (
              <TooltipContent side="bottom" className="max-w-xs">
                {activeDelegationMessage}
              </TooltipContent>
            )}
          </Tooltip>
          <CombinedFilterBar
            fields={filterFields}
            filters={activeFilterStore.filters}
            setFilter={activeFilterStore.setFilter}
            setFilters={activeFilterStore.setFilters}
            removeFilter={activeFilterStore.removeFilter}
            removeFilters={activeFilterStore.removeFilters}
            onFilterChange={() => setPageIndex(0)}
            onLiveSearch={handleLiveSearch}
          />
        </div>
      </div>

      {/* Status Filter Row */}
      <div className="flex flex-wrap gap-2">
        {statusOptions.map((opt) => (
          <Button
            key={opt.value}
            variant={statusFilter === opt.value ? "linkActive" : "link"}
            onClick={() => {
              setStatusFilter(opt.value);
              setPageIndex(0);
            }}
            className="rounded-md text-base">
            {opt.label}
          </Button>
        ))}
      </div>

      {/* Table */}
      {isLoading ? (
        <Loader />
      ) : isError ? (
        <p className="text-destructive">
          {t("userRecord.Error loading records.")}
        </p>
      ) : (
        <AdvancedTable
          columns={
            statusFilter === "myDelegation"
              ? DelegationsColumns(refetch)
              : MydelegateeColumn(refetch)
          }
          data={
            statusFilter === "myDelegation"
              ? delegations?.data || []
              : myDelegated?.data || []
          }
          tableName={
            statusFilter === "myDelegation" ? "Delegation" : "Delegatee"
          }
          toolBarPosition="right"
          itemCount={
            statusFilter === "myDelegation"
              ? delegations?.count || 0
              : myDelegated?.count || 0
          }
          pageIndex={pageIndex}
          onPageChange={setPageIndex}
          nextFunction={() => setPageIndex(pageIndex + 1)}
          prevFunction={() => setPageIndex(Math.max(0, pageIndex - 1))}
          refresh={refetch}
        />
      )}
    </div>
  );
};

export default Delegations;
