import React, { useEffect, useState } from 'react';
import { Modal, Table, Button, Form, Input, Space, message, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { RoleTagResponse, RoleTagRequest } from '../types';
import { getAllTags, createRoleTag, updateRoleTag, deleteRoleTag } from '../service';

interface TagModalProps {
    visible: boolean;
    onCancel: () => void;
    onSuccess: () => void;
}

const TagModal: React.FC<TagModalProps> = ({
    visible,
    onCancel,
    onSuccess
}) => {
    const [form] = Form.useForm();
    const [tags, setTags] = useState<RoleTagResponse[]>([]);
    const [loading, setLoading] = useState(false);
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [editingTag, setEditingTag] = useState<RoleTagResponse | null>(null);

    useEffect(() => {
        if (visible) {
            loadTags();
        }
    }, [visible]);

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

    const handleAdd = () => {
        setEditingTag(null);
        form.resetFields();
        setEditModalVisible(true);
    };

    const handleEdit = (record: RoleTagResponse) => {
        setEditingTag(record);
        form.setFieldsValue(record);
        setEditModalVisible(true);
    };

    const handleDelete = async (id: number) => {
        try {
            await deleteRoleTag(id);
            message.success('删除成功');
            loadTags();
        } catch (error) {
            message.error('删除失败');
        }
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            if (editingTag) {
                await updateRoleTag(editingTag.id, values);
                message.success('更新成功');
            } else {
                await createRoleTag(values);
                message.success('创建成功');
            }
            setEditModalVisible(false);
            loadTags();
        } catch (error) {
            message.error('操作失败');
        }
    };

    const columns = [
        {
            title: '标签名称',
            dataIndex: 'name',
            key: 'name',
            render: (text: string, record: RoleTagResponse) => (
                <Tag color={record.color}>{text}</Tag>
            )
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true
        },
        {
            title: '操作',
            key: 'action',
            width: 160,
            render: (_: any, record: RoleTagResponse) => (
                <Space>
                    <Button
                        type="link"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ];

    return (
        <>
            <Modal
                title="标签管理"
                open={visible}
                onCancel={onCancel}
                footer={null}
                width={800}
            >
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                        新建标签
                    </Button>
                </div>

                <Table
                    columns={columns}
                    dataSource={tags}
                    rowKey="id"
                    loading={loading}
                    pagination={false}
                />
            </Modal>

            <Modal
                title={editingTag ? '编辑标签' : '新建标签'}
                open={editModalVisible}
                onOk={handleSubmit}
                onCancel={() => setEditModalVisible(false)}
            >
                <Form
                    form={form}
                    layout="vertical"
                >
                    <Form.Item
                        name="name"
                        label="标签名称"
                        rules={[{ required: true, message: '请输入标签名称' }]}
                    >
                        <Input placeholder="请输入标签名称" />
                    </Form.Item>

                    <Form.Item
                        name="color"
                        label="标签颜色"
                        rules={[{ required: true, message: '请输入标签颜色' }]}
                    >
                        <Input type="color" style={{ width: 60 }} />
                    </Form.Item>

                    <Form.Item
                        name="description"
                        label="描述"
                    >
                        <Input.TextArea rows={4} placeholder="请输入描述" />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default TagModal; 