'use client';

import {
    Cigarette,
    Leaf,
    LogOut,
    Home,
    Sparkles,
    X,
    Settings,
    Shield,
    Heart,
    Calendar
} from 'lucide-react';
import React from 'react';
import { useRouter } from 'next/navigation';
import { cn } from '@/lib/utils';
import { useTheme } from '@/lib/theme-context';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { createPortal } from 'react-dom';

interface SideMenuProps {
    isOpen: boolean;
    onClose: () => void;
    user: {
        id: string;
        email: string;
        firstName?: string | null;
        lastName?: string | null;
        profilePictureUrl?: string | null;
    };
    userName: string | null;
}

export function SideMenu({ isOpen, onClose, user, userName }: SideMenuProps) {
    const router = useRouter();
    const { theme } = useTheme();

    if (!isOpen) return null;

    const handleNavigate = (path: string) => {
        router.push(path);
        onClose();
    };

    const handleLogout = () => {
        window.location.href = '/api/auth/logout';
    };

    const initials = [user.firstName?.[0], user.lastName?.[0]]
        .filter(Boolean)
        .join('')
        .toUpperCase() || user.email[0].toUpperCase();

    // Use Portal to render outside of header stacking context
    const [mounted, setMounted] = React.useState(false);

    React.useEffect(() => {
        setMounted(true);
    }, []);

    if (!mounted) return null;

    return createPortal(
        <div className="fixed inset-0 z-[100] flex">
            {/* Backdrop */}
            <div
                className="absolute inset-0 bg-black/40 backdrop-blur-sm transition-all animate-in fade-in duration-300"
                onClick={onClose}
            />

            {/* Menu Content */}
            <div
                className={cn(
                    "relative w-72 h-full flex flex-col shadow-2xl transition-all animate-in slide-in-from-left duration-300",
                    theme === 'light'
                        ? "bg-white text-slate-900"
                        : "bg-slate-900 text-white border-r border-white/5"
                )}
            >
                {/* Header/Profile Info */}
                <div className={cn(
                    "p-6 border-b",
                    theme === 'light' ? "border-slate-100 bg-slate-50/50" : "border-white/5 bg-white/5"
                )}>
                    <div className="flex items-center justify-between mb-4">
                        <Avatar className="h-12 w-12 ring-2 ring-primary/20">
                            <AvatarImage src={user.profilePictureUrl ?? undefined} alt={userName || 'User'} />
                            <AvatarFallback className="bg-primary/20 text-primary text-lg">{initials}</AvatarFallback>
                        </Avatar>
                        <button
                            onClick={onClose}
                            className="p-2 rounded-full hover:bg-slate-200/50 dark:hover:bg-white/10 transition-colors"
                        >
                            <X className="h-5 w-5 opacity-60" />
                        </button>
                    </div>
                    <div className="space-y-1">
                        <h3 className="font-bold text-lg leading-tight">{userName || 'User'}</h3>
                        <p className="text-xs opacity-50 truncate">{user.email}</p>
                    </div>
                </div>

                {/* Navigation Links */}
                <div className="flex-1 overflow-y-auto py-4 px-3 space-y-1">
                    <MenuLink
                        icon={Home}
                        label="Dashboard"
                        onClick={() => handleNavigate('/')}
                    />
                    <div className="my-2 px-3">
                        <span className="text-[10px] font-bold uppercase tracking-widest opacity-30">Tracking</span>
                    </div>
                    <MenuLink
                        icon={Cigarette}
                        label="Track Nicotine"
                        onClick={() => handleNavigate('/track/nicotine')}
                        color="rose"
                    />
                    <MenuLink
                        icon={Leaf}
                        label="Track Marijuana"
                        onClick={() => handleNavigate('/track/marijuana')}
                        color="emerald"
                    />

                    <div className="my-2 px-3 pt-2">
                        <span className="text-[10px] font-bold uppercase tracking-widest opacity-30">Resources</span>
                    </div>
                    <MenuLink
                        icon={Sparkles}
                        label="Smoking Aids"
                        onClick={() => handleNavigate('/smoking-aids')}
                        color="purple"
                    />
                </div>

                {/* Footer Actions */}
                <div className={cn(
                    "p-4 border-t",
                    theme === 'light' ? "border-slate-100" : "border-white/5"
                )}>
                    <MenuLink
                        icon={Settings}
                        label="Account Settings"
                        onClick={() => handleNavigate('/settings')}
                        color="blue"
                    />
                    <button
                        onClick={handleLogout}
                        className="w-full flex items-center gap-3 px-3 py-3 rounded-xl text-red-500 hover:bg-red-500/10 transition-colors font-medium mt-1"
                    >
                        <LogOut className="h-5 w-5" />
                        <span>Sign out</span>
                    </button>
                </div>
            </div>
        </div>,
        document.body
    );
}

interface MenuLinkProps {
    icon: any;
    label: string;
    onClick: () => void;
    color?: 'rose' | 'emerald' | 'purple' | 'blue' | 'amber';
}

function MenuLink({ icon: Icon, label, onClick, color }: MenuLinkProps) {
    const { theme } = useTheme();

    const colors = {
        rose: "text-rose-500 bg-rose-500/5",
        emerald: "text-emerald-500 bg-emerald-500/5",
        purple: "text-purple-500 bg-purple-500/5",
        blue: "text-blue-500 bg-blue-500/5",
        amber: "text-amber-500 bg-amber-500/5",
    };

    return (
        <button
            onClick={onClick}
            className={cn(
                "w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-all font-medium group",
                theme === 'light'
                    ? "hover:bg-slate-100"
                    : "hover:bg-white/5"
            )}
        >
            <div className={cn(
                "p-2 rounded-lg transition-colors",
                color ? colors[color] : (theme === 'light' ? "bg-slate-100" : "bg-white/5")
            )}>
                <Icon className="h-4 w-4" />
            </div>
            <span className="flex-1 text-left text-sm">{label}</span>
            <div className="w-1.5 h-1.5 rounded-full bg-primary opacity-0 group-hover:opacity-100 transition-opacity" />
        </button>
    );
}
