"use client";

import { useState, useRef, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
    Search, Bell, ChevronDown, User, Settings,
    Activity, Eye, LogOut, X
} from "lucide-react";

interface AdminHeaderProps {
    adminName?: string;
    adminEmail?: string;
    pendingApprovals?: number;
}

export function AdminHeader({
    adminName = "Admin",
    adminEmail = "",
    pendingApprovals = 0,
}: AdminHeaderProps) {
    const router = useRouter();
    const [searchQuery, setSearchQuery] = useState("");
    const [searchOpen, setSearchOpen] = useState(false);
    const [profileOpen, setProfileOpen] = useState(false);
    const [notificationsOpen, setNotificationsOpen] = useState(false);
    const searchRef = useRef<HTMLDivElement>(null);
    const profileRef = useRef<HTMLDivElement>(null);
    const notifRef = useRef<HTMLDivElement>(null);

    // Close dropdowns on outside click
    useEffect(() => {
        const handler = (e: MouseEvent) => {
            if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
                setSearchOpen(false);
            }
            if (profileRef.current && !profileRef.current.contains(e.target as Node)) {
                setProfileOpen(false);
            }
            if (notifRef.current && !notifRef.current.contains(e.target as Node)) {
                setNotificationsOpen(false);
            }
        };
        document.addEventListener("mousedown", handler);
        return () => document.removeEventListener("mousedown", handler);
    }, []);

    return (
        <header className="sticky top-0 z-30 flex h-16 items-center justify-between border-b border-slate-100 bg-white/80 px-6 backdrop-blur-sm">
            {/* Left — Page context / search */}
            <div ref={searchRef} className="relative flex-1 max-w-md">
                <div className="flex items-center gap-2 rounded-lg bg-slate-50 px-3 py-2">
                    <Search className="h-4 w-4 text-slate-400" />
                    <input
                        type="text"
                        placeholder="Search users, jobs, companies..."
                        value={searchQuery}
                        onChange={(e) => {
                            setSearchQuery(e.target.value);
                            setSearchOpen(e.target.value.length > 0);
                        }}
                        onFocus={() => searchQuery.length > 0 && setSearchOpen(true)}
                        className="w-full bg-transparent text-sm text-slate-700 outline-none placeholder:text-slate-400"
                    />
                    {searchQuery && (
                        <button onClick={() => { setSearchQuery(""); setSearchOpen(false); }}>
                            <X className="h-3.5 w-3.5 text-slate-400 hover:text-slate-600" />
                        </button>
                    )}
                    <kbd className="hidden rounded border border-slate-200 bg-white px-1.5 py-0.5 text-[10px] font-medium text-slate-400 sm:inline-block">
                        ⌘K
                    </kbd>
                </div>

                {/* Search Results Dropdown */}
                {searchOpen && (
                    <div className="absolute left-0 top-full mt-2 w-full rounded-xl border border-slate-100 bg-white p-2 shadow-xl">
                        <p className="px-3 py-2 text-xs font-medium text-slate-400">
                            Search results for &quot;{searchQuery}&quot;
                        </p>
                        <div className="border-t border-slate-50 pt-1">
                            <Link
                                href={`/admin/users?q=${encodeURIComponent(searchQuery)}`}
                                className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-slate-700 hover:bg-slate-50"
                                onClick={() => setSearchOpen(false)}
                            >
                                <User className="h-4 w-4 text-slate-400" />
                                Search users for &quot;{searchQuery}&quot;
                            </Link>
                            <Link
                                href={`/admin/jobs?q=${encodeURIComponent(searchQuery)}`}
                                className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-slate-700 hover:bg-slate-50"
                                onClick={() => setSearchOpen(false)}
                            >
                                <Search className="h-4 w-4 text-slate-400" />
                                Search jobs for &quot;{searchQuery}&quot;
                            </Link>
                        </div>
                    </div>
                )}
            </div>

            {/* Right — Actions */}
            <div className="flex items-center gap-2">
                {/* Pending Approvals Badge */}
                {pendingApprovals > 0 && (
                    <Link
                        href="/admin/approvals"
                        className="flex items-center gap-1.5 rounded-lg bg-orange-50 px-3 py-1.5 text-xs font-semibold text-orange-600 hover:bg-orange-100 transition-colors"
                    >
                        <span className="flex h-5 w-5 items-center justify-center rounded-full bg-orange-500 text-[10px] font-bold text-white">
                            {pendingApprovals}
                        </span>
                        <span className="hidden sm:inline">Pending</span>
                    </Link>
                )}

                {/* Notifications */}
                <div ref={notifRef} className="relative">
                    <button
                        onClick={() => setNotificationsOpen(!notificationsOpen)}
                        className="relative rounded-lg p-2 text-slate-500 hover:bg-slate-50 hover:text-slate-700 transition-colors"
                    >
                        <Bell className="h-5 w-5" />
                        <span className="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-red-500 ring-2 ring-white" />
                    </button>

                    {notificationsOpen && (
                        <div className="absolute right-0 top-full mt-2 w-80 rounded-xl border border-slate-100 bg-white shadow-xl">
                            <div className="flex items-center justify-between border-b border-slate-50 px-4 py-3">
                                <h3 className="text-sm font-semibold text-slate-900">Notifications</h3>
                                <button className="text-xs text-blue-600 hover:text-blue-700">Mark all read</button>
                            </div>
                            <div className="max-h-64 overflow-y-auto p-2">
                                <div className="rounded-lg bg-blue-50/50 px-3 py-2.5">
                                    <p className="text-sm text-slate-700">New job posted by TechCorp</p>
                                    <p className="mt-0.5 text-xs text-slate-400">5 minutes ago</p>
                                </div>
                                <div className="mt-1 rounded-lg px-3 py-2.5 hover:bg-slate-50">
                                    <p className="text-sm text-slate-700">User reported inappropriate content</p>
                                    <p className="mt-0.5 text-xs text-slate-400">1 hour ago</p>
                                </div>
                            </div>
                            <div className="border-t border-slate-50 p-2">
                                <Link
                                    href="/admin/notifications"
                                    className="block rounded-lg py-2 text-center text-xs font-medium text-blue-600 hover:bg-blue-50"
                                    onClick={() => setNotificationsOpen(false)}
                                >
                                    View all notifications
                                </Link>
                            </div>
                        </div>
                    )}
                </div>

                {/* Divider */}
                <div className="mx-1 h-6 w-px bg-slate-200" />

                {/* Admin Profile */}
                <div ref={profileRef} className="relative">
                    <button
                        onClick={() => setProfileOpen(!profileOpen)}
                        className="flex items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-slate-50 transition-colors"
                    >
                        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-red-500 to-rose-600 text-xs font-bold text-white">
                            {adminName.charAt(0)}
                        </div>
                        <div className="hidden text-left sm:block">
                            <p className="text-sm font-medium text-slate-700">{adminName}</p>
                            <p className="text-[10px] font-semibold uppercase tracking-wider text-red-500">Super Admin</p>
                        </div>
                        <ChevronDown className="h-3.5 w-3.5 text-slate-400" />
                    </button>

                    {profileOpen && (
                        <div className="absolute right-0 top-full mt-2 w-56 rounded-xl border border-slate-100 bg-white p-1.5 shadow-xl">
                            <div className="border-b border-slate-50 px-3 py-2.5 mb-1">
                                <p className="text-sm font-semibold text-slate-900">{adminName}</p>
                                <p className="text-xs text-slate-500">{adminEmail}</p>
                            </div>
                            <Link href="/admin/profile" className="flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-slate-700 hover:bg-slate-50" onClick={() => setProfileOpen(false)}>
                                <User className="h-4 w-4 text-slate-400" /> View Profile
                            </Link>
                            <Link href="/admin/settings" className="flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-slate-700 hover:bg-slate-50" onClick={() => setProfileOpen(false)}>
                                <Settings className="h-4 w-4 text-slate-400" /> Admin Settings
                            </Link>
                            <Link href="/admin/audit" className="flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-slate-700 hover:bg-slate-50" onClick={() => setProfileOpen(false)}>
                                <Activity className="h-4 w-4 text-slate-400" /> Activity Log
                            </Link>
                            <Link href="/" className="flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-slate-700 hover:bg-slate-50" onClick={() => setProfileOpen(false)}>
                                <Eye className="h-4 w-4 text-slate-400" /> Switch to User View
                            </Link>
                            <div className="my-1 border-t border-slate-100" />
                            <button 
                                onClick={async () => {
                                    try {
                                        const response = await fetch('/api/admin/auth/logout', {
                                            method: 'POST',
                                        });
                                        if (response.ok) {
                                            router.push('/admin/login');
                                            router.refresh();
                                        }
                                    } catch (error) {
                                        console.error('Logout failed:', error);
                                    }
                                }}
                                className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-red-600 hover:bg-red-50"
                            >
                                <LogOut className="h-4 w-4" /> Log Out
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </header>
    );
}
