import React, { useEffect, useState } from 'react';
import { Modal, Select, message, Spin } from 'antd';
import type { RoleTagResponse } from '../types';
import { getAllTags, assignTags } from '../service';

interface AssignTagModalProps {
    visible: boolean;
    roleId: number;
    onCancel: () => void;
    onSuccess: () => void;
    selectedTags?: RoleTagResponse[];
}

const AssignTagModal: React.FC<AssignTagModalProps> = ({
    visible,
    roleId,
    onCancel,
    onSuccess,
    selectedTags = []
}) => {
    const [loading, setLoading] = useState(false);
    const [allTags, setAllTags] = useState<RoleTagResponse[]>([]);
    const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);

    useEffect(() => {
        if (visible) {
            loadTags();
            setSelectedTagIds(selectedTags.map(tag => tag.id));
        }
    }, [visible, selectedTags]);

    const loadTags = async () => {
        try {
            setLoading(true);
            const tags = await getAllTags();
            setAllTags(tags);
        } catch (error) {
            message.error('获取标签列表失败');
        } finally {
            setLoading(false);
        }
    };

    const handleOk = async () => {
        try {
            await assignTags(roleId, selectedTagIds);
            message.success('标签分配成功');
            onSuccess();
        } catch (error) {
            message.error('标签分配失败');
        }
    };

    return (
        <Modal
            title="分配标签"
            open={visible}
            onCancel={onCancel}
            onOk={handleOk}
            width={500}
            styles={{
                body: {
                    padding: '12px'
                }
            }}
        >
            <Spin spinning={loading}>
                <Select
                    mode="multiple"
                    style={{ width: '100%' }}
                    placeholder="请选择标签"
                    value={selectedTagIds}
                    onChange={setSelectedTagIds}
                    options={allTags.map(tag => ({
                        label: tag.name,
                        value: tag.id
                    }))}
                />
            </Spin>
        </Modal>
    );
};

export default AssignTagModal; 