"use client";

import * as React from "react";
import Link from "next/link";
import { AuthSession } from "@/types";
import { formatDayDateID } from "@/lib/utils";
import {
  Menu,
  Bell,
  Search,
  User as UserIcon,
  LogOut,
  ExternalLink,
  CheckCheck,
} from "lucide-react";

interface NavbarProps {
  user: AuthSession;
  collapsed: boolean;
  onOpenMobile: () => void;
  onOpenSearch?: () => void;
}

export function Navbar({
  user,
  collapsed,
  onOpenMobile,
  onOpenSearch,
}: NavbarProps) {
  const [showProfileMenu, setShowProfileMenu] = React.useState(false);
  const [showNotifications, setShowNotifications] = React.useState(false);
  const [notifications, setNotifications] = React.useState<any[]>([]);
  const [unreadCount, setUnreadCount] = React.useState(0);

  const currentDateStr = React.useMemo(() => formatDayDateID(new Date()), []);

  // Fetch notifications
  React.useEffect(() => {
    async function loadNotifications() {
      try {
        const res = await fetch("/api/notifications");
        if (res.ok) {
          const data = await res.json();
          if (data.success) {
            setNotifications(data.data.slice(0, 5));
            setUnreadCount(data.data.filter((n: any) => !n.isRead).length);
          }
        }
      } catch (err) {
        // quiet error
      }
    }
    loadNotifications();
  }, []);

  const handleMarkAllRead = async () => {
    try {
      await fetch("/api/notifications", { method: "PUT" });
      setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
      setUnreadCount(0);
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <header
      className={`sticky top-0 z-30 flex h-16 w-full items-center justify-between border-b border-slate-200/80 bg-white/95 px-4 md:px-6 backdrop-blur transition-all duration-300 ${
        collapsed ? "md:pl-24" : "md:pl-68"
      }`}
    >
      {/* Left items */}
      <div className="flex items-center gap-3">
        <button
          onClick={onOpenMobile}
          className="flex h-9 w-9 items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:bg-slate-100 md:hidden"
        >
          <Menu className="h-5 w-5" />
        </button>

        <div className="hidden lg:block">
          <p className="text-xs font-medium text-slate-500">{currentDateStr}</p>
          <p className="text-sm font-bold text-slate-800">
            Selamat datang, <span className="text-blue-600">{user.fullName}</span>
          </p>
        </div>
      </div>

      {/* Center Search trigger */}
      <div className="flex-1 max-w-md mx-4 hidden sm:block">
        <button
          type="button"
          onClick={onOpenSearch}
          className="flex h-9 w-full items-center justify-between rounded-xl border border-slate-200 bg-slate-50 px-3 text-xs text-slate-400 hover:border-slate-300 hover:bg-white transition-colors"
        >
          <span className="flex items-center gap-2">
            <Search className="h-3.5 w-3.5" />
            Cari materi, tugas, jadwal, atau pengumuman...
          </span>
          <kbd className="rounded border border-slate-200 bg-white px-1.5 py-0.5 text-[10px] font-medium text-slate-400">
            Ctrl+K
          </kbd>
        </button>
      </div>

      {/* Right items */}
      <div className="flex items-center gap-2">
        {/* Notification Bell */}
        <div className="relative">
          <button
            onClick={() => {
              setShowNotifications(!showNotifications);
              setShowProfileMenu(false);
            }}
            className="relative flex h-9 w-9 items-center justify-center rounded-xl border border-slate-200 text-slate-600 hover:bg-slate-100 transition-colors"
            title="Notifikasi"
          >
            <Bell className="h-4 w-4" />
            {unreadCount > 0 && (
              <span className="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-rose-500 text-[10px] font-bold text-white shadow-sm ring-2 ring-white animate-bounce">
                {unreadCount}
              </span>
            )}
          </button>

          {/* Notifications Dropdown */}
          {showNotifications && (
            <div className="absolute right-0 mt-2 w-80 rounded-2xl border border-slate-200 bg-white p-3 shadow-xl z-50 animate-in fade-in zoom-in-95">
              <div className="flex items-center justify-between border-b border-slate-100 pb-2 px-2">
                <span className="text-xs font-bold text-slate-800">
                  Notifikasi Pembelajaran
                </span>
                {unreadCount > 0 && (
                  <button
                    onClick={handleMarkAllRead}
                    className="flex items-center gap-1 text-[11px] font-medium text-blue-600 hover:text-blue-700"
                  >
                    <CheckCheck className="h-3.5 w-3.5" />
                    Tandai dibaca
                  </button>
                )}
              </div>

              <div className="max-h-64 overflow-y-auto divide-y divide-slate-100 py-1">
                {notifications.length === 0 ? (
                  <p className="py-6 text-center text-xs text-slate-400">
                    Tidak ada notifikasi baru
                  </p>
                ) : (
                  notifications.map((n) => (
                    <Link
                      key={n.id}
                      href={n.link || "#"}
                      onClick={() => setShowNotifications(false)}
                      className={`block px-3 py-2.5 rounded-lg text-xs hover:bg-slate-50 transition-colors ${
                        !n.isRead ? "bg-blue-50/60" : ""
                      }`}
                    >
                      <div className="flex items-center justify-between gap-1">
                        <p className="font-semibold text-slate-800 truncate">
                          {n.title}
                        </p>
                        {!n.isRead && (
                          <span className="h-1.5 w-1.5 rounded-full bg-blue-600 shrink-0" />
                        )}
                      </div>
                      <p className="mt-0.5 text-slate-500 line-clamp-2 leading-relaxed">
                        {n.message}
                      </p>
                    </Link>
                  ))
                )}
              </div>
            </div>
          )}
        </div>

        {/* User Profile dropdown */}
        <div className="relative">
          <button
            onClick={() => {
              setShowProfileMenu(!showProfileMenu);
              setShowNotifications(false);
            }}
            className="flex items-center gap-2 rounded-xl p-1.5 hover:bg-slate-100 transition-colors border border-transparent hover:border-slate-200"
          >
            <div className="h-8 w-8 rounded-lg bg-blue-600 flex items-center justify-center text-xs font-bold text-white shadow-sm">
              {user.fullName.substring(0, 2).toUpperCase()}
            </div>
            <div className="hidden text-left sm:block pr-1">
              <p className="text-xs font-bold text-slate-800 leading-none">
                {user.fullName.split(" ")[0]}
              </p>
              <span className="text-[10px] text-slate-500">
                {user.role}
              </span>
            </div>
          </button>

          {showProfileMenu && (
            <div className="absolute right-0 mt-2 w-56 rounded-2xl border border-slate-200 bg-white p-2 shadow-xl z-50 animate-in fade-in zoom-in-95">
              <div className="border-b border-slate-100 p-2.5">
                <p className="text-xs font-bold text-slate-900 truncate">
                  {user.fullName}
                </p>
                <p className="text-[11px] text-slate-500 truncate">
                  {user.username}
                </p>
              </div>

              <div className="py-1">
                <Link
                  href="/profile"
                  onClick={() => setShowProfileMenu(false)}
                  className="flex items-center gap-2 rounded-lg px-2.5 py-2 text-xs text-slate-700 hover:bg-slate-100"
                >
                  <UserIcon className="h-4 w-4 text-slate-400" />
                  Profil & Ganti Password
                </Link>
                <Link
                  href="/"
                  target="_blank"
                  className="flex items-center justify-between rounded-lg px-2.5 py-2 text-xs text-slate-700 hover:bg-slate-100"
                >
                  <span className="flex items-center gap-2">
                    <ExternalLink className="h-4 w-4 text-slate-400" />
                    Buka Landing Page
                  </span>
                </Link>
              </div>

              <div className="border-t border-slate-100 pt-1">
                <button
                  onClick={async () => {
                    await fetch("/api/auth/logout", { method: "POST" });
                    window.location.href = "/login";
                  }}
                  className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-xs text-rose-600 hover:bg-rose-50"
                >
                  <LogOut className="h-4 w-4" />
                  Keluar dari Sistem
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
