"use client";

import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import {
  Menu,
  Bell,
  Calendar,
  User,
  ShieldCheck,
  LogOut,
  ChevronDown,
  Settings,
  Sparkles,
  KeyRound,
} from "lucide-react";
import { brandConfig } from "@/config/brand";
import { Badge } from "@/components/ui/Badge";
import { cn } from "@/lib/utils";
import { useAuth } from "@/context/AuthContext";

interface TopbarProps {
  onOpenMobileDrawer: () => void;
  className?: string;
}

const TopbarComponent: React.FC<TopbarProps> = ({
  onOpenMobileDrawer,
  className,
}) => {
  const { user, logout } = useAuth();
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const displayName = user?.name || "Admin BPI 1";
  const displayRole = user?.role || "Super Administrator";
  const displayIdentifier =
    user?.email ||
    user?.id_induk ||
    (user?.username ? `@${user.username}` : "admin@smabpi1bdr.sch.id");

  return (
    <header
      className={cn(
        "h-16 bg-white border-b border-brand-border px-4 sm:px-6 flex items-center justify-between sticky top-0 z-20 shadow-[0_1px_2px_rgba(15,23,42,0.03)]",
        className
      )}
    >
      {/* Left side: Hamburger (mobile) + System Identity */}
      <div className="flex items-center gap-2 sm:gap-3 min-w-0">
        <button
          onClick={onOpenMobileDrawer}
          className="lg:hidden p-2.5 -ml-1.5 rounded-lg text-brand-secondary hover:text-brand-text hover:bg-slate-100 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-blue/30 shrink-0"
          aria-label="Buka menu navigasi"
        >
          <Menu className="w-5 h-5" />
        </button>

        <div className="flex items-center gap-2 min-w-0">
          <span className="font-bold text-sm sm:text-base text-brand-text truncate">
            {brandConfig.appName}
          </span>
          <span className="hidden md:inline-block text-xs text-brand-secondary font-medium truncate">
            &bull; {brandConfig.shortSchoolName}
          </span>
        </div>
      </div>

      {/* Right side: Academic year badge, notifications, and profile chip */}
      <div className="flex items-center gap-2.5 sm:gap-4">
        {/* Academic year badge */}
        <div className="hidden md:flex items-center gap-1.5 px-3 py-1 rounded-full bg-slate-100 border border-slate-200 text-xs text-brand-text font-medium">
          <Calendar className="w-3.5 h-3.5 text-brand-blue" />
          <span>
            TA {brandConfig.academicYear.current} &bull; Semester{" "}
            {brandConfig.academicYear.semester}
          </span>
        </div>

        {/* Notification Bell */}
        <button
          className="relative p-2 rounded-full text-brand-secondary hover:text-brand-text hover:bg-slate-100 transition-colors"
          aria-label="Lihat notifikasi"
          title="Notifikasi"
        >
          <Bell className="w-4 h-4 sm:w-5 sm:h-5" />
          <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-brand-blue rounded-full ring-2 ring-white" />
        </button>

        {/* User Profile Avatar / Chip with Dropdown */}
        <div className="relative pl-2 sm:pl-3 border-l border-brand-border" ref={dropdownRef}>
          <button
            type="button"
            onClick={() => setDropdownOpen((prev) => !prev)}
            className="flex items-center gap-2.5 p-1 rounded-xl hover:bg-slate-100/80 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-blue/30 text-left"
            aria-expanded={dropdownOpen}
            aria-haspopup="true"
          >
            <div className="w-8 h-8 rounded-full bg-brand-navy text-white flex items-center justify-center font-bold text-xs shadow-sm ring-2 ring-blue-50">
              {displayName.charAt(0).toUpperCase()}
            </div>

            <div className="hidden sm:flex flex-col text-left">
              <div className="flex items-center gap-1.5">
                <span className="text-xs font-bold text-brand-text leading-tight max-w-[140px] truncate">
                  {displayName}
                </span>
                <ShieldCheck className="w-3.5 h-3.5 text-brand-blue shrink-0" />
              </div>
              <span className="text-[10px] text-brand-secondary max-w-[140px] truncate">
                {displayRole}
              </span>
            </div>

            <ChevronDown
              className={cn(
                "w-3.5 h-3.5 text-slate-400 transition-transform duration-200 hidden sm:block",
                dropdownOpen && "rotate-180"
              )}
            />
          </button>

          {/* Profile Dropdown Menu */}
          {dropdownOpen && (
            <div className="absolute right-0 mt-2 w-64 bg-white rounded-2xl shadow-xl border border-slate-200/90 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150">
              {/* User Identity Header */}
              <div className="px-4 py-3 border-b border-slate-100 bg-slate-50/50">
                <p className="text-xs font-bold text-slate-900 truncate">
                  {displayName}
                </p>
                <p className="text-[11px] text-slate-500 truncate mt-0.5">
                  {displayIdentifier}
                </p>
                <div className="mt-2">
                  <Badge variant="primary" size="sm" className="text-[10px] font-semibold">
                    {displayRole}
                  </Badge>
                </div>
              </div>

              {/* Action Links */}
              <div className="py-1 text-xs">
                <Link
                  href="/user-manajemen"
                  onClick={() => setDropdownOpen(false)}
                  className="flex items-center gap-2.5 px-4 py-2 text-slate-700 hover:bg-slate-50 hover:text-brand-blue transition-colors"
                >
                  <Settings className="w-4 h-4 text-slate-400" />
                  <span>Manajemen Pengguna</span>
                </Link>
                <Link
                  href="/pengaturan"
                  onClick={() => setDropdownOpen(false)}
                  className="flex items-center gap-2.5 px-4 py-2 text-slate-700 hover:bg-slate-50 hover:text-brand-blue transition-colors"
                >
                  <KeyRound className="w-4 h-4 text-slate-400" />
                  <span>Pengaturan Sistem</span>
                </Link>
              </div>

              {/* Divider */}
              <div className="border-t border-slate-100 my-1" />

              {/* Logout Button */}
              <div className="px-2 pt-1">
                <button
                  type="button"
                  onClick={() => {
                    setDropdownOpen(false);
                    logout();
                  }}
                  className="w-full flex items-center gap-2.5 px-3 py-2 text-xs font-semibold text-rose-600 hover:bg-rose-50 rounded-xl transition-colors"
                >
                  <LogOut className="w-4 h-4 text-rose-500" />
                  <span>Keluar dari Aplikasi (Logout)</span>
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </header>
  );
};

export const Topbar = React.memo(TopbarComponent);
