"use client";

import * as React from "react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
  Bell,
  Building2,
  Check,
  ChevronDown,
  HelpCircle,
  LogOut,
  Menu,
  Search,
  Settings,
  Shield,
  User as UserIcon,
} from "lucide-react";
import { SMC_COMPANIES, type CompanyFilterCode } from "@/lib/config/navigation";
import { cn, getInitials } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { CompanyPill } from "@/components/shared/company-pill";

export interface TopbarNotification {
  id: string;
  title: string;
  body: string;
  companyCode: string;
  linkUrl: string;
  isRead: boolean;
  timeAgo: string;
}

interface TopbarProps {
  onOpenMobileMenu: () => void;
  onOpenSearch: () => void;
  user: {
    name: string;
    email: string;
    roleLabel: string;
  };
  initialNotifications: TopbarNotification[];
}

export function Topbar({
  onOpenMobileMenu,
  onOpenSearch,
  user,
  initialNotifications,
}: TopbarProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const currentCompany = (searchParams.get("company") ?? "ALL") as CompanyFilterCode;
  const activeCompanyObj =
    SMC_COMPANIES.find((c) => c.code === currentCompany) ?? SMC_COMPANIES[0];

  const [notifications, setNotifications] = React.useState(initialNotifications);
  const [helpOpen, setHelpOpen] = React.useState(false);

  const unreadCount = notifications.filter((n) => !n.isRead).length;

  const handleSelectCompany = (code: CompanyFilterCode) => {
    const params = new URLSearchParams(searchParams.toString());
    if (code === "ALL") {
      params.delete("company");
    } else {
      params.set("company", code);
    }
    const qs = params.toString();
    router.push(qs ? `${pathname}?${qs}` : pathname);
  };

  const markAllRead = () => {
    setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
  };

  return (
    <>
      <header className="sticky top-0 z-30 flex h-[60px] shrink-0 items-center justify-between gap-3 border-b border-[#E5E7EB] bg-white/95 px-4 backdrop-blur supports-[backdrop-filter]:bg-white/85 lg:px-6">
        {/* Left: Mobile trigger + Company Selector */}
        <div className="flex items-center gap-2.5">
          <button
            type="button"
            onClick={onOpenMobileMenu}
            aria-label="Open navigation menu"
            className="rounded-lg p-2 text-[#475569] hover:bg-[#F1F5F9] lg:hidden"
          >
            <Menu className="h-5 w-5" />
          </button>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button
                type="button"
                className="flex h-9 items-center gap-2 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-3 text-xs font-medium text-[#111827] transition-colors hover:border-[#CBD5E1] hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/30"
              >
                <Building2 className="h-3.5 w-3.5 text-brand" />
                <span className="max-w-[160px] truncate sm:max-w-[220px]">
                  {activeCompanyObj.name}
                </span>
                <ChevronDown className="h-3.5 w-3.5 text-[#64748B]" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start" className="w-64">
              <DropdownMenuLabel>SMC Cement Group Scope</DropdownMenuLabel>
              {SMC_COMPANIES.map((company) => (
                <DropdownMenuItem
                  key={company.code}
                  onClick={() => handleSelectCompany(company.code)}
                  className="justify-between"
                >
                  <div className="flex items-center gap-2">
                    <CompanyPill code={company.code === "ALL" ? "SMC" : company.code} />
                    <span>{company.name}</span>
                  </div>
                  {currentCompany === company.code && <Check className="h-3.5 w-3.5 text-brand" />}
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
        </div>

        {/* Right: Global Search, Notifications, Help, User Profile */}
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={onOpenSearch}
            className="flex h-9 items-center gap-2 rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] px-3 text-xs text-[#64748B] transition-colors hover:border-[#CBD5E1] hover:bg-white sm:w-64 md:w-72"
          >
            <Search className="h-3.5 w-3.5 shrink-0 text-[#94A3B8]" />
            <span className="hidden flex-1 truncate text-left sm:inline">Search anything...</span>
            <kbd className="hidden rounded border border-[#E5E7EB] bg-white px-1.5 py-0.5 font-mono text-[10px] font-medium text-[#64748B] sm:inline">
              Ctrl K
            </kbd>
          </button>

          {/* Notifications Dropdown */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button
                type="button"
                aria-label="Notifications"
                className="relative flex h-9 w-9 items-center justify-center rounded-lg border border-transparent text-[#475569] transition-colors hover:border-[#E5E7EB] hover:bg-[#F8FAFC] hover:text-[#111827]"
              >
                <Bell className="h-4 w-4" />
                {unreadCount > 0 && (
                  <span className="absolute right-2 top-2 h-2 w-2 rounded-full bg-status-danger ring-2 ring-white" />
                )}
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-80 p-0">
              <div className="flex items-center justify-between border-b border-[#E5E7EB] px-3.5 py-2.5">
                <span className="text-xs font-semibold text-[#111827]">
                  Notifications ({unreadCount} unread)
                </span>
                {unreadCount > 0 && (
                  <button
                    type="button"
                    onClick={markAllRead}
                    className="text-[11px] font-medium text-brand hover:underline"
                  >
                    Mark all read
                  </button>
                )}
              </div>
              <div className="max-h-72 divide-y divide-[#F1F5F9] overflow-y-auto">
                {notifications.map((n) => (
                  <Link
                    key={n.id}
                    href={n.linkUrl}
                    className={cn(
                      "block px-3.5 py-3 transition-colors hover:bg-[#F8FAFC]",
                      !n.isRead && "bg-brand-soft/40"
                    )}
                  >
                    <div className="flex items-center justify-between gap-2">
                      <CompanyPill code={n.companyCode} />
                      <span className="text-[10px] text-[#64748B]">{n.timeAgo}</span>
                    </div>
                    <p className="mt-1.5 text-xs font-medium text-[#111827]">{n.title}</p>
                    <p className="mt-0.5 text-[11px] leading-relaxed text-[#64748B]">{n.body}</p>
                  </Link>
                ))}
              </div>
            </DropdownMenuContent>
          </DropdownMenu>

          {/* Help Button */}
          <button
            type="button"
            onClick={() => setHelpOpen(true)}
            aria-label="Help and documentation"
            className="flex h-9 w-9 items-center justify-center rounded-lg border border-transparent text-[#475569] transition-colors hover:border-[#E5E7EB] hover:bg-[#F8FAFC] hover:text-[#111827]"
          >
            <HelpCircle className="h-4 w-4" />
          </button>

          {/* User Profile Menu */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button
                type="button"
                className="flex h-9 items-center gap-2 rounded-lg pl-1.5 pr-2 transition-colors hover:bg-[#F8FAFC]"
              >
                <div className="flex h-7 w-7 items-center justify-center rounded-full bg-brand text-[11px] font-semibold text-white">
                  {getInitials(user.name)}
                </div>
                <ChevronDown className="hidden h-3.5 w-3.5 text-[#64748B] sm:block" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-60">
              <div className="px-2.5 py-2">
                <p className="text-xs font-semibold text-[#111827]">{user.name}</p>
                <p className="truncate text-[11px] text-[#64748B]">{user.email}</p>
                <span className="mt-1.5 inline-flex items-center gap-1 rounded-full bg-brand-soft px-2 py-0.5 text-[10px] font-medium text-brand">
                  <Shield className="h-2.5 w-2.5" />
                  {user.roleLabel}
                </span>
              </div>
              <DropdownMenuSeparator />
              <DropdownMenuItem asChild>
                <Link href="/people">
                  <UserIcon className="h-3.5 w-3.5" />
                  My Profile
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem asChild>
                <Link href="/settings">
                  <Settings className="h-3.5 w-3.5" />
                  System Settings
                </Link>
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem asChild>
                <Link href="/login" className="text-status-danger focus:text-status-danger">
                  <LogOut className="h-3.5 w-3.5" />
                  Sign out
                </Link>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </header>

      {/* Help Modal */}
      <Dialog open={helpOpen} onOpenChange={setHelpOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>PEOPLEFLOW Enterprise Help</DialogTitle>
            <DialogDescription>
              SMC Cement Group Employee Lifecycle Management Platform (ECC · NCC · SCII)
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3 text-xs text-[#334155]">
            <div className="rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] p-3">
              <p className="font-semibold text-[#111827]">Keyboard Shortcuts</p>
              <div className="mt-2 flex items-center justify-between">
                <span>Open Global Search</span>
                <kbd className="rounded border border-[#E5E7EB] bg-white px-2 py-0.5 font-mono text-[11px]">
                  Ctrl + K
                </kbd>
              </div>
            </div>
            <div className="rounded-lg border border-[#E5E7EB] bg-[#F8FAFC] p-3">
              <p className="font-semibold text-[#111827]">IT & HR Governance Support</p>
              <p className="mt-1 text-[#64748B]">
                For access requests, Microsoft Entra ID SSO onboarding, or company data scope
                adjustments across ECC, NCC, and SCII, contact Group Enterprise IT Service Desk.
              </p>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
