import {
  ChevronDown,
  ChevronRight,
  Briefcase,
  MoreVertical,
} from "lucide-react";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useState } from "react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { Button } from "@/shared/common/ui/button";
import { t } from "i18next";
import { PositionDto } from "@/user-management/dto/positions/positionDto";

interface DepartmentListProps {
  unitId: string;
  selectedDepartmentId: string;
  onSelectDepartment: (id: string) => void;
  departments: any[];
  positions: PositionDto[];
  isLoading: boolean;
  searchQuery: string;
  onAssignService?: (positionId: string, positionName: string) => void;
}

export const DepartmentList = ({
  unitId,
  selectedDepartmentId,
  onSelectDepartment,
  departments,
  positions,
  isLoading,
  searchQuery,
  onAssignService,
}: DepartmentListProps) => {
  const localizedName = useLocalizedName();
  const [expandedPositions, setExpandedPositions] = useState<Set<string>>(
    new Set()
  );

  const togglePosition = (positionId: string) => {
    setExpandedPositions((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(positionId)) {
        newSet.delete(positionId);
      } else {
        newSet.add(positionId);
      }
      return newSet;
    });
  };

  // Recursive function to render position hierarchy
  const renderPosition = (position: PositionDto, level: number = 0) => {
    const hasSubPositions =
      position.subPositions && position.subPositions.length > 0;
    const isExpanded = expandedPositions.has(position.id);

    return (
      <div key={position.id} className="space-y-1">
        <div
          className={`flex items-center gap-2 p-2 rounded-lg border transition-colors ${
            selectedDepartmentId === position.id
              ? "bg-purple-50 border-purple-500"
              : "bg-white border-gray-200 hover:bg-gray-50"
          }`}
          style={{ marginLeft: `${level * 16}px` }}
        >
          {hasSubPositions ? (
            <button
              onClick={() => togglePosition(position.id)}
              className="p-1 hover:bg-gray-200 rounded flex-shrink-0"
            >
              {isExpanded ? (
                <ChevronDown className="h-4 w-4" />
              ) : (
                <ChevronRight className="h-4 w-4" />
              )}
            </button>
          ) : (
            <div className="w-6 flex-shrink-0" />
          )}

          <button
            onClick={() => onSelectDepartment(position.id)}
            className="flex-1 flex items-center gap-2 text-left min-w-0"
          >
            <Briefcase className="h-4 w-4 flex-shrink-0" />
            <span className="font-medium truncate">
              {localizedName(position.name)}
            </span>
          </button>

          {hasSubPositions && (
            <span className="text-xs text-gray-500 px-2 flex-shrink-0">
              {position.subPositions.length}
            </span>
          )}

          {onAssignService && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0 flex-shrink-0"
                >
                  <MoreVertical className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  onClick={() =>
                    onAssignService(position.id, localizedName(position.name))
                  }
                >
                  {t("assignService", "Assign Service")}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>

        {/* Render sub-positions recursively */}
        {isExpanded && hasSubPositions && (
          <div className="space-y-1">
            {position.subPositions.map((subPosition) =>
              renderPosition(subPosition, level + 1)
            )}
          </div>
        )}
      </div>
    );
  };

  if (!unitId) {
    return (
      <div className="text-center py-8 text-gray-500">
        {t("selectUnitFirst", "Select a unit first")}
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="space-y-2">
        {[1, 2, 3].map((i) => (
          <Skeleton key={i} className="h-12 w-full" />
        ))}
      </div>
    );
  }

  // Filter positions based on search query
  const filterPositions = (positions: PositionDto[]): PositionDto[] => {
    if (!searchQuery) return positions;

    return positions.filter((position) => {
      const matchesSearch = localizedName(position.name)
        .toLowerCase()
        .includes(searchQuery.toLowerCase());

      // Also check sub-positions
      const hasMatchingSubPosition =
        position.subPositions &&
        filterPositions(position.subPositions).length > 0;

      return matchesSearch || hasMatchingSubPosition;
    });
  };

  const filteredPositions = filterPositions(positions);

  if (filteredPositions.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        {t("noPositionsFound", "No positions found")}
      </div>
    );
  }

  return (
    <div className="space-y-2">
      {filteredPositions.map((position) => renderPosition(position))}
    </div>
  );
};
