import React, { useState } from 'react'
import { MessageSquare, Book, Mic, Settings, LogOut, Database, ChevronRight, ChevronLeft, Menu, Globe, DownloadCloud, User } from 'lucide-react'
import { Logo } from '../Logo'
import { useLanguage } from '../../contexts/LanguageContext'
import { UserInfoDisplay } from '../UserInfoDisplay'

export type ViewType = 'chat' | 'knowledge' | 'notebooks' | 'settings' | string;

export interface NavItem {
    id: ViewType;
    icon: React.ElementType;
    label: string;
}

interface SidebarRailProps {
    currentView: ViewType;
    onViewChange: (view: ViewType) => void;
    onLogout?: () => void;
    onOpenSettings?: () => void;
    currentUser?: any;
    navItems: NavItem[];
    appMode?: 'workspace' | 'admin';
    onSwitchMode?: () => void;
}

export const SidebarRail: React.FC<SidebarRailProps> = ({ currentView, onViewChange, onLogout, currentUser, navItems, appMode, onSwitchMode }) => {
    const [isExpanded, setIsExpanded] = useState(false)
    const { language, setLanguage, t } = useLanguage()

    const handleLanguageCycle = () => {
        const langs = ['zh', 'en', 'ja'] as const
        const currentIndex = langs.indexOf(language as any)
        const nextIndex = (currentIndex + 1) % langs.length
        setLanguage(langs[nextIndex])
    }



    return (
        <div className={`
            ${isExpanded ? 'w-64' : 'w-20'}
            bg-slate-950 flex flex-col py-6 shrink-0 z-50 transition-all duration-300 ease-[cubic-bezier(0.4,0,0.2,1)] border-r border-slate-800
        `}>
            {/* Header / Logo */}
            <div className={`mb-8 flex items-center ${isExpanded ? 'px-6 justify-between' : 'justify-center'}`}>
                <div className="flex items-center justify-center shrink-0 cursor-default">
                    <Logo size={isExpanded ? 32 : 40} withText={isExpanded} />
                </div>
                {isExpanded && appMode && (
                    <span className={`ml-2 px-2 py-0.5 text-xs font-semibold rounded-md ${appMode === 'admin' ? 'bg-purple-500/20 text-purple-400' : 'bg-blue-500/20 text-blue-400'}`}>
                        {appMode === 'admin' ? 'Admin' : 'Workspace'}
                    </span>
                )}
                {isExpanded && (
                    <button
                        onClick={() => setIsExpanded(false)}
                        className="text-slate-500 hover:text-slate-300 transition-colors p-1 rounded-full hover:bg-slate-800/50 ml-auto"
                    >
                        <ChevronLeft size={18} />
                    </button>
                )}
            </div>

            {/* Current User Display - only when expanded */}
            {isExpanded && currentUser && (
                <div className="px-2 mb-4">
                    <UserInfoDisplay currentUser={currentUser} />
                </div>
            )}

            {/* ナビゲーション項目 */}
            <div className="flex-1 flex flex-col space-y-2 w-full px-3">
                {navItems.map((item) => {
                    // 現在のルートに基づいてアクティブなタブを決定
                    const isActive = currentView === item.id;
                    return (
                        <button
                            key={item.id}
                            onClick={() => onViewChange(item.id)}
                            draggable="false"
                            className={`
                                py-3 px-3 rounded-xl transition-all duration-300 group relative flex items-center outline-none
                                ${isExpanded ? 'justify-start' : 'justify-center'}
                                ${isActive
                                    ? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md shadow-blue-500/25'
                                    : 'text-slate-400 hover:bg-white/5 hover:text-slate-200'
                                }
                            `}
                            title={!isExpanded ? item.label : undefined}
                        >
                            <item.icon size={20} strokeWidth={isActive ? 2.5 : 2} className={`shrink-0 transition-transform duration-300 ${isActive ? 'scale-110' : 'group-hover:scale-110'}`} />

                            <span className={`
                                ml-3 font-medium whitespace-nowrap overflow-hidden transition-all duration-300
                                ${isExpanded ? 'opacity-100 w-auto translate-x-0' : 'opacity-0 w-0 -translate-x-4 absolute'}
                            `}>
                                {item.label}
                            </span>

                            {/* Tooltip (only when collapsed) */}
                            {!isExpanded && (
                                <span className="
                                    absolute left-full ml-4 bg-slate-900 text-slate-200 text-xs px-2.5 py-1.5 rounded-md 
                                    opacity-0 group-hover:opacity-100 transition-all duration-200 pointer-events-none whitespace-nowrap z-50
                                    top-1/2 -translate-y-1/2 shadow-xl border border-slate-800 translate-x-[-8px] group-hover:translate-x-0
                                ">
                                    {item.label}
                                </span>
                            )}
                        </button>
                    )
                })}
            </div>

            {/* Footer / Settings / Toggle */}
            <div className="flex flex-col space-y-2 w-full px-3 mt-auto">
                {/* Toggle Button (When collapsed, show here to expand) */}
                {!isExpanded && (
                    <button
                        onClick={() => setIsExpanded(true)}
                        className="p-3 rounded-xl text-slate-500 hover:bg-white/5 hover:text-slate-300 transition-all flex justify-center mb-2"
                        title={t('expandMenu')}
                    >
                        <ChevronRight size={20} />
                    </button>
                )}

                {/* Settings Button */}
                <button
                    onClick={() => onViewChange('settings')}
                    className={`
                            py-3 px-3 rounded-xl transition-all duration-300 flex items-center group relative outline-none
                            ${isExpanded ? 'justify-start' : 'justify-center'}
                            ${currentView === 'settings'
                            ? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md shadow-blue-500/25'
                            : 'text-slate-400 hover:bg-white/5 hover:text-slate-200'
                        }
                        `}
                    title={!isExpanded ? t('settings') : undefined}
                >
                    <Settings size={20} className={`shrink-0 transition-transform duration-300 ${currentView === 'settings' ? 'rotate-90' : 'group-hover:rotate-45'}`} />
                    <span className={`
                            ml-3 font-medium whitespace-nowrap overflow-hidden transition-all duration-300
                            ${isExpanded ? 'opacity-100 w-auto' : 'opacity-0 w-0 absolute'}
                        `}>
                        {t('settings')}
                    </span>
                    {!isExpanded && (
                        <span className="
                                absolute left-full ml-4 bg-slate-900 text-slate-200 text-xs px-2.5 py-1.5 rounded-md 
                                opacity-0 group-hover:opacity-100 transition-all duration-200 pointer-events-none whitespace-nowrap z-50
                                top-1/2 -translate-y-1/2 shadow-xl border border-slate-800 translate-x-[-8px] group-hover:translate-x-0
                            ">
                            {t('settings')}
                        </span>
                    )}
                </button>

                {/* App Switcher for Admins */}
                {currentUser?.isAdmin && onSwitchMode && (
                    <button
                        onClick={onSwitchMode}
                        className={`
                            py-3 px-3 rounded-xl transition-all duration-300 flex items-center group relative outline-none
                            ${isExpanded ? 'justify-start' : 'justify-center'}
                            text-slate-400 hover:bg-white/5 hover:text-slate-200
                        `}
                        title={!isExpanded ? (appMode === 'admin' ? t('backToWorkspace') || 'Workspace' : t('goToAdmin') || 'Admin Dashboard') : undefined}
                    >
                        {appMode === 'admin' ? (
                            <User size={20} className="shrink-0 group-hover:scale-110 transition-transform duration-300" />
                        ) : (
                            <Database size={20} className="shrink-0 group-hover:scale-110 transition-transform duration-300" />
                        )}
                        <span className={`
                            ml-3 font-medium whitespace-nowrap overflow-hidden transition-all duration-300
                            ${isExpanded ? 'opacity-100 w-auto' : 'opacity-0 w-0 absolute'}
                        `}>
                            {appMode === 'admin' ? t('backToWorkspace') || 'Workspace' : t('goToAdmin') || 'Admin'}
                        </span>
                        {!isExpanded && (
                            <span className="
                                absolute left-full ml-4 bg-slate-900 text-slate-200 text-xs px-2.5 py-1.5 rounded-md
                                opacity-0 group-hover:opacity-100 transition-all duration-200 pointer-events-none whitespace-nowrap z-50
                                top-1/2 -translate-y-1/2 shadow-xl border border-slate-800 translate-x-[-8px] group-hover:translate-x-0
                            ">
                                {appMode === 'admin' ? t('backToWorkspace') || 'Workspace' : t('goToAdmin') || 'Admin'}
                            </span>
                        )}
                    </button>
                )}

                {/* Language Switcher */}
                <button
                    onClick={handleLanguageCycle}
                    className={`
                        py-3 px-3 rounded-xl transition-all duration-300 flex items-center group relative outline-none
                        ${isExpanded ? 'justify-start' : 'justify-center'}
                        text-slate-400 hover:bg-white/5 hover:text-slate-200
                    `}
                    title={!isExpanded ? t('switchLanguage') : undefined}
                >
                    <Globe size={20} className="shrink-0 group-hover:scale-110 transition-transform duration-300" />
                    <span className={`
                        ml-3 font-medium whitespace-nowrap overflow-hidden transition-all duration-300
                        ${isExpanded ? 'opacity-100 w-auto' : 'opacity-0 w-0 absolute'}
                    `}>
                        {language === 'ja' ? t('langJa') : language === 'en' ? t('langEn') : t('langZh')}
                    </span>
                    {!isExpanded && (
                        <span className="
                            absolute left-full ml-4 bg-slate-900 text-slate-200 text-xs px-2.5 py-1.5 rounded-md
                            opacity-0 group-hover:opacity-100 transition-all duration-200 pointer-events-none whitespace-nowrap z-50
                            top-1/2 -translate-y-1/2 shadow-xl border border-slate-800 translate-x-[-8px] group-hover:translate-x-0
                        ">
                            {t('switchLanguage')}
                        </span>
                    )}
                </button>

                {/* Logout Button */}
                <button
                    onClick={onLogout}
                    className={`
                        py-3 px-3 rounded-xl transition-all duration-300 flex items-center group relative outline-none
                        ${isExpanded ? 'justify-start' : 'justify-center'}
                        text-slate-400 hover:bg-red-500/10 hover:text-red-400
                    `}
                    title={!isExpanded ? t('logout') : undefined}
                >
                    <LogOut size={20} className="shrink-0 group-hover:translate-x-1 transition-transform duration-300" />
                    <span className={`
                        ml-3 font-medium whitespace-nowrap overflow-hidden transition-all duration-300
                        ${isExpanded ? 'opacity-100 w-auto' : 'opacity-0 w-0 absolute'}
                    `}>
                        {t('logout')}
                    </span>
                    {!isExpanded && (
                        <span className="
                            absolute left-full ml-4 bg-slate-900 text-slate-200 text-xs px-2.5 py-1.5 rounded-md
                            opacity-0 group-hover:opacity-100 transition-all duration-200 pointer-events-none whitespace-nowrap z-50
                            top-1/2 -translate-y-1/2 shadow-xl border border-slate-800 translate-x-[-8px] group-hover:translate-x-0
                        ">
                            {t('logout')}
                        </span>
                    )}
                </button>

            </div>
        </div>
    )
}
