import { useState } from "react";
import type { Entity, Name } from "../types";
import { useQueryClient } from "@tanstack/react-query";

export interface UseSelectionHandlersResult {
  selectedOrgId: string;
  selectedUnitId: string;
  selectedDepartmentId: string;
  selectedDepartmentName: string;
  breadcrumb: Entity[];
  handleSelectOrganization: (id: string) => void;
  handleSelectUnit: (id: string, units: Entity[]) => void;
  handleSelectDepartment: (id: string, departments: Entity[]) => void;
}

export const useSelectionHandlers = (
  organizations: Entity[],
  localizedName: (name: Name) => string
): UseSelectionHandlersResult => {
  const queryClient = useQueryClient();
  const [selectedOrgId, setSelectedOrgId] = useState("");
  const [selectedUnitId, setSelectedUnitId] = useState("");
  const [selectedDepartmentId, setSelectedDepartmentId] = useState("");
  const [selectedDepartmentName, setSelectedDepartmentName] = useState("");

  const [breadcrumb, setBreadcrumb] = useState<Entity[]>([]);

  const handleSelectOrganization = (orgId: string) => {
    queryClient.invalidateQueries({ queryKey: ["unitList"] });

    setSelectedOrgId(orgId);
    setSelectedUnitId("");
    setSelectedDepartmentId("");

    const org = organizations.find((o) => o.id === orgId);
    if (org) {
      setBreadcrumb([{ id: org.id, name: org.name }]);
    }
  };

  const handleSelectUnit = (unitId: string, units: Entity[]) => {
    queryClient.invalidateQueries({ queryKey: ["positionHierarchy"] });

    setSelectedUnitId(unitId);
    setSelectedDepartmentId("");

    const unit = units.find((u) => u.id === unitId);
    const org = organizations.find((o) => o.id === selectedOrgId);
    if (unit && org) {
      setBreadcrumb([
        { id: org.id, name: org.name },
        { id: unit.id, name: unit.name },
      ]);
    }
  };

  const handleSelectDepartment = (
    departmentId: string,
    departments: Entity[]
  ) => {
    queryClient.invalidateQueries({
      queryKey: ["positionEmployees"],
    });

    setSelectedDepartmentId(departmentId);

    const department = departments.find((d) => d.id === departmentId);
    const unit = breadcrumb.find((b) => b.id === selectedUnitId);
    const org = breadcrumb.find((b) => b.id === selectedOrgId);
    department?.name &&
      setSelectedDepartmentName(localizedName(department?.name) || "");
    if (department && unit && org) {
      setBreadcrumb([
        { id: org.id, name: org.name },
        { id: unit.id, name: unit.name },
        { id: department.id, name: department.name },
      ]);
    }
  };

  return {
    selectedOrgId,
    selectedUnitId,
    selectedDepartmentId,
    selectedDepartmentName,
    breadcrumb,
    handleSelectOrganization,
    handleSelectUnit,
    handleSelectDepartment,
  };
};
