import { useLocalizedName } from "@/shared/common/localizedName";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
} from "@/shared/common/ui/select";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useQueryClient } from "@tanstack/react-query";
import Cookies from "js-cookie";
import { useTranslation } from "react-i18next";
import { UserCheck } from "lucide-react";
import { useEffect } from "react";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { PositionName } from "../dto/delegation/delegationDto";
interface BasePosition {
  id: string;
  employeePositionId: string;
  name: PositionName;
  isDelegate: boolean;
}

export const PositionSelect = () => {
  const {
    unFilteredUserDetails,
    selectedPositionId,
    setSelectedPositionId,
    isLoading,
  } = useAuthUser();
  const queryClient = useQueryClient();
  const localizedName = useLocalizedName();
  const { t } = useTranslation();
  const allPositions = Array.isArray(unFilteredUserDetails?.employee)
    ? unFilteredUserDetails.employee.flatMap((emp) => emp?.positions ?? [])
    : [];
  const selectablePositions = allPositions ?? [];
  const currentPositionCookie = Cookies.get("current-position-id");
  const delegatedPositionCookie = Cookies.get("delegatedPositionId");
  const activePositionId =
    selectedPositionId || currentPositionCookie || delegatedPositionCookie;

  const currentPosition =
    selectablePositions.find(
      (pos) =>
        pos.id === activePositionId ||
        pos.employeePositionId === activePositionId ||
        pos.id === currentPositionCookie ||
        pos.employeePositionId === delegatedPositionCookie,
    ) ?? selectablePositions[0];

  useEffect(() => {
    if (isLoading || !currentPosition) return;

    if (
      currentPosition.employeePositionId &&
      selectedPositionId !== currentPosition.employeePositionId
    ) {
      setSelectedPositionId(currentPosition.employeePositionId);
    }

    if (Cookies.get("current-position-id") !== currentPosition.id) {
      Cookies.set("current-position-id", currentPosition.id);
    }

    if (
      currentPosition.employeePositionId &&
      Cookies.get("delegatedPositionId") !== currentPosition.employeePositionId
    ) {
      Cookies.set("delegatedPositionId", currentPosition.employeePositionId);
    }
  }, [currentPosition, isLoading, selectedPositionId, setSelectedPositionId]);

  if (isLoading || selectablePositions.length === 0) return null;

  const handleChange = (value: string) => {
    setSelectedPositionId(value);
    const selected = selectablePositions.find((pos) => pos.id === value);

    Cookies.set("current-position-id", value);
    Cookies.set("delegatedPositionId", selected?.employeePositionId || "");

    // Invalidate relevant queries
    [
      // record-management
      "userRecords",
      "approvalRecord",
      "incoming-cc",
      "record-incoming",
      "incoming-instances",
      "my-collaborations",
      "external-incoming",
      "dashbordReportRO",
      "dashbordReport",
      "myRecordApprovals",
      "authUser",
      // performance-management
      "plans",
      "plans-sector",
      "my-plans",
      "my-employee-plans",
      "employee-plans",
      "combined-employee-plan",
      "plan-team-list",
      "plan-team-member-list",
      // OKR / objective-management
      "goals",
      "goal-participants",
      "goal-participant",
      "majorTasks",
      "majorTasks-participants",
      "majorTasks-participant",
      "detailTasks",
      "detailTask",
      "expectations",
      "expectation",
      "employee-expectations",
      "achievements",
      "achievement",
      "achievementStatistics",
      "participants",
      "position",
      "employees",
      "directorSignature",
      "signatureListWithPresigned",
      "teetersListWithPresigned",
    ].forEach((key) => {
      queryClient.invalidateQueries({ queryKey: [key] });
    });
  };
  function getPositionName(pos: BasePosition): PositionName {
    return pos.name;
  }
  return selectablePositions.length > 1 ? (
    <div className="relative mt-3 lg:mt-3">
      <Select value={currentPosition?.id || ""} onValueChange={handleChange}>
        <TooltipProvider delayDuration={300}>
          <Tooltip>
            <TooltipTrigger asChild>
              <div className="contents">
                <SelectTrigger className="flex items-center cursor-pointer gap-3 p-8 bg-white/80 dark:bg-gray-800/80 hover:bg-gray-100 dark:hover:bg-gray-700/80 rounded-xl transition-all shadow-sm max-w-[320px] backdrop-blur-sm border-0">
                  <div className="bg-primary-100 text-primary-800 dark:bg-primary-900/30 dark:text-primary-300 p-2 rounded-lg">
                    <UserCheck className="w-4 h-4" />
                  </div>

                  <div className="flex-1 text-left min-w-0 overflow-hidden">
                    <div className="flex items-center gap-2">
                      <p className="font-medium truncate text-sm">
                        {currentPosition
                          ? localizedName(currentPosition.name)
                          : t("delegation.select")}
                      </p>
                      {currentPosition && currentPosition.isDelegate && (
                        <span className="flex-shrink-0 text-xs bg-yellow-100 dark:bg-yellow-900/50 text-yellow-800 dark:text-yellow-200 px-2 py-0.5 rounded-md">
                          {t("delegation.title")}
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-gray-500 dark:text-gray-400 truncate mt-0.5">
                      {t("delegation.acting")}
                    </p>
                  </div>
                </SelectTrigger>
              </div>
            </TooltipTrigger>
            {currentPosition && (
              <TooltipContent
                side="bottom"
                align="start"
                className="max-w-[320px]"
              >
                <p className="font-medium">
                  {localizedName(getPositionName(currentPosition))}
                </p>
                {currentPosition && currentPosition.isDelegate && (
                  <p className="text-yellow-600 dark:text-yellow-400 text-xs mt-1">
                    {t("delegation.title")}
                  </p>
                )}
              </TooltipContent>
            )}
          </Tooltip>
        </TooltipProvider>

        <SelectContent
          className="w-[320px] max-w-[90vw] rounded-xl p-2 shadow-lg bg-white dark:bg-gray-800 max-h-[60vh] overflow-y-auto border-0"
          align="start"
        >
          <div className="py-1">
            <h3 className="px-3 py-2 text-sm font-medium text-gray-500 dark:text-gray-400 sticky top-0 bg-white dark:bg-gray-800 z-10 backdrop-blur-sm bg-opacity-90 dark:bg-opacity-90">
              {t("delegation.switchRole")}
            </h3>

            {selectablePositions.map((pos) => {
              const positionId = pos.id;
              const positionName = localizedName(pos.name);
              return (
                <SelectItem
                  key={positionId}
                  value={positionId || ""}
                  className="rounded-lg px-3 py-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-750 border-0"
                >
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <div className="flex items-center gap-3 w-full">
                          <div className="bg-primary/10 text-primary dark:bg-primary/20 dark:text-primary p-2 rounded-lg flex-shrink-0">
                            <UserCheck className="w-4 h-4" />
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="font-medium truncate text-sm">
                              {positionName}
                            </p>
                            {pos?.isDelegate && (
                              <span className="text-xs text-yellow-600 dark:text-yellow-400 mt-1 inline-block">
                                {t("delegation.title")}
                              </span>
                            )}
                          </div>
                        </div>
                      </TooltipTrigger>
                      <TooltipContent
                        side="right"
                        align="center"
                        className="max-w-[280px]"
                        hidden={positionName.length < 40}
                      >
                        <p>{positionName}</p>
                        {pos?.isDelegate && (
                          <p className="text-yellow-600 dark:text-yellow-400 text-xs mt-1">
                            {t("delegation.title")}
                          </p>
                        )}
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </SelectItem>
              );
            })}
          </div>
        </SelectContent>
      </Select>
    </div>
  ) : null;
};
