import { useMemo, useState } from "react";
import { Button } from "@/shared/common/ui/button";

import { useTranslation } from "react-i18next";

import MyApprovalsTable from "./MyApprovalsTable";
import TasksTable from "./TasksTable";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import DelegationView from "@/record-management/common/DelegationView";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { FilterParams } from "@/shared/utils/filterParams";

const approvalStatuses = [
  "approve",
  "reject",
  "send_back",
  "send_to_ro",
] as const;
type ApprovalStatus =
  | (typeof approvalStatuses)[number]
  | "active"
  | "under_review"
  | "all";

export default function ApproveRecords() {
  const { t } = useTranslation();
  const { userDetails } = useAuthUser();
  const isDelegated = userDetails?.employee?.some((emp) =>
    emp.positions.some((pos) => pos.hasDelegated),
  );
  const [statusFilter, setStatusFilter] = useState<ApprovalStatus>("active");
  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 = useMemo<CombinedFilterField[]>(
    () => [
      {
        key: "receiverEmployee",
        label: t("ApprovalPage.receiverEmployee"),
        type: "text",
      },
      {
        key: "receiverPosition",
        label: t("ApprovalPage.receiverPosition"),
        type: "text",
      },
      { key: "subject", label: t("ApprovalPage.Subject"), type: "text" },
      { key: "letterName", label: t("ApprovalPage.LetterName"), type: "text" },
      {
        key: "sendingPosition",
        label: t("ApprovalPage.SendingDepartment"),
        type: "text",
      },
      {
        key: "createdAt",
        label: t("ApprovalPage.Date"),
        type: "dateRange",
        fromKey: "fromCreatedAt",
        toKey: "toCreatedAt",
      },
    ],
    [t],
  );

  const statusOptions = [
    { value: "all", label: t("ApprovalPage.All") },
    { value: "active", label: t("statusBar.InProgress") },
    { value: "under_review", label: t("statusBar.Under Review") },
    { value: "send_to_ro", label: t("statusBar.Approved") },
    { value: "approve", label: t("statusBar.Accepted") },
    { value: "send_back", label: t("statusBar.Adjustment") },
    { value: "reject", label: t("statusBar.Rejected") },
  ];

  const isMyApprovalsMode =
    approvalStatuses.includes(statusFilter as any) || statusFilter === "all";
  const isUnderReviewMode = statusFilter === "under_review";

  return isDelegated ? (
    <DelegationView />
  ) : (
    <div className="flex flex-col gap-2 bg-background text-foreground pt-10">
      <div className="flex flex-col sm:flex-row justify-between items-start gap-4 w-full">
        <h4 className="text-xl font-medium text-gray-900 dark:text-gray-100">
          {t("ApprovalPage.Letters")}
        </h4>

        <CombinedFilterBar
          fields={filterFields}
          filters={combinedFilters.filters}
          setFilter={combinedFilters.setFilter}
          setFilters={combinedFilters.setFilters}
          removeFilter={combinedFilters.removeFilter}
          removeFilters={combinedFilters.removeFilters}
          onLiveSearch={handleLiveSearch}
        />
      </div>

      <div className="flex flex-wrap gap-2">
        {statusOptions.map(({ value, label }) => (
          <Button
            key={value}
            variant={statusFilter === value ? "linkActive" : "link"}
            onClick={() => setStatusFilter(value as ApprovalStatus)}
            className="rounded-md text-sm sm:text-base">
            {label}
          </Button>
        ))}
      </div>

      {isMyApprovalsMode ? (
        <MyApprovalsTable
          status={
            statusFilter as
              | "approve"
              | "reject"
              | "send_back"
              | "send_to_ro"
              | "active"
              | "all"
          }
          filters={combinedFilters.filters}
          liveSearch={liveSearch}
        />
      ) : (
        <TasksTable
          filters={combinedFilters.filters}
          onReview={isUnderReviewMode}
          liveSearch={liveSearch}
        />
      )}
    </div>
  );
}
