import * as React from 'react';
import { 
    Form, Input, Select, InputNumber, Radio, Switch, Row, Col, Slider, 
    Space, Button, Tooltip, message, Divider, Typography, Tag 
} from 'antd';
import { ArrowLeftOutlined, InfoCircleOutlined, LinkOutlined } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import { Splitter } from 'antd';
import './style.scss';

interface KnowledgeItem {
    index_type_id: number;
    knowledge_id: string;
}

interface RAGConfig {
    param_desc: string;
    show_recall_result: boolean;
    recall_method: string;
    rerank_status: boolean;
    rerank_model_name: string;
    slice_config_type: string;
    slice_count: number;
    is_multi_round: boolean;
    multi_round: number;
}

interface Step2ConfigProps {
    form: any;
    knowledgeList: any[];
    modelList: any[];
    rerankModelList: any[];
    topPValue: number;
    tempValue: number;
    isVisible: boolean;
    isVisibleCus: boolean;
    isVisibleSlice: boolean;
    isDeepThinkVisible: boolean;
    isMultiRound: boolean;
    automatic: boolean;
    name: string;
    onTopPChange: (value: number) => void;
    onTempChange: (value: number) => void;
    onModelChange: (value: string) => void;
    onRecallMethodChange: (e: RadioChangeEvent) => void;
    onSliceCountChange: (value: string) => void;
    onMultiRoundChange: (checked: boolean) => void;
    onAutomaticChange: (checked: boolean) => void;
    onBack: () => void;
    onSubmit: () => void;
    onSave?: () => void;
    createFlag: boolean;
    appId?: string;
}

