import * as React from 'react';
import { Drawer, Form, Input, Select, Cascader, Tag, InputNumber, ColorPicker, Button, Space, Switch, Divider, message, Radio } from 'antd';
import { PlusCircleOutlined, MinusCircleOutlined, CloseCircleOutlined, LinkOutlined } from '@ant-design/icons';
import * as AllIcons from '@ant-design/icons';
import { Globe, Lock } from 'lucide-react';
import IconPicker from './IconPicker';
import VipSelector from './VipSelector';
import './DrawerForm.scss';

interface Step1DrawerProps {
    open: boolean;
    onClose: () => void;
    form: any;
    appTypeList: any[];
    appVisibleList: any[];
    appProjectList: any[];
    isAppPro: boolean;
    visibleFlag: string | number;
    vipList: any[];
    userInfo: any;
    inputs: Array<{ id: number; value: string }>;
    selectedIcon: string | null;
    previewBg: string;
    onAppChange: (typeId: number) => void;
    onVisibleChange: (value: any) => void;
    onRemoveVip: (userId: string) => void;
    onVipConfirm: (users: any[]) => void;
    onNext: () => void;
    onIconChange: (icon: string | null) => void;
    onBgColorChange: (color: string) => void;
    onInputsChange: (inputs: Array<{ id: number; value: string }>) => void;
}

interface InputItem {
    id: number;
    value: string;
}

