import React, { useState } from 'react';
import { LayoutDashboard, History, CreditCard, Dumbbell, ShieldAlert, BrainCircuit, LogOut, Zap, ChevronDown, ChevronRight, Calendar } from 'lucide-react';
import { User } from '@/types';

interface SidebarProps {
    user: User;
    activeTab: string;
    setActiveTab: (tab: string) => void;
    onLogout: () => void;
    onOpenAdmin?: () => void;
    onOpenPro?: () => void;
    t: any; // Translation object
    coachHistory?: any[]; // Array of coach_analyses records
    onSelectCoachPlan?: (plan: any) => void;
}

const Sidebar: React.FC<SidebarProps> = ({ user, activeTab, setActiveTab, onLogout, onOpenAdmin, onOpenPro, t, coachHistory, onSelectCoachPlan }) => {
    const [isCoachExpanded, setIsCoachExpanded] = useState(false);

    const handleCoachClick = () => {
        // If has history, toggle submenu
        if (coachHistory && coachHistory.length > 0) {
            setIsCoachExpanded(!isCoachExpanded);
        }
        setActiveTab('coach');
    };

    return (
        <aside className="w-64 bg-white border-r border-gray-200 fixed h-full z-20 hidden md:flex flex-col">
            <div className="p-6 border-b border-gray-100 flex items-center justify-between">
                <div className="flex items-center gap-2">
                    <div className="w-8 h-8 bg-brand-900 rounded-lg flex items-center justify-center text-brand-400">
                        <Zap size={18} fill="currentColor" />
                    </div>
                    <span className="font-bold text-xl tracking-tight">FoodSnap</span>
                </div>
            </div>

            <nav className="flex-1 p-4 space-y-1 overflow-y-auto custom-scrollbar">
                <SidebarItem
                    icon={<LayoutDashboard size={20} />}
                    label={t.dashboard.menuOverview}
                    active={activeTab === 'overview'}
                    onClick={() => setActiveTab('overview')}
                />

                {/* Coach AI with Submenu */}
                <div className="space-y-1">
                    <SidebarItem
                        icon={<Dumbbell size={20} />}
                        label="Coach AI"
                        active={activeTab === 'coach'}
                        onClick={handleCoachClick}
                        hasSubmenu={!!(coachHistory && coachHistory.length > 0)}
                        isExpanded={isCoachExpanded}
                    />

                    {/* Submenu Items */}
                    {isCoachExpanded && coachHistory && (
                        <div className="pl-11 space-y-1 animate-in slide-in-from-top-2 duration-200">
                            {coachHistory.map((item) => (
                                <button
                                    key={item.id}
                                    onClick={() => {
                                        const plan = typeof item.ai_structured === 'string'
                                            ? JSON.parse(item.ai_structured)
                                            : item.ai_structured;
                                        if (onSelectCoachPlan) onSelectCoachPlan(plan);
                                        setActiveTab('coach');
                                    }}
                                    className="w-full text-left px-3 py-2 text-xs font-medium text-gray-500 hover:text-brand-600 hover:bg-brand-50 rounded-lg flex items-center gap-2 transition-colors truncate"
                                >
                                    <Calendar size={12} />
                                    <span>{new Date(item.created_at).toLocaleDateString('pt-BR')}</span>
                                    <span className="text-[10px] text-gray-400 ml-auto truncate max-w-[60px]">{item.goal_suggestion || "Personalizado"}</span>
                                </button>
                            ))}
                        </div>
                    )}
                </div>

                <SidebarItem
                    icon={<History size={20} />}
                    label={t.dashboard.menuHistory} // Refers to Food History
                    active={activeTab === 'history'}
                    onClick={() => setActiveTab('history')}
                />
                <SidebarItem
                    icon={<CreditCard size={20} />}
                    label={t.dashboard.menuSubscription}
                    active={activeTab === 'subscription'}
                    onClick={() => setActiveTab('subscription')}
                />

                {/* Admin Link if capable */}
                {onOpenAdmin && (
                    <div className="mt-4 pt-4 border-t border-gray-100">
                        <button
                            onClick={onOpenAdmin}
                            className="w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all text-gray-400 hover:bg-gray-50 hover:text-red-500"
                        >
                            <ShieldAlert size={20} />
                            <span className="text-sm font-medium">Admin Panel</span>
                        </button>
                    </div>
                )}

                {/* Professional Link */}
                {user.is_professional && onOpenPro && (
                    <div className="mt-2">
                        <button
                            onClick={onOpenPro}
                            className="w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all bg-gray-900 text-white hover:bg-black shadow-lg shadow-gray-200"
                        >
                            <BrainCircuit size={20} className="text-brand-400" />
                            <span className="text-sm font-bold">Área Profissional</span>
                        </button>
                    </div>
                )}
            </nav>

            <div className="p-4 border-t border-gray-100 bg-gray-50/50">
                <div className="flex items-center gap-3 mb-4 px-2">
                    <img src={user.avatar || `https://ui-avatars.com/api/?name=${user.name}&background=random`} alt="User" className="w-9 h-9 rounded-full bg-gray-200 border-2 border-white shadow-sm" />
                    <div className="overflow-hidden">
                        <p className="text-sm font-bold text-gray-900 truncate">{user.name}</p>
                        <p className="text-[10px] text-gray-500 truncate uppercase font-bold tracking-wider">{user.plan === 'pro' ? 'PRO PLAN' : 'FREE PLAN'}</p>
                    </div>
                </div>
                <button
                    onClick={onLogout}
                    className="w-full flex items-center justify-center gap-2 text-gray-500 hover:text-red-600 hover:bg-red-50 p-2 rounded-lg transition-colors text-xs font-bold uppercase tracking-wider"
                >
                    <LogOut size={16} />
                    {t.dashboard.logout}
                </button>
            </div>
        </aside>
    );
};

interface SidebarItemProps {
    icon: React.ReactNode;
    label: string;
    active: boolean;
    onClick: () => void;
    hasSubmenu?: boolean;
    isExpanded?: boolean;
}

const SidebarItem = ({ icon, label, active, onClick, hasSubmenu, isExpanded }: SidebarItemProps) => (
    <button
        onClick={onClick}
        className={`w-full flex items-center justify-between px-4 py-3 rounded-xl transition-all group ${active
            ? 'bg-brand-50 text-brand-700 font-semibold shadow-sm'
            : 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
            }`}
    >
        <div className="flex items-center gap-3">
            {icon}
            <span className="text-sm">{label}</span>
        </div>
        {hasSubmenu && (
            <div className={`transition-transform duration-200 ${isExpanded ? 'rotate-180' : ''}`}>
                <ChevronDown size={14} className={active ? 'text-brand-500' : 'text-gray-400 group-hover:text-gray-600'} />
            </div>
        )}
    </button>
);

export default Sidebar;