const Step2Config: React.FC<Step2ConfigProps> = (props) => {
    const {
        form,
        knowledgeList,
        modelList,
        rerankModelList,
        topPValue,
        tempValue,
        isVisible,
        isVisibleCus,
        isVisibleSlice,
        isDeepThinkVisible,
        isMultiRound,
        automatic,
        name,
        onTopPChange,
        onTempChange,
        onModelChange,
        onRecallMethodChange,
        onSliceCountChange,
        onMultiRoundChange,
        onAutomaticChange,
        onBack,
        onSubmit,
        onSave,
        createFlag,
        appId,
    } = props;

    const MAX_COUNT = 5;

    const tagRender = (props: any) => {
        const { label, value, closable, onClose } = props;
        return (
            <Tag
                color="blue"
                closable={closable}
                onClose={onClose}
                style={{ marginRight: 4 }}
            >
                {label}
                <LinkOutlined 
                    style={{
                        marginLeft: 4,
                        fontSize: 12,
                        cursor: 'pointer',
                        color: '#FF9500',
                        fontWeight: 'bold',
                    }}
                    onMouseUp={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        // TODO: 跳转到知识库详情
                    }}
                />
            </Tag>
        );
    };

    return (
        <div className='create-step2'>
            <div className='step2-header'>
                <Button className='btn-back' icon={<ArrowLeftOutlined />} onClick={onBack}>
                    上一步
                </Button>
                <Space>
                    {appId && onSave && (
                        <Tooltip title='保存'>
                            <Button onClick={onSave}>
                                保存
                            </Button>
                        </Tooltip>
                    )}
                    {createFlag && (
                        <Button type='primary' onClick={onSubmit}>
                            提交应用
                        </Button>
                    )}
                </Space>
            </div>

            <Splitter className='app-splitter' style={{ minHeight: 0 }}>
                <Splitter.Panel defaultSize="35%" className='splitter-panel'>
                    <div className='section-title' style={{ marginBottom: 0 }}>
                        Prompt 编写与参数配置
                        <Tooltip
                            title="Prompt 用于对大模型的回复做出一些列指令和约束。这段 Prompt 不会被用户看到。"
                            placement="right"
                        >
                            <InfoCircleOutlined style={{ marginLeft: '8px', color: '#999', fontSize: '14px' }} />
                        </Tooltip>
                    </div>
                    <div className='prompt-editor'>
                        <div className='prompt-info'>
                            <Typography.Paragraph style={{ fontSize: '12px', lineHeight: '1.6', color: '#999', margin: 0 }}>
                                编写 Prompt 过程中可以引入 2 项变量：
                                <span className='variable-highlight'>{'{{知识}}'}</span>
                                代表知识库中检索到的知识内容，
                                <span className='variable-highlight'>{'{{用户}}'}</span>
                                代表用户输入的内容。您可以在编写 Prompt 过程中将变量拼接在合适的位置。
                            </Typography.Paragraph>
                        </div>
                        <Form.Item 
                            name='prompt'
                            tooltip='当前应用会遵循提示词进行输出'
                            rules={[{ required: true, message: '提示词不能为空' }]}
                        >
                            <Input.TextArea
                                placeholder="提示词"
                                rows={50}
                                className='prompt-textarea'
                            />
                        </Form.Item>
                    </div>
                </Splitter.Panel>

                <Splitter.Panel defaultSize="30%" className='splitter-panel param-config'>
                    <div className='config-header'>
                        <span>参数配置 {name || '问答应用'}</span>
                        <Switch 
                            checkedChildren="手动" 
                            unCheckedChildren="自动" 
                            checked={!automatic}
                            onChange={onAutomaticChange}
                        />
                    </div>

                    <Form.Item
                        label='引用知识库'
                        tooltip='应用对应的知识库可以选择多个，点击链接可以查看知识库中的文件'
                        name='knowledge_ids'
                        rules={[{ required: true, message: '知识库不能为空' }]}
                    >
                        <Select
                            mode='multiple'
                            maxCount={MAX_COUNT}
                            showSearch
                            filterOption={(input, option) => 
                                (option?.children as unknown as string)?.toLowerCase()?.includes(input.toLowerCase())
                            }
                            className='form-input'
                            placeholder='请选择需要引用的知识库'
                            tagRender={tagRender}
                        >
                            {knowledgeList.map((item) => (
                                <Select.Option key={item.value} value={item.value}>
                                    {item.label}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label='调用模型'
                        tooltip='应用使用的模型'
                        name="model"
                        rules={[{ required: true, message: '模型不能为空' }]}
                    >
                        <Select
                            placeholder='请选择模型'
                            className='form-input'
                            onChange={onModelChange}
                        >
                            {modelList.map((item: any, index: number) => (
                                <Select.Option key={index} value={item.value}>
                                    {item.label}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label='max token'
                        name='max_token'
                        tooltip='每次会话输出 的最大 token 数'
                        rules={[{ required: true, message: 'max token 不能为空' }]}
                    >
                        <InputNumber
                            disabled
                            className='form-input'
                        />
                    </Form.Item>

                    {isVisible && (
                        <>
                            {isVisibleCus && automatic && (
                                <Space direction="vertical" style={{ width: '100%' }} size="large">
                                    <Form.Item
                                        label='Top-p'
                                        name='topP'
                                        tooltip='Top-p 参数控制生成文本的多样性，值越大生成的文本越多样化'
                                    >
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Slider
                                                    min={0}
                                                    max={1}
                                                    onChange={onTopPChange}
                                                    value={topPValue}
                                                    step={0.1}
                                                />
                                            </Col>
                                            <Col span={12}>
                                                <InputNumber
                                                    min={0}
                                                    max={1}
                                                    step={0.01}
                                                    value={topPValue}
                                                    onChange={onTopPChange}
                                                    style={{ width: '100%' }}
                                                />
                                            </Col>
                                        </Row>
                                    </Form.Item>

                                    <Form.Item
                                        label='Temperature'
                                        name='temperature'
                                    >
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Slider
                                                    min={0}
                                                    max={1}
                                                    onChange={onTempChange}
                                                    value={tempValue}
                                                    step={0.01}
                                                />
                                            </Col>
                                            <Col span={12}>
                                                <InputNumber
                                                    min={0}
                                                    max={1}
                                                    step={0.01}
                                                    value={tempValue}
                                                    onChange={onTempChange}
                                                    style={{ width: '100%' }}
                                                />
                                            </Col>
                                        </Row>
                                    </Form.Item>
                                </Space>
                            )}

                            <Form.Item
                                label='回答风格'
                                name='param_desc'
                                tooltip='大模型会遵循设置的风格进行回答'
                                rules={[{ required: true, message: '回答风格不能为空' }]}
                            >
                                <Radio.Group buttonStyle="solid" className='form-radio-group'>
                                    <Radio.Button value='strict' onClick={() => {
                                        onTopPChange(0.5);
                                        onTempChange(0.01);
                                    }}>
                                        严谨
                                    </Radio.Button>
                                    <Radio.Button value='moderate' onClick={() => {
                                        onTopPChange(0.7);
                                        onTempChange(0.50);
                                    }}>
                                        适中
                                    </Radio.Button>
                                    <Radio.Button value='flexib' onClick={() => {
                                        onTopPChange(0.9);
                                        onTempChange(0.90);
                                    }}>
                                        发散
                                    </Radio.Button>
                                    {automatic && (
                                        <Radio.Button 
                                            value='custom'
                                            onClick={() => {
                                                onAutomaticChange(true);
                                                onTopPChange(0.1);
                                                onTempChange(0.01);
                                            }}
                                        >
                                            自定义
                                        </Radio.Button>
                                    )}
                                </Radio.Group>
                            </Form.Item>

                            <Form.Item
                                label='展示引用知识'
                                tooltip='是否在回答中展示引用的知识内容'
                                name='show_recall_result'
                                valuePropName='checked'
                            >
                                <Switch />
                            </Form.Item>

                            <Form.Item
                                label='召回方式'
                                tooltip='知识库内容的检索方式'
                                name='recall_method'
                                rules={[{ required: true, message: '召回方式不能为空' }]}
                            >
                                <Radio.Group
                                    onChange={onRecallMethodChange}
                                    options={[
                                        { value: 'embedding', label: '向量化检索' },
                                        { value: 'keyword', label: '关键词检索' },
                                        { value: 'mixed', label: '混合检索' },
                                    ]}
                                />
                            </Form.Item>

                            <Divider orientation="left" style={{ fontSize: '14px', fontWeight: 500 }}>
                                重排方式
                            </Divider>

                            <Form.Item
                                label='Rerank 模型'
                                tooltip='检索结果的重新排序模型'
                                name='rerank_model_name'
                            >
                                <Input disabled />
                            </Form.Item>

                            <Form.Item
                                label='召回切片数量'
                                name='slice_config_type'
                                tooltip='自动模式默认召回 15 个切片，手动模式可自定义召回切片数量'
                                rules={[{ required: true, message: '召回方式不能为空' }]}
                            >
                                <Select
                                    className='form-input'
                                    placeholder='请选择'
                                    onChange={onSliceCountChange}
                                >
                                    <Select.Option value="fixed">手动设置</Select.Option>
                                    <Select.Option value="customized">自动设置</Select.Option>
                                </Select>
                            </Form.Item>

                            {isVisibleSlice && (
                                <Form.Item
                                    label='召回切片数'
                                    tooltip='自定义召回切片的数量'
                                    name='slice_count'
                                    rules={[{ required: true, message: '切片数不能为空' }]}
                                >
                                    <InputNumber 
                                        max={1024} 
                                        changeOnWheel
                                        className='form-input'
                                    />
                                </Form.Item>
                            )}

                            <Form.Item
                                label='是否开启多轮对话'
                                name='is_multi_round'
                                tooltip='开启后支持多轮对话功能'
                                valuePropName='checked'
                            >
                                <Switch checked={isMultiRound} onChange={onMultiRoundChange} />
                            </Form.Item>

                            {isMultiRound && (
                                <Form.Item
                                    label='多轮对话次数'
                                    tooltip='支持上下文对话轮数'
                                    name='multi_round'
                                    rules={[{ required: true, message: '多轮对话次数不能为空' }]}
                                >
                                    <InputNumber 
                                        min={1} 
                                        max={10}
                                        className='form-input'
                                    />
                                </Form.Item>
                            )}
                        </>
                    )}
                </Splitter.Panel>

                <Splitter.Panel defaultSize="35%" className='splitter-panel'>
                    {/* TODO: Chat 预览区域 */}
                    <div style={{ padding: 20, textAlign: 'center', color: '#999' }}>
                        Chat 预览区域（待实现）
                    </div>
                </Splitter.Panel>
            </Splitter>
        </div>
    );
};

export default Step2Config;
