import { useState, useEffect } from "react";
import { Name } from "../types";
import { usePositions } from "@/user-management/hooks/usePosition";
import { PositionDto } from "@/user-management/dto/positions/positionDto";

interface UseDepartmentsData {
  departments: PositionEntity[];
  isLoading: boolean;
  setDepartments: (departments: PositionEntity[]) => void;
  positions: PositionDto[];
}

export interface PositionEntity {
  id: string;
  name: Name;
  parentId?: string | null;
  children?: PositionEntity[];
}

export const mapPositionDtoToEntity = (
  position: PositionDto
): PositionEntity => {
  return {
    id: position.id,
    name: position.name, // or position.name.am for Armenian
    parentId: position.parentPositionId,
    ...(position.subPositions.length > 0 && {
      children: position.subPositions.map(mapPositionDtoToEntity),
    }),
  };
};

export const useDepartmentsData = (unitId: string): UseDepartmentsData => {
  const [departments, setDepartments] = useState<PositionEntity[]>([]);
  const [positions, setPositions] = useState<PositionDto[]>([]);

  const { usePositionHierarchy } = usePositions();

  const { data, isLoading } = usePositionHierarchy(unitId);

  useEffect(() => {
    if (data) {
      const positions = data as PositionDto[];
      const mappedPositions: PositionEntity[] = positions.map(
        mapPositionDtoToEntity
      );
      setPositions(positions);
      setDepartments(mappedPositions);
    }
  }, [data]);

  return { departments, isLoading, setDepartments, positions };
};
