import { DepartmentSchema, DepartmentSectionSchema } from "../../../../../client";
import { Select } from "@mantine/core";
import { DepartmentSectionModalForm } from "../types/DepartmentModalForm.tsx";
import { UseFormReturnType } from "@mantine/form";


type Props = {
    allDepartments: DepartmentSchema[];
    form: UseFormReturnType<DepartmentSectionModalForm>;
    parentDepartmentSectionId?: number;
}

const DepartmentSelect = ({
                              allDepartments,
                              form,
                              parentDepartmentSectionId,
                          }: Props) => {
    const getDepartmentValue = () => {
        if (form.values.departmentId) {
            return "D" + form.values.departmentId;
        }
        return "O" + form.values.parentDepartmentSectionId;
    };

    const setDepartmentValue = (value: string | null) => {
        if (!value) {
            form.setFieldValue("departmentId", null);
            form.setFieldValue("parentDepartmentSectionId", null);
            return;
        }
        const isDepartmentSection = value && value[0] === "O";
        const id = Number.parseInt(value.substring(1));
        if (isDepartmentSection) {
            form.setFieldValue("departmentId", null);
            form.setFieldValue("parentDepartmentSectionId", id);
        } else {
            form.setFieldValue("departmentId", id);
            form.setFieldValue("parentDepartmentSectionId", null);
        }
    };

    const getDepartmentSections = (section: DepartmentSectionSchema | DepartmentSchema): DepartmentSectionSchema[] => {
        const sections: DepartmentSectionSchema[] = [];

        section.sections?.forEach((section) => {
            sections.push(section);
            sections.push(...getDepartmentSections(section));
        });
        return sections;
    };

    let departmentSections: DepartmentSectionSchema[] = [];
    allDepartments.forEach(department => {
        departmentSections.push(...getDepartmentSections(department));
    });

    if (parentDepartmentSectionId) {
        departmentSections = departmentSections.filter(section => section.id !== parentDepartmentSectionId);
    }

    return (
        <Select
            data={[
                {
                    group: "Департаменты",
                    items: allDepartments.map(d => ({ label: d.name, value: "D" + d.id.toString() })),
                },
                {
                    group: "Отделы",
                    items: departmentSections.map(d => ({ label: d.name, value: "O" + d.id.toString() })),
                },
            ]}
            value={getDepartmentValue()}
            onChange={setDepartmentValue}
            label={"Родительский департамент/отдел"}
            searchable
        />
    );
};

export default DepartmentSelect;
