import { ClusterOutlined, EditOutlined, ReadOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import {
    ModalForm,
    PageContainer,
    ProForm,
    ProFormDigit,
    ProFormSwitch,
    ProFormTextArea,
    ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message, Space, Tag, theme, Typography, Tabs, Card, Switch } from 'antd';
import React, { useState } from 'react';
import { queryAgentList, updateAgentConfig, getAgentPrompt, querySkillList } from '@/services/agent';
import MarkdownEditor from '@/components/MarkdownEditor';
import type { AgentItem, SkillItem } from './data';

const { Text } = Typography;

const AgentManager: React.FC = () => {
    const { token } = theme.useToken();
    const intl = useIntl();
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [currentAgent, setCurrentAgent] = useState<AgentItem | null>(null);

    const agentColumns: any[] = [
        {
            title: intl.formatMessage({ id: 'pages.agent.name', defaultMessage: 'Agent 名称' }),
            dataIndex: 'name',
            key: 'name',
            render: (text: string) => <Text strong>{text}</Text>,
        },
        {
            title: intl.formatMessage({ id: 'pages.agent.mode', defaultMessage: '运行模式' }),
            dataIndex: 'mode',
            key: 'mode',
            valueEnum: {
                primary: { text: 'Primary (PM)', status: 'Success' },
                subagent: { text: 'SubAgent', status: 'Default' },
            },
            render: (_: any, record: AgentItem) => (
                <Tag color={record.mode === 'primary' ? 'purple' : 'blue'}>
                    {record.mode.toUpperCase()}
                </Tag>
            ),
        },
        {
            title: intl.formatMessage({ id: 'pages.agent.temperature', defaultMessage: '核温' }),
            dataIndex: 'temperature',
            key: 'temperature',
            search: false,
        },
        {
            title: intl.formatMessage({ id: 'pages.agent.tools', defaultMessage: '工具权限' }),
            dataIndex: 'tools',
            key: 'tools',
            search: false,
            render: (tools: any) => (
                <Space>
                    {tools.write && <Tag color="green">Write</Tag>}
                    {tools.edit && <Tag color="cyan">Edit</Tag>}
                    {tools.bash && <Tag color="orange">Bash</Tag>}
                    {!tools.write && !tools.edit && !tools.bash && <Tag>Read Only</Tag>}
                </Space>
            ),
        },
        {
            title: intl.formatMessage({ id: 'common.action', defaultMessage: '操作' }),
            valueType: 'option',
            key: 'option',
            render: (_: any, record: AgentItem) => [
                <a
                    key="edit"
                    onClick={async () => {
                        const res = await getAgentPrompt(record.key);
                        setCurrentAgent({
                            ...record,
                            promptContent: res.data
                        });
                        setEditModalVisible(true);
                    }}
                >
                    <EditOutlined /> {intl.formatMessage({ id: 'common.config', defaultMessage: '配置' })}
                </a>,
            ],
        },
    ];

    const skillColumns: any[] = [
        {
            title: intl.formatMessage({ id: 'pages.agent.skills.name', defaultMessage: '技能名称' }),
            dataIndex: 'name',
            key: 'name',
            render: (text: string) => <Text strong>{text}</Text>,
        },
        {
            title: intl.formatMessage({ id: 'pages.agent.skills.description', defaultMessage: '描述' }),
            dataIndex: 'description',
            key: 'description',
        },
        {
            title: intl.formatMessage({ id: 'pages.agent.skills.status', defaultMessage: '状态' }),
            dataIndex: 'isEnabled',
            key: 'isEnabled',
            render: (enabled: boolean) => (
                <Tag color={enabled ? 'green' : 'default'}>
                    {enabled
                        ? intl.formatMessage({ id: 'pages.agent.skills.enabled', defaultMessage: '已启用' })
                        : intl.formatMessage({ id: 'pages.agent.skills.disabled', defaultMessage: '未启用' })}
                </Tag>
            ),
        },
        {
            title: intl.formatMessage({ id: 'common.action', defaultMessage: '操作' }),
            valueType: 'option',
            key: 'option',
            render: (_: any, record: SkillItem) => [
                <Switch
                    key="toggle"
                    checked={record.isEnabled}
                    onChange={() => message.info(intl.formatMessage({ id: 'pages.agent.skills.toggle.mock', defaultMessage: 'Mock: 切换技能状态' }))}
                />
            ],
        },
    ];

    return (
        <PageContainer>
            <Tabs
                defaultActiveKey="agents"
                items={[
                    {
                        key: 'agents',
                        label: (
                            <span>
                                <ClusterOutlined />
                                <FormattedMessage id="pages.agent.tabs.agents" defaultMessage="Agents 管理" />
                            </span>
                        ),
                        children: (
                            <ProTable<AgentItem>
                                headerTitle={
                                    <Space>
                                        <ClusterOutlined style={{ color: token.colorPrimary }} />
                                        <FormattedMessage id="pages.agent.title" defaultMessage="Agent 列表" />
                                    </Space>
                                }
                                columns={agentColumns}
                                request={queryAgentList}
                                rowKey="key"
                                search={{
                                    layout: 'vertical',
                                    defaultCollapsed: false,
                                    style: {
                                        background: token.colorBgContainer,
                                        padding: token.padding,
                                        borderRadius: token.borderRadius,
                                        marginBottom: token.marginLG,
                                    },
                                }}
                                pagination={{ defaultPageSize: 10 }}
                            />
                        ),
                    },
                    {
                        key: 'skills',
                        label: (
                            <span>
                                <SafetyCertificateOutlined />
                                <FormattedMessage id="pages.agent.tabs.skills" defaultMessage="Skills 管理" />
                            </span>
                        ),
                        children: (
                            <ProTable<SkillItem>
                                headerTitle={intl.formatMessage({ id: 'pages.agent.skills.title', defaultMessage: '团队技能中心' })}
                                columns={skillColumns}
                                request={querySkillList}
                                rowKey="id"
                                search={false}
                            />
                        ),
                    },
                ]}
            />

            <ModalForm
                title={`配置 Agent: ${currentAgent?.name}`}
                visible={editModalVisible}
                onVisibleChange={setEditModalVisible}
                initialValues={currentAgent || {}}
                onFinish={async (values) => {
                    await updateAgentConfig({ key: currentAgent?.key, ...values });
                    message.success(intl.formatMessage({ id: 'common.success.save.mock', defaultMessage: '配置已保存 (Mock 模式)' }));
                    return true;
                }}
                modalProps={{
                    destroyOnHidden: true,
                    width: 1000,
                }}
            >
                <ProFormDigit
                    label={intl.formatMessage({ id: 'pages.agent.temperature', defaultMessage: '核温 (Temperature)' })}
                    name="temperature"
                    min={0}
                    max={1}
                    fieldProps={{ step: 0.1 }}
                />
                <Space size="large" style={{ marginBottom: 24 }}>
                    <ProFormSwitch label={intl.formatMessage({ id: 'pages.agent.tools.write', defaultMessage: 'Write 权限' })} name={['tools', 'write']} />
                    <ProFormSwitch label={intl.formatMessage({ id: 'pages.agent.tools.edit', defaultMessage: 'Edit 权限' })} name={['tools', 'edit']} />
                    <ProFormSwitch label={intl.formatMessage({ id: 'pages.agent.tools.bash', defaultMessage: 'Bash 权限' })} name={['tools', 'bash']} />
                </Space>

                <ProForm.Item
                    label={intl.formatMessage({ id: 'pages.agent.prompt', defaultMessage: '提示词内容' })}
                    name="promptContent"
                >
                    <MarkdownEditor height={500} />
                </ProForm.Item>
            </ModalForm>
        </PageContainer>
    );
};

export default AgentManager;
