"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Search,
  Globe,
  Menu,
  ChevronRight,
  ShieldCheck,
  Zap,
  LogOut,
} from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { SpotlightDialog } from "./SpotlightDialog";
import { useDashboardShell } from "./DashboardShellContext";
import { apiFetch } from "@/lib/csrf/client";
import { FREE_SCAN_LIMIT, LAUNCH_BONUS_SCANS } from "@/lib/limits";

interface TopNavProps {
  onTriggerScan?: () => void;
}

export interface BreadcrumbMeta {
  parentDe: string;
  parentEn: string;
  currentDe: string;
  currentEn: string;
}

export function getRouteBreadcrumbs(pathname: string): BreadcrumbMeta {
  if (pathname.startsWith("/dashboard/activity")) {
    return {
      parentDe: "Dashboard",
      parentEn: "Dashboard",
      currentDe: "Beleg-Archiv & Validierung",
      currentEn: "Activity & Ingestion Archive",
    };
  }
  if (pathname.startsWith("/dashboard/export")) {
    return {
      parentDe: "Dashboard",
      parentEn: "Dashboard",
      currentDe: "Export Control & CSV",
      currentEn: "Export Control & CSV",
    };
  }
  if (pathname.startsWith("/dashboard/settings")) {
    return {
      parentDe: "Dashboard",
      parentEn: "Dashboard",
      currentDe: "Systemeinstellungen",
      currentEn: "Account & Preferences",
    };
  }
  if (pathname.startsWith("/dashboard/pricing")) {
    return {
      parentDe: "Dashboard",
      parentEn: "Dashboard",
      currentDe: "Preise & Pläne",
      currentEn: "Pricing & Plans",
    };
  }
  if (pathname.startsWith("/dashboard/projects")) {
    return {
      parentDe: "Dashboard",
      parentEn: "Dashboard",
      currentDe: "Projekte & Ordner",
      currentEn: "Projects & Folders",
    };
  }
  // Default to Overview
  return {
    parentDe: "Dashboard",
    parentEn: "Dashboard",
    currentDe: "Beleg- & Spesen-Zentrale",
    currentEn: "Expense & Ingestion Hub",
  };
}

