import React, { useState, useEffect } from 'react';
import {
    PlusOutlined,
    StarOutlined,
    AppstoreOutlined,
    EditOutlined,
    DeleteOutlined,
    DownOutlined,
    SearchOutlined,
    MessageOutlined,
} from '@ant-design/icons';
import { Input, Modal, Form, message, Dropdown, MenuProps } from 'antd';
import { useChatStore } from '../store/chatStore';
import { mockFavorites, mockApps, MockApp } from '../mock';
import '../styles/index.scss';

interface SideBarProps {
    onNewChat: () => void;
}

export const SideBar: React.FC<SideBarProps> = ({ onNewChat }) => {
    const [form] = Form.useForm();

    const {
        sessions,
        currentSessionId,
        sidebarOpen,
        setCurrentSessionId,
        addSession,
        deleteSession,
        updateSession,
    } = useChatStore();

    // 展开状态
    const [expandedFavorites, setExpandedFavorites] = useState(true);
    const [expandedApps, setExpandedApps] = useState(false);
    const [searchValue, setSearchValue] = useState('');
    const [renameModalOpen, setRenameModalOpen] = useState(false);
    const [editingSession, setEditingSession] = useState<{ id: string; topic: string } | null>(null);

    // Mock 数据
    const [favorites] = useState<MockApp[]>(mockFavorites);
    const [apps] = useState<MockApp[]>(mockApps);

    // 按日期分组的历史记录
    const groupedHistory = sessions.reduce((acc, session) => {
        const date = new Date(session.createTime || '');
        const now = new Date();
        const diffTime = now.getTime() - date.getTime();
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
        
        let dateLabel = '';
        if (diffDays === 0) {
            dateLabel = '今天';
        } else if (diffDays === 1) {
            dateLabel = '1 天前';
        } else if (diffDays <= 3) {
            dateLabel = '3 天前';
        } else if (diffDays <= 7) {
            dateLabel = '5 天前';
        } else {
            dateLabel = '更早';
        }
        
        if (!acc[dateLabel]) {
            acc[dateLabel] = [];
        }
        acc[dateLabel].push(session);
        return acc;
    }, {} as Record<string, typeof sessions>);

    const handleAppSelect = (app: MockApp) => {
        const newSession = {
            id: Date.now().toString(),
            topic: app.name,
            appId: app.id,
            messages: [],
            createTime: new Date().toISOString(),
        };
        addSession(newSession);
    };

    const handleSessionClick = (sessionId: string) => {
        setCurrentSessionId(sessionId);
    };

    const handleRename = (session: { id: string; topic: string }) => {
        setEditingSession(session);
        form.setFieldsValue({ dialogName: session.topic, dialogId: session.id });
        setRenameModalOpen(true);
    };

    const handleDeleteSession = (sessionId: string, e: React.MouseEvent) => {
        e.stopPropagation();
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这个对话吗？',
            onOk: () => {
                deleteSession(sessionId);
                message.success('删除成功');
            },
        });
    };

    const getSessionMenuItems = (session: any): MenuProps['items'] => [
        {
            key: 'rename',
            icon: <EditOutlined />,
            label: '重命名',
            onClick: () => handleRename(session),
        },
        {
            key: 'delete',
            icon: <DeleteOutlined style={{ color: '#ff4d4f' }} />,
            label: '删除',
            danger: true,
            onClick: (e: any) => handleDeleteSession(session.id, e.domEvent),
        },
    ];

    // 可折叠菜单项组件
    const CollapsibleMenu = ({
        icon,
        title,
        expanded,
        onToggle,
        children,
        hasSearch = false
    }: {
        icon: React.ReactNode;
        title: string;
        expanded: boolean;
        onToggle: () => void;
        children: React.ReactNode;
        hasSearch?: boolean;
    }) => (
        <div className="collapsible-menu">
            <div className="menu-header" onClick={onToggle}>
                <div className="menu-header-left">
                    <span className="menu-icon">{icon}</span>
                    <span className="menu-title">{title}</span>
                    {hasSearch && <SearchOutlined className="menu-search-icon" />}
                </div>
                <DownOutlined className={`menu-arrow ${expanded ? 'expanded' : ''}`} />
            </div>
            {expanded && <div className="menu-content">{children}</div>}
        </div>
    );

    return (
        <div className={`chat-sidebar ${sidebarOpen ? 'open' : 'collapsed'}`}>
            {/* Sidebar Header - 简化 */}
            {sidebarOpen && (
                <div className="chat-sidebar-header">
                    <div className="logo">
                        <span style={{ color: '#10b981' }}></span>建科•小智
                    </div>
                </div>
            )}

            {/* New Chat Button - 淡蓝色背景 */}
            <button className="new-chat-btn" onClick={onNewChat}>
                <PlusOutlined />
                <span>新建对话</span>
            </button>

            {/* Sidebar Body */}
            <div className="chat-sidebar-body">
                {/* 我的收藏应用 */}
                <CollapsibleMenu
                    icon={<StarOutlined />}
                    title="我的收藏应用"
                    expanded={expandedFavorites}
                    onToggle={() => setExpandedFavorites(!expandedFavorites)}
                    hasSearch
                >
                    {favorites.length === 0 ? (
                        <div className="empty-item">暂无收藏</div>
                    ) : (
                        favorites.map((app) => (
                            <div
                                key={app.id}
                                className="simple-app-item"
                                onClick={() => handleAppSelect(app)}
                            >
                                <span className="simple-app-icon">{app.icon}</span>
                                <span className="simple-app-name">{app.name}</span>
                            </div>
                        ))
                    )}
                </CollapsibleMenu>

                {/* 职能管理 */}
                <CollapsibleMenu
                    icon={<AppstoreOutlined />}
                    title="职能管理"
                    expanded={expandedApps}
                    onToggle={() => setExpandedApps(!expandedApps)}
                >
                    {apps.slice(0, 3).map((app) => (
                        <div
                            key={app.id}
                            className="simple-app-item"
                            onClick={() => handleAppSelect(app)}
                        >
                            <span className="simple-app-icon">{app.icon}</span>
                            <span className="simple-app-name">{app.name}</span>
                        </div>
                    ))}
                </CollapsibleMenu>

                {/* 最近对话 */}
                {sidebarOpen && sessions.length > 0 && (
                    <div className="recent-chats-section">
                        <div className="section-header">
                            <MessageOutlined /> 最近对话
                        </div>
                        {Object.entries(groupedHistory).map(([dateLabel, sessions]) => (
                            <div key={dateLabel} className="date-group">
                                <div className="date-label">{dateLabel}</div>
                                {sessions.map((session) => (
                                    <Dropdown
                                        key={session.id}
                                        menu={{ items: getSessionMenuItems(session) }}
                                        trigger={['contextMenu']}
                                    >
                                        <div
                                            className={`chat-item ${currentSessionId === session.id ? 'active' : ''}`}
                                            onClick={() => handleSessionClick(session.id)}
                                        >
                                            <span className="chat-item-title">{session.topic}</span>
                                            <EditOutlined className="chat-item-edit" />
                                        </div>
                                    </Dropdown>
                                ))}
                            </div>
                        ))}
                    </div>
                )}

                {/* 空状态 */}
                {sessions.length === 0 && (
                    <div className="empty-chats">
                        <MessageOutlined style={{ fontSize: '32px', color: '#d9d9d9' }} />
                        <p>暂无对话记录</p>
                    </div>
                )}
            </div>

            {/* Rename Modal */}
            <Modal
                title="重命名"
                open={renameModalOpen}
                width={300}
                maskClosable={false}
                onOk={() => {
                    form.validateFields().then(async (values) => {
                        if (editingSession) {
                            updateSession(editingSession.id, (session) => {
                                session.topic = values.dialogName;
                            });
                            message.success('重命名成功');
                        }
                        setRenameModalOpen(false);
                        setEditingSession(null);
                    });
                }}
                onCancel={() => {
                    setRenameModalOpen(false);
                    setEditingSession(null);
                }}
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        label="名称"
                        name="dialogName"
                        rules={[{ required: true, message: '名称不能为空' }]}
                    >
                        <Input maxLength={20} placeholder="请输入对话名称" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};
