import { cn } from "@/super-admin/lib/utils";
import { UnitActions } from "../actions/UnitActions";
import { useState, useRef } from "react";
import { Entity, Name } from "../types";
import { FolderX, Loader2 } from "lucide-react";
import { useLocalizedName } from "@/shared/common/localizedName";
import { t } from "i18next";

interface Unit {
  id: string;
  name: Name;
  departments?: any[];
  isExpanded?: boolean;
  isRelated?: boolean;
}

interface UnitListProps {
  organizationId?: string;
  selectedUnitId: string;
  onSelectUnit: (unitId: string, units: Entity[]) => void;
  units: Unit[];
  isLoading: boolean;
  searchQuery?: string;
  onEditUnit?: (unitId: string) => void;
  onArchiveUnit?: (unitId: string, unitName: string) => void;
  onDeleteUnit?: (unitId: string, unitName: string) => void;
  onAddDepartment?: (unitId: string) => void;
  onManageUnitAdmin?: (unitId: string) => void;
  onAddFromSubCity?: (unitId: string) => void;
}

export const UnitList = ({
  selectedUnitId,
  onSelectUnit,
  units = [],
  isLoading = false,
  searchQuery = "",
  onAddDepartment,
  onManageUnitAdmin,
  onEditUnit,
  onArchiveUnit,
  onDeleteUnit,
  onAddFromSubCity,
}: UnitListProps) => {
  const [hoveredId, setHoveredId] = useState<string | null>(null);
  const [clickTimeout, setClickTimeout] = useState<NodeJS.Timeout | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const localizedName = useLocalizedName();

  // Filter units based on search query
  const filteredUnits = units.filter((unit) => {
    if (!searchQuery) return true;
    const name = localizedName(unit.name);
    return name.toLowerCase().includes(searchQuery.toLowerCase());
  });

  // Handle single click with delay to prevent double-click interference
  const handleUnitClick = (unitId: string, units: Entity[]) => {
    // If already selected, don't trigger selection again
    if (unitId === selectedUnitId) {
      return;
    }

    // Clear any existing timeout
    if (clickTimeout) {
      clearTimeout(clickTimeout);
    }

    // Set a timeout to handle the click after a short delay
    const timeout = setTimeout(() => {
      onSelectUnit(unitId, units);
    }, 200);

    setClickTimeout(timeout);
  };
  return (
    <div
      className="flex flex-col gap-2 h-[50vh]   overflow-y-auto"
      ref={containerRef}
    >
      {isLoading && filteredUnits.length === 0 ? (
        <div className="flex justify-center items-center h-full gap-2 text-gray-500 dark:text-gray-400">
          <Loader2 className="w-4 h-4 animate-spin" />
          <p>{t("organization.loading")}</p>
        </div>
      ) : filteredUnits.length > 0 ? (
        filteredUnits.map((unit) => {
          return (
            <div
              key={unit.id}
              className={cn(
                "flex items-center justify-between p-2 rounded-md cursor-pointer group",
                unit.id === selectedUnitId
                  ? "bg-primary-50 dark:bg-primary-900/30 text-primary-700 dark:text-primary-300"
                  : "hover:bg-primary-50 dark:hover:bg-primary-900/20 hover:text-primary-700 dark:hover:text-primary-300 text-gray-800 dark:text-gray-200"
              )}
              onMouseEnter={() => setHoveredId(unit.id)}
              onMouseLeave={() => setHoveredId(null)}
              onClick={() => handleUnitClick(unit.id, units)}
            >
              <div className="flex-1">
                <span
                  className={cn(
                    "text-sm",
                    unit.id === selectedUnitId ? "font-medium" : ""
                  )}
                >
                  {localizedName(unit.name)}
                </span>
              </div>
              <UnitActions
                unit={unit}
                onAddDepartment={onAddDepartment}
                onManageUnitAdmin={onManageUnitAdmin}
                onEditUnit={onEditUnit}
                onArchiveUnit={unit.isRelated ? undefined : onArchiveUnit}
                onDeleteUnit={unit.isRelated ? undefined : onDeleteUnit}
                onAddFromSubCity={onAddFromSubCity}
                showAlways={hoveredId === unit.id || unit.id === selectedUnitId}
              />
            </div>
          );
        })
      ) : (
        <div className="flex flex-col items-center justify-center h-full gap-2 text-gray-400 dark:text-gray-500">
          <FolderX className="w-6 h-6" />
          <p className="text-sm">{t("contentManagement.noUnit")}</p>
        </div>
      )}
      {isLoading && units.length > 0 && (
        <div className="flex justify-center py-2 text-gray-500 dark:text-gray-400 text-sm">
          <Loader2 className="w-4 h-4 animate-spin mr-2" />
          {t("organization.loading")}
        </div>
      )}
    </div>
  );
};
