import React, { useEffect, useRef, useState } from 'react';
import * as XLSX from 'xlsx';
import { getRoleNameByTarget } from '../../ultis/get-role-name-by-target';
import { ConfirmUpload } from './confirm-upload';
import { PreviewUser } from './preview-user';
import { ERROR_MESSAGE_UPLOAD_FILE, SAMPLE_FILE_URL } from '../../constant';
import { PHXModal } from '../../../Modal';
import { useImportUser } from '../../hooks/use-import-user';
import { PHXBannerWithCard } from '../../../BannerWithCard/BannerWithCard';
import { EUploadType, PHXUploadFile } from '../../../UploadFile/PHXUploadFile';
export default function ModalImportUser({ onHide, onSubmit, show, target }) {
    const [fileName, setFileName] = useState('');
    const [error, setError] = useState('');
    const [userCodes, setUserCodes] = useState([]);
    const { findUserByUserCodes } = useImportUser();
    const [step, setStep] = useState(1);
    const [loading, setLoading] = useState(false);
    const [validList, setValidList] = useState([]);
    const [invalidList, setInvalidList] = useState([]);
    const downloadLinkRef = useRef(null);
    const roleName = getRoleNameByTarget(target);
    const onHandleHide = () => {
        onHide();
    };
    const step1HandleFindUser = async (codes) => {
        if (codes.length === 0) {
            setError('user_code không được để trống');
            return;
        }
        setLoading(true);
        try {
            const response = await findUserByUserCodes(target, codes);
            const nodeMap = new Map();
            response.forEach((n) => nodeMap.set(n.code, n));
            const codeCounts = new Map();
            codes.forEach((code) => {
                codeCounts.set(code, (codeCounts.get(code) || 0) + 1);
            });
            const invalids = [];
            const valids = [];
            const seenValid = new Set();
            codes.forEach((code) => {
                if (codeCounts.get(code) > 1) {
                    invalids.push({
                        code,
                        reason: 'Trùng mã',
                        reasonDetail: `Mã ${getRoleNameByTarget(target, false)} đang bị trùng`,
                    });
                }
                else if (!nodeMap.has(code)) {
                    invalids.push({
                        code,
                        reason: 'Sai mã',
                        reasonDetail: `Mã ${getRoleNameByTarget(target, false)} không tồn tại`,
                    });
                }
                else {
                    if (!seenValid.has(code)) {
                        valids.push(nodeMap.get(code));
                        seenValid.add(code);
                    }
                }
            });
            setInvalidList(invalids);
            setValidList(valids);
            setStep(2);
        }
        catch (err) {
            console.error(err);
        }
        finally {
            setLoading(false);
        }
    };
    const step3HandleSubmit = () => {
        onSubmit(validList);
        onHide();
    };
    const handleFileChange = (e) => {
        var _a;
        const file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
        if (file) {
            setError('');
            const reader = new FileReader();
            reader.onload = (evt) => {
                var _a;
                const arrayBuffer = (_a = evt.target) === null || _a === void 0 ? void 0 : _a.result;
                if (arrayBuffer) {
                    try {
                        const workbook = XLSX.read(arrayBuffer, { type: 'array' });
                        const sheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[sheetName];
                        const data = XLSX.utils.sheet_to_json(worksheet, { defval: '' });
                        if (data.length === 0) {
                            setError(ERROR_MESSAGE_UPLOAD_FILE);
                            setFileName('');
                            return;
                        }
                        const firstRow = data[0];
                        const hasUserCode = Object.keys(firstRow).some((key) => key.trim().toLowerCase() === 'user_code');
                        if (!hasUserCode) {
                            setError(ERROR_MESSAGE_UPLOAD_FILE);
                            setFileName('');
                            return;
                        }
                        const userCodesExcel = data.map((item) => String(item.user_code));
                        setUserCodes(userCodesExcel);
                        setFileName(file.name);
                    }
                    catch (err) {
                        setError(ERROR_MESSAGE_UPLOAD_FILE);
                        setFileName('');
                    }
                }
            };
            reader.readAsArrayBuffer(file);
        }
        e.target.value = '';
    };
    useEffect(() => {
        if (show) {
            setStep(1);
            setFileName('');
            setError('');
            setUserCodes([]);
            setValidList([]);
            setInvalidList([]);
        }
    }, [show]);
    const STEP_CONFIG = {
        1: {
            primaryText: 'Tiếp tục',
            title: `Tải lên danh sách ${roleName}`,
            sizeModal: 'large',
            handleSubmit: () => step1HandleFindUser(userCodes),
        },
        2: {
            leftActionText: '← Quay lại',
            leftActionHandle: () => setStep(1),
            primaryText: 'Tải lên',
            title: `Xem trước danh sách ${roleName}`,
            sizeModal: 'extra-large',
            handleSubmit: () => setStep(3),
        },
        3: {
            leftActionHandle: () => setStep(2),
            handleSubmit: () => step3HandleSubmit(),
            primaryText: 'Xác nhận',
            title: 'Xác nhận tải lên',
            sizeModal: 'medium',
        },
    };
    const currentStep = STEP_CONFIG[step];
    return (React.createElement(PHXModal, { closeButton: true, disableSubmit: step === 1 ? !fileName || loading : false, dowloadIcon: step === 1, downloadLinkRef: step === 1 ? downloadLinkRef : undefined, downloadText: step === 1 ? 'Tải xuống file mẫu' : undefined, hrefLink: step === 1 ? SAMPLE_FILE_URL.url : undefined, inCard: false, leftActionText: currentStep.leftActionText, onCancel: onHandleHide, onHide: onHandleHide, onLeftActionText: currentStep.leftActionHandle, onSubmit: currentStep.handleSubmit, primaryActionText: currentStep.primaryText, primaryLoading: loading, secondaryActionText: '\u0110\u00F3ng', show: show, size: currentStep.sizeModal || 'large', title: currentStep.title },
        React.createElement("div", { className: 'py-2' },
            step === 1 && (React.createElement(React.Fragment, null,
                error && React.createElement(PHXBannerWithCard, { className: 'mb-4', description: error, hideCloseButton: true, show: true, type: 'danger' }),
                React.createElement(PHXUploadFile, { fileName: fileName, fileType: 'excel', handleFileChange: handleFileChange, type: EUploadType.TO_CLIENT }))),
            step === 2 && React.createElement(PreviewUser, { invalidList: invalidList, target: target, validList: validList }),
            step === 3 && React.createElement(ConfirmUpload, { totalInvalidList: invalidList.length, totalValidList: validList.length }))));
}
//# sourceMappingURL=modal-import-user.js.map