import { useCallback, useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import { selectUser } from "../redux/slices/userSlice";
import { Bell, ChevronDown, HelpCircle } from "lucide-react";
import Avatar from "./Avatar";

/**
 * Props:
 * - user: { name, avatar (string or JSX), email?, phone? }
 * - onLogout: () => void
 * - className: extra classes if needed
 */

export default function ProfileDropdown({ onLogout = () => { }, className = "", top = 'top-16' }) {
    const user = useSelector(selectUser) ?? { name: "User", avatar: "U" };
    const [open, setOpen] = useState(false);
    const [isDark, setIsDark] = useState(() => {
        if (typeof window === "undefined") return false;
        const saved = localStorage.getItem("theme");
        if (saved) return saved === "dark";
        return window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
    });

    const rootRef = useRef(null);
    const toggleOpen = useCallback(() => setOpen(v => !v), []);
    const close = useCallback(() => setOpen(false), []);

    // apply dark mode class on <html>
    useEffect(() => {
        if (typeof document !== "undefined") {
            document.documentElement.classList.toggle("dark", isDark);
            localStorage.setItem("theme", isDark ? "dark" : "light");
        }
    }, [isDark]);

    // click outside & escape key handling
    useEffect(() => {
        function handlePointerDown(e) {
            if (!rootRef.current) return;
            if (!rootRef.current.contains(e.target)) close();
        }
        function handleKeyDown(e) {
            if (e.key === "Escape") close();
            // optionally: handle Enter/Space on focused menu items if you add focus management
        }

        document.addEventListener("mousedown", handlePointerDown);
        document.addEventListener("touchstart", handlePointerDown);
        document.addEventListener("keydown", handleKeyDown);
        return () => {
            document.removeEventListener("mousedown", handlePointerDown);
            document.removeEventListener("touchstart", handlePointerDown);
            document.removeEventListener("keydown", handleKeyDown);
        };
    }, [close]);

    const handleLogout = useCallback(() => {
        close();
        onLogout();
    }, [onLogout, close]);

    return (
        <>
            {/* Header (left content + action buttons) */}
            <div className="header-actions flex items-center">
                <div className="help-and-bell flex items-center flex-row">
                    <button className="p-2 hover:bg-gray-100 rounded-xl transition-all md:flex items-center justify-center" aria-label="Help">
                        <HelpCircle className="w-5 h-5 text-gray-600" />
                    </button>

                    <button
                        className="notification-btn p-2 hover:bg-gray-100 rounded-xl transition-all relative md:flex items-center justify-center"
                        aria-label="Notifications"
                    >
                        <Bell className="w-5 h-5 text-gray-600" />
                        <span className="notification-dot absolute top-1 right-2 w-2 h-2 bg-[#FF6B00] rounded-full" />
                    </button>
                </div>

                {/* PROFILE BUTTON: single source of truth for opening dropdown */}
                <div ref={rootRef} className={`${className}`}>
                    <button
                        aria-haspopup="true"
                        aria-expanded={open}
                        onClick={toggleOpen}
                        className="profile-btn flex items-center gap-2 hover:bg-gray-100 rounded-xl p-2 transition-all md:flex"
                        aria-label="Open profile menu"
                    >
                        <Avatar className="avatar w-7 h-7 md:w-9 md:h-9 bg-gradient-to-br from-[#FF6B00] to-[#FF8534] rounded-full flex items-center justify-center text-white text-sm font-semibold shadow-lg">
                            {user.avatar ?? (user.name ? user.name[0].toUpperCase() : "U")}
                        </Avatar>
                        <span className="text-sm font-medium avatar-name">{user.name}</span>
                        <ChevronDown className="w-4 h-4 text-gray-600" />
                    </button>
                    {/* DROPDOWN */}
                    {open && (
                        <div
                            role="menu"
                            aria-label="Profile menu"
                            className={`absolute ${top} right-0 mt-3 w-72 bg-card rounded-2xl shadow-xl p-4 z-50 bg-white`}
                        >
                            {/* Top: avatar left, details right */}
                            <div className="flex items-center gap-3 pb-3 border-b" style={{ borderColor: '#a1a1a1' }}>
                                <Avatar className="avatar w-12 h-12 bg-gradient-to-br from-[#FF6B00] to-[#FF8534] rounded-full flex items-center justify-center text-white text-sm font-semibold shadow-lg">
                                    <div className="text-lg">{user.avatar ?? (user.name ? user.name[0].toUpperCase() : "U")}</div>
                                </Avatar>

                                <div className="flex-1">
                                    <div className="text-sm font-semibold text-card-foreground text-[#2f2f2f]">{user.name}</div>
                                    {user.phone && <div className="text-xs text-muted-foreground mt-1">{user.phone}</div>}
                                    {user.email && <div className="text-xs text-muted-foreground">{user.email}</div>}
                                </div>
                            </div>

                            {/* Middle: display toggle */}
                            <div className="mt-2 mb-2">
                                <button
                                    onClick={() => setIsDark(v => !v)}
                                    type="button"
                                    className="w-full flex items-center justify-between px-3 py-2 rounded-lg hover:bg-accent transition"
                                    role="menuitem"
                                >
                                    <div className="flex items-center gap-3">
                                        {isDark ? (
                                            <svg className="w-5 h-5 text-yellow-400" viewBox="0 0 24 24" fill="currentColor">
                                                <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" />
                                            </svg>
                                        ) : (
                                            <svg className="w-5 h-5 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                <circle cx="12" cy="12" r="4" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                                <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                            </svg>
                                        )}
                                        <span className="text-sm font-medium text-card-foreground text-[#2f2f2f]">Display: {isDark ? "Dark" : "Light"}</span>
                                    </div>

                                    <div className="" aria-hidden>
                                        <div className={`w-10 h-5 flex items-center rounded-full transition-colors ${isDark ? "bg-blue-600" : "bg-gray-300"}`}>
                                            <div className={`bg-white w-4 h-4 rounded-full shadow-sm transform transition-transform ${isDark ? "translate-x-5.5" : "translate-x-0.5"}`} />
                                        </div>
                                    </div>
                                </button>
                            </div>

                            {/* Bottom: logout */}
                            <div className="mt-2">
                                <button
                                    onClick={handleLogout}
                                    className="w-full text-left px-3 py-2 rounded-lg hover:bg-accent transition flex items-center gap-3"
                                    role="menuitem"
                                >
                                    <svg className="w-5 h-5 text-red-500" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                        <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                        <path d="M16 17l5-5-5-5" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                        <path d="M21 12H9" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                    </svg>
                                    <span className="text-sm font-medium text-red-600 dark:text-red-400">Logout</span>
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>


            <style jsx>{`
            .avatar-name {
                        display: block;
                    }
                        .help-and-bell {
                            display: flex;
                        }
                @media (max-width: 576px) {
                    .avatar-name {
                        display: none !important;
                    }
                        .help-and-bell {
                            display: none !important;
                        }
                }
            `}
            </style>
        </>
    );
}