"use client";

import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Link from "next/link";
import { User, Settings, LogOut, Briefcase, FileText, ChevronDown } from "lucide-react";

interface UserMenuDropdownProps {
    user: any;
    role: string;
}

export function UserMenuDropdown({ user, role }: UserMenuDropdownProps) {
    const [isOpen, setIsOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);

    // Initial letters for avatar
    const userInitials = user?.name
        ? user.name.split(' ').map((n: string) => n[0]).join('').substring(0, 2).toUpperCase()
        : role.charAt(0).toUpperCase();

    // Calculate basic profile completion (example logic)
    const calculateCompletion = () => {
        let score = 0;
        const total = 5;
        if (user?.name) score += 1;
        if (user?.title || user?.company) score += 1;
        if (user?.bio || user?.aboutMe) score += 1;
        if (user?.skills?.length > 0) score += 1;
        if (user?.location) score += 1;

        return Math.round((score / total) * 100);
    };

    const completionPercentage = calculateCompletion();

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };

        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    const toggleDropdown = () => setIsOpen(!isOpen);

    const isCandidate = role === "candidate";

    return (
        <div className="relative" ref={dropdownRef}>
            <button
                onClick={toggleDropdown}
                className="flex items-center gap-2 md:gap-3 rounded-full md:pr-4 md:hover:bg-slate-100 transition-colors p-1 focus:outline-none focus:ring-2 focus:ring-primary/20"
                aria-expanded={isOpen}
                aria-haspopup="true"
            >
                <div className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary border border-primary/20 shadow-sm overflow-hidden">
                    {user?.avatarUrl ? (
                        <img src={user.avatarUrl} alt={user.name} className="h-full w-full object-cover" />
                    ) : (
                        userInitials
                    )}
                </div>
                <div className="hidden md:block text-left">
                    <p className="text-sm font-medium text-slate-700 leading-none">{user?.name || "User"}</p>
                    <p className="text-xs text-slate-500 mt-1 capitalize">{role.replace('_', ' ')}</p>
                </div>
                <ChevronDown className={`hidden md:block h-4 w-4 text-slate-400 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`} />
            </button>

            <AnimatePresence>
                {isOpen && (
                    <motion.div
                        initial={{ opacity: 0, scale: 0.95, y: 10 }}
                        animate={{ opacity: 1, scale: 1, y: 0 }}
                        exit={{ opacity: 0, scale: 0.95, y: 10 }}
                        transition={{ duration: 0.15, ease: "easeOut" }}
                        className="absolute right-0 mt-2 w-72 rounded-xl bg-white shadow-lg border border-slate-100 overflow-hidden z-50 origin-top-right"
                    >
                        {/* User Info Header */}
                        <div className="p-4 border-b border-slate-100 bg-slate-50/50">
                            <h3 className="font-semibold text-slate-800">{user?.name}</h3>
                            <p className="text-sm text-slate-500 truncate">{user?.email}</p>

                            {/* Profile Completion Indicator */}
                            <div className="mt-3">
                                <div className="flex justify-between text-xs mb-1">
                                    <span className="font-medium text-slate-600">Profile Completion</span>
                                    <span className="font-semibold text-primary">{completionPercentage}%</span>
                                </div>
                                <div className="h-2 w-full bg-slate-200 rounded-full overflow-hidden">
                                    <motion.div
                                        initial={{ width: 0 }}
                                        animate={{ width: `${completionPercentage}%` }}
                                        transition={{ duration: 0.5, ease: "easeOut" }}
                                        className="h-full bg-primary rounded-full"
                                    />
                                </div>
                                {completionPercentage < 100 && (
                                    <Link
                                        href="/dashboard/profile"
                                        className="text-xs text-primary hover:underline mt-1 inline-block"
                                        onClick={() => setIsOpen(false)}
                                    >
                                        Complete your profile
                                    </Link>
                                )}
                            </div>
                        </div>

                        {/* Quick Actions */}
                        <div className="p-2">
                            <Link
                                href="/dashboard/profile"
                                className="flex items-center gap-3 px-3 py-2 text-sm text-slate-700 rounded-lg hover:bg-slate-50 transition-colors"
                                onClick={() => setIsOpen(false)}
                            >
                                <User className="h-4 w-4 text-slate-400" />
                                My Profile
                            </Link>

                            {isCandidate ? (
                                <>
                                    <Link
                                        href="/dashboard/applications"
                                        className="flex items-center gap-3 px-3 py-2 text-sm text-slate-700 rounded-lg hover:bg-slate-50 transition-colors"
                                        onClick={() => setIsOpen(false)}
                                    >
                                        <Briefcase className="h-4 w-4 text-slate-400" />
                                        My Applications
                                    </Link>
                                    <Link
                                        href="/dashboard/profile" // Assuming resume edit is part of profile
                                        className="flex items-center gap-3 px-3 py-2 text-sm text-slate-700 rounded-lg hover:bg-slate-50 transition-colors"
                                        onClick={() => setIsOpen(false)}
                                    >
                                        <FileText className="h-4 w-4 text-slate-400" />
                                        Manage Resume
                                    </Link>
                                </>
                            ) : (
                                <>
                                    <Link
                                        href="/dashboard/jobs"
                                        className="flex items-center gap-3 px-3 py-2 text-sm text-slate-700 rounded-lg hover:bg-slate-50 transition-colors"
                                        onClick={() => setIsOpen(false)}
                                    >
                                        <Briefcase className="h-4 w-4 text-slate-400" />
                                        Manage Jobs
                                    </Link>
                                </>
                            )}

                            <Link
                                href="/dashboard/settings"
                                className="flex items-center gap-3 px-3 py-2 text-sm text-slate-700 rounded-lg hover:bg-slate-50 transition-colors"
                                onClick={() => setIsOpen(false)}
                            >
                                <Settings className="h-4 w-4 text-slate-400" />
                                Account Settings
                            </Link>
                        </div>

                        {/* Logout */}
                        <div className="p-2 border-t border-slate-100">
                            <button
                                onClick={async () => {
                                    try {
                                        const { logout } = await import("@/app/actions/auth");
                                        await logout();
                                    } catch (error) {
                                        console.error("Logout failed:", error);
                                    }
                                }}
                                className="flex w-full items-center gap-3 px-3 py-2 text-sm text-red-600 rounded-lg hover:bg-red-50 transition-colors"
                            >
                                <LogOut className="h-4 w-4" />
                                Sign Out
                            </button>
                        </div>
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    );
}
