import React, { useEffect, useRef, useState } from 'react';
import { Modal, Form, Input, Select, Upload, message, Image, Button, Radio, Tooltip } from 'antd';
import { InboxOutlined, InfoCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import LocalStorage from '@/LocalStorage';

const { TextArea } = Input;
const { Option } = Select;
const { Dragger } = Upload;
import DataManagementMode from '../../datasetManagement/components/dataManagementMode';

import aiwj from '@/assets/public/aiwj.png';
import model from '@/assets/public/model.png';
import { apis } from '@/apis';

interface Props {
    openCreateTaskMode: boolean;
    onCancel: () => void;
    onSubmit?: (values: any) => void;
}

const EVAL_TYPES = [
    { label: '自动评测', value: 'auto' },
    { label: '人工评测', value: 'manual' },
];

const MODELS = [
    { label: 'gpt-4', value: 'gpt-4' },
    { label: 'gpt-3.5', value: 'gpt-3.5' },
];


const CreateTaskMode: React.FC<Props> = ({ openCreateTaskMode, onCancel, onSubmit }) => {
    type AppTypeList = {
        label: string,
        value: string,
        children: {
            label: string,
            value: string,
        }[],
    }[];
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState<any[]>([]);
    const [modelType, setModelType] = React.useState<AppTypeList>([]); // 选择模型
    const [ragOptions, setRagOptions] = useState<Array<{ label: string; value: string }>>([]);// RAG应用
    const [evaluationDataOptions, setSelecteevaluationData] = useState<Array<{ label: string; value: string }>>([]);// 评测数据
    const [radioModel, setRadioModel] = useState<string>('Qwen3-30B');
    const reviewRag = useRef('');
    useEffect(() => {
        if (!openCreateTaskMode) {
            form.resetFields();
            setFileList([]);
        }
    }, [openCreateTaskMode, form]);
    useEffect(() => {
        if (openCreateTaskMode) {
            fetchRagList();
            fetchAppmodelType('');
        }
    }, [openCreateTaskMode]);

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            console.log('Form Values:', values);
            const params = {
                ...values,
                model: radioModel,
            };
            const res: any = await apis.createEvaluationApi(params);
            if (res.code === 200) {
                message.success('创建任务成功');
                form.resetFields();
            }
            onCancel();
        } catch (err) {
            // 校验失败，表单将显示错误
        }
    };
    const fetchRagList = async () => {
        // Implementation for fetching RAG list
        const userInfo = LocalStorage.getUserInfo();
        const userId = (userInfo?.id ?? '').toString();
        const res = await apis.fetchTakaiAppList({
            pageSize: 300,
            pageNum: 1,
            userId: userId,
            isCollect: null,
            typeId: null,
        })
        if (res.code !== 200) return;
        const options = res.rows.map((item: any) => ({ label: item.name, value: item.appId }));
        setRagOptions(options);
    };
    // 获取向量化模型
    const fetchAppmodelType = async (id: string) => {
        try {
            const res = await apis.fetchTakaiAppTypeList('model_type');
            const list = res.data.map((item: any) => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue,
                }
            });
            setModelType(list);
            if (!id) {
                form.setFieldsValue({
                    // visible: list[0].value === '0' ? true : false
                });
            }
        } catch (error: any) {
            console.error(error);
        }
    }
    // 获取评测数据
    const onFetchDatasetSelectList = async (appId: any) => {
        try {
            const res: any = await apis.fetchDatasetSelectList(
                {
                    appId: appId,
                }
            );
            if (res.code === 200) {
                const options = res.data.map((item: any) => ({ label: item.name, value: item.id }));
                setSelecteevaluationData(options);

            }
        } catch (error) {
            console.error('Error fetching dataset select list:', error);
        }
    };

    const [openDataManagementMode, setOpenDataManagementMode] = useState(false);

    return (
        <Modal
            open={openCreateTaskMode}
            title="创建评测任务"
            onCancel={onCancel}
            onOk={handleOk}
            width={'600px'}
            footer={
                <div>
                    <Button
                        className="mr-2 px-4 py-2 bg-gray-200 rounded"
                        onClick={onCancel}
                    >
                        取消
                    </Button>
                    <Button
                        type='primary'
                        className="px-4 py-2 bg-blue-600 text-white rounded"
                        onClick={handleOk}
                    >
                        确定
                    </Button>
                </div>
            }
            cancelText="取消"
        >
            <Form form={form} layout="vertical">
                <Form.Item
                    name="taskName"
                    label="任务名称"
                    rules={[{ required: true, message: '请输入任务名称' }]}
                >
                    <Input placeholder="输入任务名称" />
                </Form.Item>

                <Form.Item name="taskDescription" label="任务描述">
                    <TextArea rows={4} placeholder="任务描述（可选）" />
                </Form.Item>

                <Form.Item name="evaluationType" label="评测类型" initialValue={'RAG评测'}>
                    <div className='flex items-center gap-2 p-2 border rounded-md bg-blue-100  border-blue-300 cursor-pointer'>
                        <Image width={18} height={18} src={aiwj} preview={false} className='mt-[-8px]' />
                        <div className='text-xs'>
                            <p>RAG评测</p>
                            <p> 通过上传验证集自动测和打分，生成评测报告 </p>
                        </div>
                    </div>
                </Form.Item>
                <Form.Item name="reviewRag" label="评测RAG" 
                    rules={[{ required: true, message: '请选择RAG应用' }]}
                >
                    <Select onChange={(e) => {
                        reviewRag.current = e;
                        setSelecteevaluationData([]);
                        form.setFieldsValue({
                            evaluationData: '',
                        });
                        onFetchDatasetSelectList(e)
                    }} >
                        {ragOptions.map(t => (
                            <Option key={t.value} value={t.value}>
                                {t.label}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item name="model" label="选择模型" initialValue={'Qwen3-30B'}>
                    <div className='flex items-center justify-between'>
                        <div className={'flex items-center gap-2 p-2 border rounded-md cursor-pointer w-[50%]' + (radioModel === 'Qwen3-30B' ? ' bg-blue-100  border-blue-300' : ' ml-0')}
                            onClick={() => setRadioModel('Qwen3-30B')}>
                            <Image src={model} width={50} preview={false} className='mt-[-8px]' />
                            <div className='text-xs'>
                                <p>Qwen3-30B</p>
                                <p>Qwen3-30-A3B是阿里通义千问推出的混合专家模型，支持思考/非思考双模式切换。</p>
                            </div>
                        </div>

                        {/* <div className={'flex items-center gap-2 p-2 border rounded-md  cursor-pointer ml-3' + (radioModel === 'Qwen2-72B' ? ' bg-blue-100  border-blue-300' : ' ml-0')}
                            onClick={() => setRadioModel('Qwen2-72B')}>
                            <Image width={50} src={model} preview={false} className='mt-[-8px]' />
                            <div className='text-xs'>
                                <p>Qwen2-72B</p>
                                <p>Qwen2-72B-Instruct是Qwen2.5系列的指令调优版本，在数学、编程等复杂任务上表现卓越。</p>
                            </div>
                        </div> */}
                    </div>
                </Form.Item>
                <Form.Item name="embeddingId"
                    rules={[{ required: true, message: '请选择向量化模型' }]}
                    label={
                        <span>
                            向量化模型
                            <Tooltip
                                title="提示：此向量化模型只针对下方评测数据"
                                placement="right"
                            >
                                <InfoCircleOutlined style={{ marginLeft: 4, color: '#1890ff' }} />
                            </Tooltip>
                        </span>
                    }
                >
                    {
                        <Select
                            style={{ width: '100%' }}
                            placeholder='请选择向量化模型'
                            allowClear={true}
                        >
                            {
                                modelType.map((item, index) => {
                                    return <Option value={item.value} key={index}>
                                        {item.label}
                                    </Option>
                                })
                            }
                        </Select>
                    }
                </Form.Item>
                <div className="flex gap-2">

                    <Form.Item name="evaluationData" label="评测数据" style={{width:'100%'}}
                        rules={[{ required: true, message: '请选择评测数据' }]}
                    >
                        <Select placeholder="请先选择评测RAG应用">
                            {evaluationDataOptions.map(t => (
                                <Option key={t.value} value={t.value}>
                                    {t.label}
                                </Option>
                            ))}
                        </Select>

                    </Form.Item>
                    <Button className='mt-[30px]' type="primary" icon={<PlusCircleOutlined />} onClick={() => {
                        if(reviewRag.current){
                            setOpenDataManagementMode(true)
                        }else{
                            message.error('请先选择评测RAG应用')
                        }
                    }} />
                </div>

                <Form.Item name="flg" label="立即执行" initialValue={true}
                    rules={[{ required: true, message: '请选择是否立即执行' }]}
                >
                    <Radio.Group>
                        <Radio value={true}>是</Radio>
                        <Radio value={false}>否</Radio>
                    </Radio.Group>
                </Form.Item>
            </Form>
            {openDataManagementMode && <DataManagementMode openDataManagementMode={openDataManagementMode}
                reviewRagdata={reviewRag.current}
                onSubmit={(values) => {
                    setSelecteevaluationData((pre) => {
                        return [...pre, {
                            label: values.name,
                            value: values.id
                        }]
                    })
                    form.setFieldsValue({
                        evaluationData: values.id,
                    });
                    console.log('values---- 评测历史', values)
                }}
                onCancel={() => { setOpenDataManagementMode(false); }} />}
        </Modal>
    );
};

export default CreateTaskMode;