const Step1Drawer: React.FC<Step1DrawerProps> = (props) => {
    const {
        open,
        onClose,
        form,
        appTypeList,
        appVisibleList,
        appProjectList,
        isAppPro,
        visibleFlag,
        vipList,
        userInfo,
        inputs,
        selectedIcon,
        previewBg,
        onAppChange,
        onVisibleChange,
        onRemoveVip,
        onVipConfirm,
        onNext,
        onIconChange,
        onBgColorChange,
        onInputsChange,
    } = props;

    const [iconPickerVisible, setIconPickerVisible] = React.useState(false);
    const [vipSelectorVisible, setVipSelectorVisible] = React.useState(false);

    const getContrastColor = (hex: string) => {
        const c = hex.replace('#', '');
        const r = parseInt(c.substring(0, 2), 16);
        const g = parseInt(c.substring(2, 4), 16);
        const b = parseInt(c.substring(4, 6), 16);
        const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        return luminance > 0.6 ? '#000' : '#fff';
    };

    const presetColors = ['#1677ff', '#52c41a', '#fa8c16', '#f5222d', '#722ed1', '#ffffff', '#f0f0f0'];
    const presetItems = [{ label: '', colors: presetColors }];

    const addInput = () => {
        const newId = inputs.length + 1;
        onInputsChange([...inputs, { id: newId, value: '' }]);
    };

    const delInput = (id: number) => {
        if (inputs.length <= 1) {
            message.warning("至少保留 1 个预设问题");
            return;
        }
        onInputsChange(inputs.filter(input => input.id !== id));
    };

    const handleChange = (id: number, value: string) => {
        const newInputs = inputs.map(input => (input.id === id ? { ...input, value } : input));
        onInputsChange(newInputs);
        form.setFieldValue('questionList', newInputs.map(input => input.value));
    };

    const handleNext = async () => {
        try {
            const values = await form.validateFields(['name', 'desc', 'appProId', 'iconType']);
            form.setFieldValue('questionList', inputs.map(input => input.value));
            onNext();
        } catch (error) {
            console.error('验证失败:', error);
        }
    };

    return (
        <>
            <Drawer
                title="创建 RAG 应用"
                placement="right"
                width={720}
                open={open}
                onClose={onClose}
                className='rag-drawer'
                destroyOnClose
                extra={
                    <Space>
                        <Button onClick={onClose}>取消</Button>
                        <Button type="primary" onClick={handleNext}>下一步</Button>
                    </Space>
                }
            >
                <div className='drawer-form-container'>
                    {/* 图标选择区域 */}
                    <div className='icon-select-section'>
                        <div className='icon-preview-wrapper'>
                            <div
                                className='icon-preview-box'
                                style={{ background: previewBg }}
                            >
                                {selectedIcon ? (() => {
                                    const C = (AllIcons as any)[selectedIcon];
                                    const iconColor = getContrastColor(previewBg);
                                    return C ? <C style={{ fontSize: 32, color: iconColor }} /> : <span>{selectedIcon}</span>;
                                })() : (
                                    <span className='icon-preview-placeholder'>预览</span>
                                )}
                            </div>
                        </div>
                        <div className='icon-actions'>
                            <Button type="link" onClick={() => setIconPickerVisible(true)}>
                                选择图标
                            </Button>
                            <Space size="small">
                                <span className='color-label'>背景色：</span>
                                <ColorPicker
                                    presets={presetItems}
                                    value={previewBg}
                                    onChange={(color) => {
                                        const hex = color.toHexString?.() || color?.toString?.() || previewBg;
                                        onBgColorChange(hex);
                                        form.setFieldValue('iconColor', hex);
                                    }}
                                />
                            </Space>
                        </div>
                    </div>

                    <Divider className='section-divider'>基础设置</Divider>

                    <div className='form-section'>
                        <Form.Item
                            shouldUpdate
                            children={() => {
                                return (
                                    <>
                                        <Form.Item
                                            label='应用名称'
                                            name='name'
                                            rules={[{ required: true, message: '请输入应用名称' }]}
                                            extra='尽量概括应用的主要功能'
                                        >
                                            <Input placeholder="请输入应用名称" maxLength={50} showCount />
                                        </Form.Item>

                                        <Form.Item
                                            label='应用类型'
                                            name='typeId'
                                            extra='应用的实际分类'
                                        >
                                            <Select placeholder='请选择应用类型' allowClear>
                                                {appTypeList.map((item) => (
                                                    <Select.Option key={item.value} value={item.value}>
                                                        {item.label}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        </Form.Item>

                                        {isAppPro && (
                                            <Form.Item
                                                label='所属项目'
                                                name='appProId'
                                                rules={[{ required: true, message: '请选择项目' }]}
                                                extra='应用所属的项目'
                                            >
                                                <Cascader
                                                    options={appProjectList}
                                                    placeholder="请选择项目"
                                                    showSearch
                                                />
                                            </Form.Item>
                                        )}

                                        <Form.Item
                                            label='可见性'
                                            name='visible'
                                            extra='公开应用后，所有用户均可使用；私有应用仅限自己和指定用户使用'
                                        >
                                            <Radio.Group 
                                                buttonStyle="solid" 
                                                className='visibility-radio'
                                                onChange={(e) => onVisibleChange(e.target.value)}
                                            >
                                                <Radio.Button value='0'>
                                                    <Globe size={16} style={{ marginRight: 4 }} />
                                                    公开
                                                </Radio.Button>
                                                <Radio.Button value='1'>
                                                    <Lock size={16} style={{ marginRight: 4 }} />
                                                    私有
                                                </Radio.Button>
                                            </Radio.Group>
                                        </Form.Item>

                                        {userInfo?.tenantId === '000000' && (visibleFlag === '0' || visibleFlag === 0) && (
                                            <Form.Item
                                                label='集团公开'
                                                name='groupVisible'
                                                valuePropName='checked'
                                                extra='集团下所有用户均可使用该应用'
                                            >
                                                <Switch />
                                            </Form.Item>
                                        )}

                                        {/*<Form.Item*/}
                                        {/*    label='显示顺序'*/}
                                        {/*    name='sort'*/}
                                        {/*    extra='用于应用广场的显示顺序'*/}
                                        {/*>*/}
                                        {/*    <InputNumber placeholder="请输入显示顺序" style={{ width: '100%' }} />*/}
                                        {/*</Form.Item>*/}

                                        {(visibleFlag === '1' || visibleFlag === 1) && (
                                            <Form.Item
                                                label='指定用户'
                                                extra='私有应用的指定用户'
                                            >
                                                <div className='tags-info'>
                                                    <div className='tags-list'>
                                                        {vipList.map((item: any) => (
                                                            <Tag
                                                                key={item.userId}
                                                                color="blue"
                                                                closable
                                                                onClose={(e) => {
                                                                    e?.preventDefault();
                                                                    onRemoveVip(item.userId);
                                                                }}
                                                            >
                                                                {item.userName}
                                                            </Tag>
                                                        ))}
                                                    </div>
                                                    <Space>
                                                        {vipList.length > 0 && (
                                                            <CloseCircleOutlined
                                                                className='clear-all'
                                                                onClick={() => onRemoveVip('all')}
                                                            />
                                                        )}
                                                        <Button type="primary" variant="outlined" onClick={() => setVipSelectorVisible(true)}>
                                                            选择用户
                                                        </Button>
                                                    </Space>
                                                </div>
                                            </Form.Item>
                                        )}

                                        <Form.Item
                                            label='应用描述'
                                            name='desc'
                                            rules={[{ required: true, message: '请输入应用描述' }]}
                                            extra='对当前应用功能的描述，使用户更了解应用的使用范围'
                                        >
                                            <Input.TextArea
                                                showCount
                                                maxLength={500}
                                                placeholder="请输入应用描述"
                                                rows={4}
                                            />
                                        </Form.Item>
                                    </>
                                );
                            }}
                        />
                    </div>

                    <Divider className='section-divider'>引导问题</Divider>

                    <div className='preset-questions'>
                        <div className='questions-list'>
                            {inputs.map(input => (
                                <div key={input.id} className='question-item'>
                                    <label>问题 {input.id}</label>
                                    <Input
                                        className='question-input'
                                        type="text"
                                        value={input.value}
                                        onChange={e => handleChange(input.id, e.target.value)}
                                        placeholder="请输入引导问题"
                                    />
                                    <div className='question-actions'>
                                        <PlusCircleOutlined className='question-icon add' onClick={addInput} />
                                        <MinusCircleOutlined className='question-icon del' onClick={() => delInput(input.id)} />
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </Drawer>

            {/* IconPicker 弹窗 */}
            <IconPicker
                open={iconPickerVisible}
                onClose={() => setIconPickerVisible(false)}
                onSelect={(iconName) => {
                    onIconChange(iconName);
                    form.setFieldValue('iconType', iconName);
                }}
                value={selectedIcon}
            />

            {/* VIP 用户选择弹窗 */}
            <VipSelector
                open={vipSelectorVisible}
                onClose={() => setVipSelectorVisible(false)}
                onConfirm={(users) => {
                    onVipConfirm(users);
                    setVipSelectorVisible(false);
                }}
                existingUsers={vipList}
            />
        </>
    );
};

export default Step1Drawer;
