import { useEffect, useState } from 'react';
import { useFormContext, useFormState } from 'react-hook-form';
import { PHXDivider } from '../Divider/divider';
import { CheckboxGroup } from './components/radio-group-select';
import { TARGET_CONFIGS } from './config';
import { DEFAULT_NOTIFY_WITH_BY_TARGET, ERoleCode, FILTER_BY } from './constant';
import { GET_CLASSROOM_BY_USER_IDS, GET_TARGET_BY_ROLE_QUERY } from './graphql/query';
import { transformTargetUser } from './ultis/tranform-target-user';
import PHXGetCurrentYearWithTermV3 from '../Func/SchoolYearV3/getSchoolYearV3';
import PHXFuncGetLoggedInfo from '../Func/getLoginInfo';
import { PHXClientQueryV3 } from '../Func/GRPC/PHXGrpcClientV3';
import React from 'react';
import { PHXBannerWithCard } from '../BannerWithCard/BannerWithCard';
import { PHXSkeleton } from '../Skeleton';
import { PHXCheckbox } from '../Checkbox';
import { PHXText } from '../Text/Text';
import PHXToggle from '../PHXToggle/Toggle';
import { useGetDataSelectTarget } from './hooks';
import { PHXBox } from '../Box';
export const PHXFormTarget = ({ targetId, onLoading, onChange }) => {
    var _a, _b, _c;
    const { clearErrors, control, formState: { errors }, register, setValue, watch, } = useFormContext();
    const [getDefaultLoading, setGetDefaultLoading] = useState(false);
    const schoolYear = PHXGetCurrentYearWithTermV3();
    const schoolYearId = (_b = (_a = schoolYear === null || schoolYear === void 0 ? void 0 : schoolYear.current_school_year) === null || _a === void 0 ? void 0 : _a.schoolYear) === null || _b === void 0 ? void 0 : _b.id;
    const userInfo = PHXFuncGetLoggedInfo();
    const { loading: getSelectLoading, selectOptions } = useGetDataSelectTarget({
        schoolYearId,
    });
    const { isSubmitted } = useFormState({ control });
    const listTargetSelected = watch('target');
    const handleSetTarget = (newTargets) => {
        setValue('target', newTargets, {
            shouldValidate: false,
            shouldDirty: true,
        });
        onChange === null || onChange === void 0 ? void 0 : onChange(newTargets);
    };
    useEffect(() => {
        register('target', {
            validate: (value) => (value === null || value === void 0 ? void 0 : value.length) > 0 || 'Vui lòng chọn loại đối tượng',
        });
    }, []);
    const handleChangeTarget = (target) => {
        const exists = listTargetSelected.some((item) => item.target === target);
        const nextValues = exists
            ? listTargetSelected.filter((item) => item.target !== target)
            : [
                ...listTargetSelected,
                {
                    target,
                    filter: [],
                    notifyWith: DEFAULT_NOTIFY_WITH_BY_TARGET[target],
                },
            ];
        handleSetTarget(nextValues);
    };
    const handleChangeNotifyWith = (target, notifyWith) => {
        const itemIndex = listTargetSelected.findIndex((item) => item.target === target && item.notifyWith === notifyWith);
        let nextValues = [...listTargetSelected];
        if (itemIndex !== -1) {
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const { notifyWith: _, ...rest } = nextValues[itemIndex];
            nextValues[itemIndex] = rest;
        }
        else {
            nextValues = listTargetSelected.map((item) => (item.target === target ? { ...item, notifyWith } : item));
        }
        handleSetTarget(nextValues);
    };
    const handleChangeFilter = (target, checked, filterItem) => {
        clearErrors('target');
        // lất vị trí item hiện tại trong danh sách
        const selectedIndex = listTargetSelected.findIndex((i) => i.target === target);
        if (selectedIndex === -1)
            return;
        // lấy ra item hiện tại
        const item = listTargetSelected[selectedIndex];
        // kiểm tra xem filter đã tồn tại chưa
        const exists = item.filter.some((f) => f.filterBy === filterItem.filterBy);
        const isCheckAll = filterItem.filterBy === FILTER_BY.ALL;
        let nextFilter;
        // xử lý logic thay đổi filter
        if (!checked) {
            nextFilter = item.filter.filter((f) => f.filterBy !== filterItem.filterBy);
        }
        else if (exists) {
            nextFilter = item.filter.map((f) => (f.filterBy === filterItem.filterBy ? filterItem : f));
        }
        else {
            if (isCheckAll) {
                // nếu chọn "Tất cả", thì bỏ tất cả các filter khác
                nextFilter = [filterItem];
            }
            else {
                nextFilter = [...item.filter, filterItem];
            }
        }
        const nextValues = [...listTargetSelected];
        nextValues[selectedIndex] = {
            ...item,
            filter: nextFilter,
        };
        handleSetTarget(nextValues);
    };
    const getDefaultData = async () => {
        if (!targetId)
            return;
        onLoading === null || onLoading === void 0 ? void 0 : onLoading(true);
        setGetDefaultLoading(true);
        try {
            const { data: { user_segment_target_by_pk: { school_year_id, target_by_roles }, }, } = await PHXClientQueryV3({
                query: GET_TARGET_BY_ROLE_QUERY,
                variables: {
                    id: targetId,
                },
            });
            const userIds = target_by_roles.flatMap((r) => r.target_users).map((u) => u.user.id);
            const { data } = await PHXClientQueryV3({
                query: GET_CLASSROOM_BY_USER_IDS,
                variables: {
                    schoolYearId: school_year_id || schoolYearId,
                    userIds,
                },
            });
            const classroomMap = data.classroom_student.reduce((acc, item) => {
                var _a;
                acc[_a = item.user.id] || (acc[_a] = []);
                acc[item.user.id].push(item.classroom);
                return acc;
            }, {});
            const result = target_by_roles.map((item) => {
                var _a, _b;
                return ({
                    ...item,
                    role: {
                        ...item.role,
                        role_code: ((_a = item.role) === null || _a === void 0 ? void 0 : _a.role_code) === ERoleCode.PARENT ? ERoleCode.STUDENT : (_b = item.role) === null || _b === void 0 ? void 0 : _b.role_code,
                    },
                    target_users: item.target_users.map((tu) => ({
                        ...tu,
                        user: {
                            ...tu.user,
                            classroom_students: (classroomMap[tu.user.id] || []).map((classroom) => ({ classroom })),
                        },
                    })),
                });
            });
            const formatted = result
                .map((item) => {
                var _a, _b, _c, _d, _e, _f, _g;
                const filters = [];
                if (item.is_all) {
                    filters.push({ filterBy: FILTER_BY.ALL, filterValues: [] });
                }
                if ((_a = item.target_educational_levels) === null || _a === void 0 ? void 0 : _a.length) {
                    filters.push({
                        filterBy: FILTER_BY.EDUCATIONAL_LEVEL,
                        filterValues: item.target_educational_levels.map((x) => x.educational_level),
                    });
                }
                if ((_b = item.target_grades) === null || _b === void 0 ? void 0 : _b.length) {
                    filters.push({
                        filterBy: FILTER_BY.GRADE,
                        filterValues: item.target_grades.map((x) => x.grade),
                    });
                }
                if ((_c = item.target_classrooms) === null || _c === void 0 ? void 0 : _c.length) {
                    filters.push({
                        filterBy: FILTER_BY.CLASSROOM,
                        filterValues: item.target_classrooms.map((x) => x.classroom),
                    });
                }
                if ((_d = item.target_departments) === null || _d === void 0 ? void 0 : _d.length) {
                    filters.push({
                        filterBy: FILTER_BY.DEPARTMENT,
                        filterValues: item.target_departments.map((x) => x.department),
                    });
                }
                if ((_e = item.target_users) === null || _e === void 0 ? void 0 : _e.length) {
                    filters.push({
                        filterBy: FILTER_BY.CUSTOM_LIST,
                        filterValues: item.target_users.map((u) => {
                            var _a, _b, _c;
                            const formatUser = transformTargetUser([
                                {
                                    ...u.user,
                                    full_name: u.user.name,
                                    phone_number: (_a = u.user) === null || _a === void 0 ? void 0 : _a.phone,
                                },
                            ], (_c = (_b = item.role) === null || _b === void 0 ? void 0 : _b.role_code) !== null && _c !== void 0 ? _c : ERoleCode.DEPARTMENT);
                            return formatUser[0];
                        }),
                    });
                }
                if (filters.length === 0)
                    return null;
                return {
                    target: (_g = (_f = item.role) === null || _f === void 0 ? void 0 : _f.role_code) !== null && _g !== void 0 ? _g : ERoleCode.DEPARTMENT,
                    filter: filters,
                    notifyWith: item.notify_with,
                };
            })
                .filter((item) => item !== null);
            handleSetTarget(formatted);
        }
        catch (e) {
            console.error(e);
        }
        finally {
            setGetDefaultLoading(false);
            onLoading === null || onLoading === void 0 ? void 0 : onLoading(false);
        }
    };
    useEffect(() => {
        if (targetId && schoolYearId && (userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id)) {
            getDefaultData();
        }
    }, [targetId, schoolYearId, userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id]);
    return (React.createElement(React.Fragment, null, (getSelectLoading || getDefaultLoading) && targetId ? (React.createElement(PHXSkeleton, { type: 'table' })) : (React.createElement("div", null,
        ((_c = errors.target) === null || _c === void 0 ? void 0 : _c.message) && (React.createElement(PHXBannerWithCard, { className: 'mb-3', description: errors.target.message, hideCloseButton: true, show: true, type: 'danger' })),
        React.createElement("div", { className: 'space-y-2' }, TARGET_CONFIGS.map((config, targetIndex) => {
            var _a, _b, _c, _d, _e;
            const { listRadio, notifyWith, title, value: targetConfig } = config;
            const isChecked = listTargetSelected.some((i) => i.target === targetConfig);
            const item = listTargetSelected.find((i) => i.target === targetConfig);
            const notifyActive = (item === null || item === void 0 ? void 0 : item.notifyWith) === (notifyWith === null || notifyWith === void 0 ? void 0 : notifyWith.value);
            const targetError = (_c = (_b = (_a = errors === null || errors === void 0 ? void 0 : errors.target) === null || _a === void 0 ? void 0 : _a[targetIndex]) === null || _b === void 0 ? void 0 : _b.filter) === null || _c === void 0 ? void 0 : _c.message;
            return (React.createElement("div", { key: targetConfig, className: 'space-y-2' },
                React.createElement("div", null,
                    React.createElement(PHXCheckbox, { checked: isChecked, error: !!targetError && isSubmitted, errorType: 'required-field', id: targetConfig, onChange: () => handleChangeTarget(targetConfig), title: title }),
                    React.createElement("div", { className: 'ml-7' },
                        React.createElement(PHXText, { tone: 'subdued' }, config.description))),
                notifyWith && isChecked && (React.createElement("div", { className: 'ml-7 flex flex-col gap-2' },
                    React.createElement(PHXBox, { mb: 'atomic' },
                        React.createElement(PHXDivider, null)),
                    React.createElement("div", { className: 'flex items-center justify-between ' },
                        React.createElement(PHXText, null, notifyWith.title),
                        React.createElement(PHXToggle, { active: !!notifyActive, onChange: () => handleChangeNotifyWith(targetConfig, notifyWith.value) })),
                    React.createElement(PHXText, { tone: 'subdued' }, notifyWith.description),
                    React.createElement(PHXDivider, null))),
                isChecked && (React.createElement("div", null,
                    React.createElement(CheckboxGroup, { errors: (_e = (_d = errors === null || errors === void 0 ? void 0 : errors.target) === null || _d === void 0 ? void 0 : _d[targetIndex]) === null || _e === void 0 ? void 0 : _e.filter, handleChangeFilter: handleChangeFilter, listRadio: listRadio, listTargetSelected: listTargetSelected, schoolYearId: schoolYearId, selectOptions: selectOptions, target: targetConfig })))));
        }))))));
};
//# sourceMappingURL=PHXFormTarget.js.map