"use client";
// src/components/layout/Topbar.tsx
import { useAuth } from "@/hooks/useAuth";
import { useLanguage } from "@/i18n/LanguageContext";
import { getInitials } from "@/lib/utils";
import { cn } from "@/lib/utils";
import { GlobalSearch } from "./GlobalSearch";
import { ROLE_LABEL_KEYS } from "@/lib/roleLabels";
import {
  Bell, Globe, LogOut, User, Settings, ChevronDown, Menu,
} from "lucide-react";
import { useState, useRef, useEffect, useCallback } from "react";
import Link from "next/link";

interface TopbarProps {
  sidebarCollapsed: boolean;
  onMobileMenuToggle: () => void;
  breadcrumbs?: { label: string; href?: string }[];
}

export function Topbar({ sidebarCollapsed, onMobileMenuToggle, breadcrumbs }: TopbarProps) {
  const { user, logout } = useAuth();
  const { language, setLanguage, isRTL, t } = useLanguage();
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const [notifications, setNotifications] = useState<any[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const userMenuRef = useRef<HTMLDivElement>(null);
  const notifRef = useRef<HTMLDivElement>(null);

  const fetchNotifications = useCallback(() => {
    fetch("/api/notifications?take=10")
      .then(r => r.json())
      .then(d => {
        const items = d.data?.notifications ?? [];
        setNotifications(items);
        setUnreadCount(typeof d.data?.unreadCount === "number" ? d.data.unreadCount : items.filter((n: { isRead?: boolean }) => !n.isRead).length);
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    fetchNotifications();
  }, [fetchNotifications]);

  useEffect(() => {
    const onVis = () => {
      if (document.visibilityState === "visible") fetchNotifications();
    };
    document.addEventListener("visibilitychange", onVis);
    return () => document.removeEventListener("visibilitychange", onVis);
  }, [fetchNotifications]);

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (userMenuRef.current && !userMenuRef.current.contains(e.target as Node)) setUserMenuOpen(false);
      if (notifRef.current && !notifRef.current.contains(e.target as Node)) setNotifOpen(false);
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const markAllRead = async () => {
    try {
      await fetch("/api/notifications/read-all", { method: "POST" });
      setUnreadCount(0);
      setNotifications(prev => prev.map(n => ({ ...n, isRead: true })));
    } catch {}
  };

  return (
    <header
      className={cn(
        "fixed top-0 left-0 right-0 z-30 h-[60px] bg-card border-b border-border flex items-center px-2 sm:px-4 gap-1.5 sm:gap-3 transition-all duration-200 overflow-x-clip",
        isRTL
          ? `lg:${sidebarCollapsed ? "right-[68px]" : "right-[260px]"}`
          : `lg:${sidebarCollapsed ? "left-[68px]" : "left-[260px]"}`
      )}
    >
      {/* Mobile menu button */}
      <button
        onClick={onMobileMenuToggle}
        className="lg:hidden p-2 rounded-lg hover:bg-accent text-muted-foreground hover:text-foreground flex-shrink-0"
      >
        <Menu className="w-5 h-5" />
      </button>

      {/* Breadcrumbs — desktop only */}
      {breadcrumbs && breadcrumbs.length > 0 && (
        <nav className="hidden lg:flex items-center gap-1.5 text-sm flex-shrink-0">
          {breadcrumbs.map((crumb, i) => (
            <div key={i} className="flex items-center gap-1.5">
              {i > 0 && <span className="text-muted-foreground">/</span>}
              {crumb.href ? (
                <Link href={crumb.href} className="text-muted-foreground hover:text-foreground transition-colors font-medium">
                  {crumb.label}
                </Link>
              ) : (
                <span className="text-foreground font-semibold">{crumb.label}</span>
              )}
            </div>
          ))}
        </nav>
      )}

      {/* Mobile spacer keeps actions pinned to opposite edge */}
      <div className="flex-1 sm:hidden" />

      {/* Global Search — fills remaining space */}
      <div className="hidden sm:flex flex-1 justify-center max-w-lg mx-auto min-w-0">
        <GlobalSearch />
      </div>

      {/* Right side actions */}
      <div className="flex items-center gap-1 sm:gap-1.5 flex-shrink-0 min-w-0">
        {/* Language toggle */}
        <button
          onClick={() => setLanguage(language === "en" ? "ar" : "en")}
          className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-border hover:bg-accent text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
          title={t("topbar.toggleLanguage")}
        >
          <Globe className="w-4 h-4" />
          <span className="hidden sm:inline text-xs">{language === "en" ? "عربي" : "EN"}</span>
        </button>

        {/* Notifications */}
        <div className="relative" ref={notifRef}>
          <button
            onClick={() => setNotifOpen(!notifOpen)}
            className="relative p-2 rounded-lg hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
          >
            <Bell className="w-5 h-5" />
            {unreadCount > 0 && (
              <span className="absolute top-1 right-1 w-4 h-4 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center">
                {unreadCount > 9 ? "9+" : unreadCount}
              </span>
            )}
          </button>

          {notifOpen && (
            <div className={cn(
              "absolute top-full mt-1 w-[min(20rem,calc(100vw-1rem))] bg-popover border border-border rounded-xl shadow-xl z-50 overflow-hidden animate-fade-in",
              isRTL ? "left-0" : "right-0"
            )}>
              <div className="px-4 py-3 border-b border-border flex items-center justify-between">
                <span className="text-sm font-semibold text-foreground">{t("topbar.notifications")}</span>
                {unreadCount > 0 && (
                  <button onClick={markAllRead} className="text-xs text-primary hover:underline">
                    {t("topbar.markAllRead")}
                  </button>
                )}
              </div>
              <div className="max-h-80 overflow-y-auto">
                {notifications.length === 0 ? (
                  <div className="py-8 text-center text-sm text-muted-foreground">{t("topbar.noNotifications")}</div>
                ) : (
                  notifications.map((n: any) => (
                    <div key={n.id} className={cn(
                      "px-4 py-3 hover:bg-accent transition-colors border-b border-border last:border-0",
                      !n.isRead && "bg-primary/5"
                    )}>
                      <div className="flex items-start gap-2">
                        {!n.isRead && <div className="w-2 h-2 rounded-full bg-primary mt-1.5 flex-shrink-0" />}
                        <div className={!n.isRead ? "" : "pl-4"}>
                          <p className="text-sm font-medium text-foreground">{n.title}</p>
                          <p className="text-xs text-muted-foreground mt-0.5">{n.body}</p>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>
              <div className="px-4 py-2 border-t border-border">
                <Link href="/notifications" onClick={() => setNotifOpen(false)}
                  className="text-xs text-primary hover:underline block text-center">
                  {t("topbar.viewAllNotifications")}
                </Link>
              </div>
            </div>
          )}
        </div>

        {/* User menu */}
        <div className="relative" ref={userMenuRef}>
          <button
            onClick={() => setUserMenuOpen(!userMenuOpen)}
            className="flex items-center gap-1.5 sm:gap-2 pl-1 pr-1.5 sm:pr-2 py-1 rounded-lg hover:bg-accent transition-colors max-w-[140px] sm:max-w-none"
          >
            <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center text-white text-xs font-bold">
              {user ? getInitials(user.name) : "U"}
            </div>
            <div className="hidden sm:block text-left">
              <div className="text-xs font-semibold text-foreground leading-none">{user?.name}</div>
              <div className="text-[10px] text-muted-foreground mt-0.5">
                {user?.role && ROLE_LABEL_KEYS[user.role]
                  ? t(ROLE_LABEL_KEYS[user.role])
                  : user?.role?.replace(/_/g, " ")}
              </div>
            </div>
            <ChevronDown className="w-3.5 h-3.5 text-muted-foreground hidden sm:block" />
          </button>

          {userMenuOpen && (
            <div className={cn(
              "absolute top-full mt-1 w-48 bg-popover border border-border rounded-xl shadow-lg py-1 z-50 animate-fade-in",
              isRTL ? "left-0" : "right-0"
            )}>
              <div className="px-3 py-2 border-b border-border">
                <div className="text-sm font-semibold text-foreground">{user?.name}</div>
                <div className="text-xs text-muted-foreground truncate">{user?.email}</div>
              </div>
              <Link href="/settings" onClick={() => setUserMenuOpen(false)}
                className="flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-accent transition-colors">
                <User className="w-4 h-4" /> {t("topbar.profile")}
              </Link>
              <Link href="/settings" onClick={() => setUserMenuOpen(false)}
                className="flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-accent transition-colors">
                <Settings className="w-4 h-4" /> {t("nav.settings")}
              </Link>
              <div className="border-t border-border mt-1 pt-1">
                <button onClick={() => { setUserMenuOpen(false); logout(); }}
                  className="flex items-center gap-2 px-3 py-2 text-sm text-destructive hover:bg-accent w-full transition-colors">
                  <LogOut className="w-4 h-4" /> {t("auth.logout")}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
