import React, { createContext, FC, useContext, useEffect, useState } from "react";
import {
    DepartmentSchema,
    DepartmentSectionBaseSchema,
    DepartmentSectionSchema,
    DepartmentService,
} from "../../../../../client";
import { modals } from "@mantine/modals";
import { Text } from "@mantine/core";
import useDepartmentCrud from "../hooks/useDepartmentCrud.tsx";
import useDepartmentSectionCrud from "../hooks/useDepartmentSectionCrud.tsx";

type DepartmentContextState = {
    departments: DepartmentSchema[],
    fetchDepartments: () => void,
    onCreateDepartmentClick: (isSection: boolean, element?: DepartmentSectionBaseSchema) => void,
    onUpdateDepartmentClick: (element: DepartmentSchema | DepartmentSectionSchema, isSection: boolean) => void,
    onDeleteDepartmentClick: (element: DepartmentSchema, isSection: boolean) => void,
    onAddUserClick: (departmentSection: DepartmentSectionSchema) => void,
};

const DepartmentContext = createContext<DepartmentContextState | undefined>(
    undefined,
);

const useDepartmentContextState = () => {
    const [departments, setDepartments] = useState<DepartmentSchema[]>([]);

    const fetchDepartments = () => {
        DepartmentService.getDepartments()
            .then(res => {
                setDepartments(res.departments);
            })
            .catch(e => console.log(e));
    };

    const departmentsCrud = useDepartmentCrud({ fetchDepartments });
    const departmentSectionsCrud = useDepartmentSectionCrud({ fetchDepartments });

    useEffect(() => {
        fetchDepartments();
    }, []);

    const openDepartmentModal = (
        title: string,
        isDepartmentSection: boolean,
        element?: DepartmentSchema | DepartmentSectionSchema | DepartmentSectionBaseSchema,
    ) => {
        modals.openContextModal({
            modal: "departmentModal",
            title,
            withCloseButton: false,
            innerProps: {
                departmentsCrud,
                departmentSectionsCrud,
                isDepartmentSection,
                element,
                allDepartments: departments,
            },
        });
    };

    const onCreateDepartmentClick = (
        isSection: boolean,
        element?: DepartmentSectionBaseSchema,
    ) => {
        const title: string = isSection ? "Создание отдела" : "Создание департамента";
        openDepartmentModal(title, isSection, element);
    };

    const onUpdateDepartmentClick = (
        element: DepartmentSchema | DepartmentSectionSchema,
        isSection: boolean,
    ) => {
        const title: string = isSection ? "Редактирование отдела" : "Редактирование департамента";
        openDepartmentModal(title, isSection, element);
    };

    const onDeleteDepartmentClick = (
        element: DepartmentSchema | DepartmentSectionSchema,
        isSection: boolean,
    ) => {
        modals.openConfirmModal({
            title: "Удаление " + (isSection ? "отдела" : "департамента"),
            children: (
                <Text size="sm">
                    Вы уверены что хотите удалить {isSection ? "отдел" : "департамент"} {element.name}?
                </Text>
            ),
            labels: { confirm: "Да", cancel: "Нет" },
            confirmProps: { color: "red" },
            onConfirm: () => {
                if (isSection) {
                    departmentSectionsCrud.onDelete(element as DepartmentSectionSchema);
                } else {
                    departmentsCrud.onDelete(element as DepartmentSchema);
                }
            },
        });
    };

    const onAddUserClick = (departmentSection: DepartmentSectionSchema) => {
        modals.openContextModal({
            modal: "addUserToDepartmentModal",
            title: `Добавление пользователя в отдел ${departmentSection.name}`,
            withCloseButton: false,
            innerProps: {
                departmentSection,
                fetchDepartments,
            },
        });
    };

    return {
        departments,
        fetchDepartments,
        onCreateDepartmentClick,
        onUpdateDepartmentClick,
        onDeleteDepartmentClick,
        onAddUserClick,
    };
};

type DepartmentContextProviderProps = {
    children: React.ReactNode;
};

export const DepartmentContextProvider: FC<DepartmentContextProviderProps> = ({ children }) => {
    const state = useDepartmentContextState();
    return (
        <DepartmentContext.Provider value={state}>
            {children}
        </DepartmentContext.Provider>
    );
};

export const useDepartmentContext = () => {
    const context = useContext(DepartmentContext);
    if (!context) {
        throw new Error(
            "useDepartmentContext must be used within a DepartmentContextProvider",
        );
    }
    return context;
};