export function TopNav({ onTriggerScan }: TopNavProps) {
  const { language, setLanguage } = useI18n();
  const isDe = language === "de";
  const pathname = usePathname();
  const [isSpotlightOpen, setIsSpotlightOpen] = useState(false);
  const { isMobileDrawerOpen, toggleMobileDrawer } = useDashboardShell();

  // Subscription / Quota state for the header badge
  const [sessionInfo, setSessionInfo] = useState<{
    isPro: boolean;
    scanCount: number;
    scanLimit: number;
  } | null>(null);

  const [isSigningOut, setIsSigningOut] = useState(false);

  const breadcrumb = getRouteBreadcrumbs(pathname || "/dashboard");

  // Load session information on mount and path change
  useEffect(() => {
    let active = true;
    apiFetch("/api/auth/session")
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (active && data?.user) {
          const u = data.user;
          const isPro = Boolean(u.isPro);
          const limit = isPro
            ? Infinity
            : u.launchBonus
            ? LAUNCH_BONUS_SCANS
            : (u.freeScanAllowance || FREE_SCAN_LIMIT);
          setSessionInfo({
            isPro,
            scanCount: Number(u.scanCount ?? 0),
            scanLimit: limit,
          });
        }
      })
      .catch(() => {});
    return () => {
      active = false;
    };
  }, [pathname]);

  // Global CMD+K / CTRL+K keyboard shortcut listener
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setIsSpotlightOpen((prev) => !prev);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, []);

  const handleSignOut = async () => {
    setIsSigningOut(true);
    try {
      await apiFetch("/api/auth/logout", { method: "POST" });
    } catch (err) {
      console.error("Sign out error:", err);
    } finally {
      try {
        localStorage.removeItem("is_pro_user");
        localStorage.removeItem("license_key");
      } catch {}
      window.location.href = "/auth/login";
    }
  };

  return (
    <>
      <header
        data-testid="dashboard-topnav"
        className="h-20 bg-white border-b border-[#E2E8F0] px-4 sm:px-6 lg:px-8 flex items-center justify-between font-sans shrink-0 gap-3 z-30 sticky top-0"
      >
        {/* Left Section: Mobile Hamburger Toggle + Dynamic Breadcrumb */}
        <div className="flex items-center gap-3 sm:gap-4 min-w-0">
          {/* Mobile Hamburger Button */}
          <button
            type="button"
            data-testid="mobile-hamburger-btn"
            onClick={toggleMobileDrawer}
            aria-label="Open navigation menu"
            aria-expanded={isMobileDrawerOpen}
            className="md:hidden p-2 border border-[#E2E8F0] hover:border-black text-black transition-colors shrink-0 flex items-center justify-center"
          >
            <Menu className="w-5 h-5" />
          </button>

          {/* Breadcrumb Navigation */}
          <nav
            aria-label="Breadcrumb"
            data-testid="topnav-breadcrumbs"
            className="flex items-center gap-1.5 font-mono text-xs text-[#64748B] min-w-0"
          >
            <span className="hidden sm:inline hover:text-black transition-colors font-medium">
              {isDe ? breadcrumb.parentDe : breadcrumb.parentEn}
            </span>
            <ChevronRight className="hidden sm:inline w-3 h-3 text-[#94A3B8] shrink-0" />
            <span className="font-semibold text-black truncate text-xs sm:text-xs">
              {isDe ? breadcrumb.currentDe : breadcrumb.currentEn}
            </span>
          </nav>
        </div>

        {/* Center / Search Input Trigger (CMD+K to search system) */}
        <div className="flex items-center gap-3 w-full max-w-xs md:max-w-sm lg:max-w-md shrink">
          <div
            onClick={() => setIsSpotlightOpen(true)}
            data-testid="spotlight-search-trigger"
            className="relative w-full cursor-pointer group"
          >
            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-[#94A3B8] group-hover:text-black transition-colors" />
            <input
              type="text"
              readOnly
              onClick={() => setIsSpotlightOpen(true)}
              placeholder={isDe ? "CMD+K für Schnellsuche..." : "CMD+K to search system..."}
              className="w-full pl-10 pr-12 py-2 bg-[#F8FAFC] border border-[#E2E8F0] group-hover:border-black font-mono text-xs text-black placeholder:text-[#94A3B8] cursor-pointer transition-colors focus:outline-none"
            />
            <kbd className="hidden sm:block absolute right-3 top-1/2 -translate-y-1/2 font-mono text-[10px] text-[#64748B] bg-white border border-[#E2E8F0] px-1.5 py-0.5 group-hover:border-black group-hover:text-black transition-colors">
              ⌘K
            </kbd>
          </div>
        </div>

        {/* Right Controls */}
        <div className="flex items-center gap-2 sm:gap-4 shrink-0">
          {/* Subscription / Quota Badge (replaces System Online / Nominal) */}
          {sessionInfo?.isPro ? (
            <Link
              href="/dashboard/pricing"
              data-testid="system-status-indicator"
              className="hidden lg:flex items-center gap-2 px-3 py-1.5 bg-emerald-50 border border-emerald-300 font-mono text-[11px] uppercase tracking-wider text-emerald-900 hover:border-emerald-600 transition-colors"
              title={isDe ? "Abonnement verwalten" : "Manage subscription"}
            >
              <Zap className="w-3.5 h-3.5 text-emerald-600 shrink-0" />
              <span className="font-bold">{isDe ? "PRO-KONTO AKTIV" : "PRO ACTIVE"}</span>
            </Link>
          ) : (
            <Link
              href="/dashboard/pricing"
              data-testid="system-status-indicator"
              className="hidden lg:flex items-center gap-2 px-3 py-1.5 bg-[#EEF4FC] border border-[#E2E8F0] hover:border-black font-mono text-[11px] uppercase tracking-wider text-[#475569] hover:text-black transition-colors"
              title={isDe ? "Zu Pro upgraden" : "Upgrade to Pro"}
            >
              <ShieldCheck className="w-3.5 h-3.5 text-black shrink-0" />
              <span>
                {isDe
                  ? `FREE: ${sessionInfo?.scanCount ?? 0}/${sessionInfo?.scanLimit ?? FREE_SCAN_LIMIT} SCANS`
                  : `FREE: ${sessionInfo?.scanCount ?? 0}/${sessionInfo?.scanLimit ?? FREE_SCAN_LIMIT} SCANS`}
              </span>
            </Link>
          )}

          {/* Language Switch */}
          <button
            onClick={() => setLanguage(isDe ? "en" : "de")}
            data-testid="language-switch-btn"
            className="flex items-center gap-1 font-mono text-xs px-2.5 py-1.5 border border-[#E2E8F0] hover:border-black text-[#475569] hover:text-black transition-colors"
            title="Switch Language"
            aria-label={`Switch language to ${isDe ? "English" : "German"}`}
          >
            <Globe className="w-3.5 h-3.5" />
            <span className="font-semibold uppercase">{language}</span>
          </button>

          {/* Sign-Out Button (replaces Landing Page and Bell buttons) */}
          <button
            type="button"
            onClick={handleSignOut}
            disabled={isSigningOut}
            data-testid="topnav-signout-btn"
            className="flex items-center gap-1.5 font-mono text-xs uppercase tracking-caps text-[#475569] hover:text-red-700 hover:border-red-300 border border-[#E2E8F0] px-3 py-1.5 transition-colors font-medium bg-white disabled:opacity-50"
            title={isDe ? "Abmelden" : "Sign Out"}
          >
            <LogOut className="w-3.5 h-3.5" />
            <span className="hidden sm:inline font-medium">
              {isDe ? (isSigningOut ? "WIRD ABGEMELDET..." : "ABMELDEN") : (isSigningOut ? "SIGNING OUT..." : "SIGN OUT")}
            </span>
          </button>
        </div>
      </header>

      {/* Global CMD+K Spotlight Dialog */}
      <SpotlightDialog
        isOpen={isSpotlightOpen}
        onClose={() => setIsSpotlightOpen(false)}
        onTriggerScan={onTriggerScan}
      />
    </>
  );
}
