import * as React from 'react';
import { useNavigate } from "react-router-dom";
import { Dropdown, Spin, Tooltip } from 'antd';
import { Chat } from './DeepSeekHomeOnlyChat';
import whiteLogo from "../icons/whiteLogo.png";
import jkxz from "../icons/jkxz.png";
import { useChatStore } from "../store";
import { useMobileScreen } from '../utils';
import api from "@/app/api/api";
import './deepSeekHome.scss';

const DeekSeek: React.FC = () => {
    const chatStore = useChatStore();
    const isMobileScreen = useMobileScreen();

    const navigate = useNavigate();

    const [listLoading, setListLoading] = React.useState(false);
    const [hideTitleOnMobile, setHideTitleOnMobile] = React.useState(false);
    const [activeNavIndex, setActiveNavIndex] = React.useState<number | null>(null);

    type List = {
        title: string,
        children: {
            title: string,
            showMenu: string,
            chatMode: string,
            appId: string,
            children?: List[number]['children'],
        }[],
    }[];

    const [list, setList] = React.useState<List>([
        {
            "children": [
                {
                    "chatMode": "LOCAL",
                    "showMenu": "false",
                    "appId": "2935625422066814976",
                    "title": "公司作业指导书（2023版）"
                },
                {
                    "chatMode": "LOCAL",
                    "showMenu": "false",
                    "appId": "2935200536655695872",
                    "title": "常用验收规范问答"
                },
                {
                    "chatMode": "LOCAL",
                    "showMenu": "false",
                    "appId": "2942568790025965568",
                    "title": "钢结构AI监理师"
                }
            ],
            "title": "专业知识"
        },

        {
            "children": [
                {
                    "chatMode": "LOCAL",
                    "showMenu": "false",
                    "appId": "2919677614293913600",
                    "title": "员工入职小百科"
                },
                {
                    "chatMode": "LOCAL",
                    "showMenu": "false",
                    "appId": "2919668410128666624",
                    "title": "数字系统答疑"
                },
                {
                    "chatMode": "LOCAL",
                    "showMenu": "false",
                    "appId": "2945774476037853184",
                    "title": "企业介绍"
                }
            ],
            "title": "职能管理"
        },
        
        {
            "children": [],
            "title": "项目级应用"
        }
    ]);

    const init = async () => {
        setListLoading(true);
        try {
            const res = await api.get('/deepseek/api/appType');
            setList(res.data);
        } catch (error) {
            console.error(error);
        } finally {
            setListLoading(false);
        }
    }

    React.useEffect(() => {
        chatStore.clearSessions();
        const userInfo = localStorage.getItem('userInfo');

        if (userInfo) {
            init();
        }
    }, []);

    const formatMenuTitle = React.useCallback(
        (title: string) => {
            if (isMobileScreen) {
                return title;
            }
            return title.length > 7 ? `${title.slice(0, 7)}...` : title;
        },
        [isMobileScreen]
    );

    const dropdownAlign = React.useMemo(() => {
        if (isMobileScreen) {
            return undefined;
        }
        return {
            points: ['tl', 'bl'],
            offset: [0, 8],
            overflow: {
                adjustY: false,
                adjustX: true,
            },
        };
    }, [isMobileScreen]);

    return (
        <Spin spinning={listLoading}>
            <div className='deekSeek'>
                <div className='deekSeek-header' style={{ justifyContent: isMobileScreen ? "space-between" : "center" }}>
                    <div
                        style={{
                            display: 'flex',
                            alignItems: 'center',
                            margin: isMobileScreen ? 0 : '0 20px',
                            fontSize: isMobileScreen ? undefined : 14,
                            fontWeight: isMobileScreen ? undefined : 600,
                        }}
                    >
                        <img src={whiteLogo.src} style={{ width: 20, marginRight: isMobileScreen ? 0 : 10 }} />
                        {!isMobileScreen && (
                            <div style={{ whiteSpace: 'nowrap' }}>
                                上海建科
                            </div>
                        )}
                    </div>
                    {
                        list.map((item, index) => {
                            return <Dropdown
                                onOpenChange={(open) => {
                                    if (open) {
                                        setActiveNavIndex(index);
                                    }
                                }}
                                menu={{
                                    items: item.children.map((child, i) => {
                                        return {
                                            key: 'child' + i,
                                            label: <div
                                            className='deekSeek-menuds'
                                                onClick={() => {
                                                    const search = `?showMenu=${child.showMenu}&chatMode=${child.chatMode}&appId=${child.appId}`;
                                                    if (child.appId) {
                                                        navigate({
                                                            pathname: '/knowledgeChat',
                                                            search: search,
                                                        })
                                                    }
                                                }}
                                            >
                                                <Tooltip placement="top" title={child.title}>
                                                    {formatMenuTitle(child.title)}
                                                </Tooltip>
                                            </div>,
                                            children: child.children ? child.children.map((record, ind) => {
                                                return {
                                                    key: 'record' + ind,
                                                    label: (
                                                        <Tooltip placement="bottom" title={record.title}>
                                                            <div
                                                                onClick={() => {
                                                                    const search = `?showMenu=${record.showMenu}&chatMode=${record.chatMode}&appId=${record.appId}`;
                                                                    if (record.appId) {
                                                                        navigate({
                                                                            pathname: '/knowledgeChat',
                                                                            search: search,
                                                                        })
                                                                    }
                                                                }}
                                                            >
                                                                {formatMenuTitle(record.title)}
                                                            </div>
                                                        </Tooltip>
                                                    )
                                                };
                                            }) : undefined,
                                        };
                                    })
                                }}
                                overlayClassName="deekSeek-dropdown"
                                placement="bottomLeft"
                                align={dropdownAlign}
                                getPopupContainer={(triggerNode) => {
                                    if (isMobileScreen) {
                                        return document.body;
                                    }
                                    return triggerNode.parentElement || document.body;
                                }}
                                key={index}
                            >
                                <div
                                    className={`deekSeek-header__item ${activeNavIndex === index ? 'active' : ''}`}
                                    style={{
                                        marginRight: isMobileScreen ? 0 : 20,
                                        fontSize: isMobileScreen ? undefined : 14,
                                        fontWeight: isMobileScreen ? undefined : 600,
                                    }}
                                    title={item.title}
                                    onClick={() => setActiveNavIndex(index)}
                                >
                                    {formatMenuTitle(item.title)}
                                </div>
                            </Dropdown>
                        })
                    }
                    {/*<div style={{ whiteSpace: 'nowrap', marginRight: 20, color: '#98b4fa', cursor: 'pointer' }} onClick={() => {*/}
                    {/*    navigate({*/}
                    {/*        pathname: '/deepseekChat',*/}
                    {/*    })*/}
                    {/*}}>*/}
                    {/*    DeepSeek问答*/}
                    {/*</div>*/}

                    {/* 右侧区域 - 开放平台按钮 */}
                    {!isMobileScreen && (
                        <div style={{ display: 'flex', alignItems: 'center', marginRight: 20 }}>
                            <button
                                className='open-platform-btn'
                                onClick={() => {
                                    // 跳转到其他平台的逻辑，这里使用window.open举例
                                    const userInfo = localStorage.getItem('userInfo');
                                    const tokenParam = userInfo ? "?token=" + JSON.parse(userInfo).token : "";
                                    window.open('https://llm.jkec.info:11431/deepseek/questionAnswer' + tokenParam, '_blank');
                                }}
                            >
                                更多
                            </button>
                        </div>
                    )}
                </div>
                <div className='deekSeek-content'>
                    {(!isMobileScreen || !hideTitleOnMobile) && (
                        <>
                            <div className='deekSeek-content-title'>
                                <img src={jkxz.src} />
                            </div>
                            <div className='deekSeek-content-title-sm' style={{ marginBottom: isMobileScreen ? 14 : 20 }}>
                                智能问答助手
                            </div>
                        </>
                    )}
                    <div 
                        className={isMobileScreen ? 'deekSeek-content-mobile' : 'deekSeek-content-pc'} 
                        style={isMobileScreen && hideTitleOnMobile ? { height: 'calc(100% - 16px)', marginTop: 16 } : undefined}
                    >
                        <Chat onMessageSent={() => {
                            if (isMobileScreen) {
                                setHideTitleOnMobile(true);
                            }
                        }} />
                    </div>
                    {isMobileScreen && (
                        <div style={{ 
                            marginTop: 8, 
                            textAlign: 'center', 
                            color: '#FFFFFF', 
                            fontSize: 12,
                            opacity: 0.8
                        }}>
                            内容由AI生成，仅供参考
                        </div>
                    )}
                </div>
            </div>
        </Spin>
    );
};

export default DeekSeek;
