"use client";

import { useMemo, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { apiPost } from "@/lib/api";
import { AppNotificationBell } from "@/components/notifications/app-notification-bell";
import type { User } from "@/types";

const PAGE_LABELS: Array<{ match: RegExp; label: string; description: string }> = [
  { match: /^\/dashboard/, label: "CORI Briefing", description: "Daily business briefing, check-ins, and plain next steps" },
  { match: /^\/dispatch/, label: "Dispatch Board", description: "Live loads and urgent work" },
  { match: /^\/loads/, label: "Loads", description: "Find loads and open the record that needs work" },
  { match: /^\/routes/, label: "Routes", description: "Pick load, truck, and driver before route advice" },
  { match: /^\/fleet-map/, label: "Fleet Map", description: "Live and estimated positions for dispatched workspace trucks" },
  { match: /^\/cori\/quotes/, label: "CORI's Quotes", description: "Guided broker quote calls and call help" },
  { match: /^\/cori\/financial/, label: "CORI Financial", description: "Financial briefing, truck earnings, and plain money follow-up" },
  { match: /^\/cori\/mail/, label: "CORI Mail", description: "Email briefing, safe draft replies, and user-approved send controls" },
  { match: /^\/cori/, label: "Ask CORI", description: "Focused dispatcher chat and guided assistance" },
  { match: /^\/notifications/, label: "Notifications", description: "Alerts for dispatch, paperwork, billing, and tasks" },
  { match: /^\/documents/, label: "Paperwork", description: "Missing proof, PODs, BOLs, and load documents" },
  { match: /^\/billing/, label: "Billing Records", description: "Invoices, unpaid loads, and payment follow-up" },
  { match: /^\/drivers/, label: "Drivers", description: "Driver list, truck links, and follow-up" },
  { match: /^\/trucks/, label: "Trucks", description: "Fleet, units, and equipment records" },
  { match: /^\/owner-operators/, label: "Owner Operators", description: "Owner operator list, truck links, and follow-up" },
  { match: /^\/crm/, label: "CRM Overview", description: "Leads, relationships, and follow-up" },
  { match: /^\/brokers/, label: "Brokers", description: "Broker list and follow-up" },
  { match: /^\/shippers/, label: "Shippers", description: "Shipper list and follow-up" },
  { match: /^\/companies/, label: "Companies", description: "Company list and follow-up" },
  { match: /^\/profile/, label: "Profile & Security", description: "Identity, password, and sign-in protection" },
  { match: /^\/company\/integrations/, label: "Third-Party Integrations", description: "Email, maps, voice, accounting, payments, and future API connections" },
  { match: /^\/company/, label: "Workspace Settings", description: "Company profile, users, notification settings, and setup" },
];

export function Topbar({ user, onOpenMenu }: { user: User; onOpenMenu?: () => void }) {
  const router = useRouter();
  const pathname = usePathname();
  const [working, setWorking] = useState(false);

  async function logout() {
    try {
      setWorking(true);
      await apiPost("/api/auth/logout", {});
      window.location.href = "/login";
    } catch {
      router.push("/login");
    } finally {
      setWorking(false);
    }
  }

  const displayName = [user?.firstName, user?.lastName].filter(Boolean).join(" ") || user?.email || "Connected session";
  const pageMeta = useMemo(() => PAGE_LABELS.find((entry) => entry.match.test(pathname)) ?? {
    label: "Workspace",
    description: "Use the sidebar to move between work areas.",
  }, [pathname]);

  return (
    <header className="border-b border-slate-200 bg-white/90 backdrop-blur">
      <div className="flex flex-col gap-4 px-4 py-4 sm:px-6 lg:px-8">
        <div className="flex items-start justify-between gap-4">
          <div className="flex min-w-0 items-start gap-3">
            <button
              type="button"
              onClick={onOpenMenu}
              className="inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-slate-200 bg-white text-slate-700 xl:hidden"
              aria-label="Open navigation"
            >
              ☰
            </button>
            <div className="min-w-0">
              <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Current workspace area</div>
              <div className="mt-1 truncate text-2xl font-semibold tracking-tight text-slate-950">{pageMeta.label}</div>
              <p className="mt-1 max-w-2xl text-sm text-slate-500">{pageMeta.description}</p>
            </div>
          </div>

          <div className="hidden items-center gap-2 xl:flex">
            <AppNotificationBell />
            <div className="rounded-2xl border border-slate-200 bg-slate-50 px-3 py-2 text-right">
              <div className="text-xs text-slate-500">Signed in</div>
              <div className="text-sm font-semibold text-slate-900">{displayName}</div>
            </div>
            <button
              onClick={logout}
              disabled={working}
              className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-medium text-slate-700 disabled:opacity-60"
            >
              {working ? "Signing out..." : "Log out"}
            </button>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <div className="inline-flex rounded-full bg-slate-100 px-3 py-1.5 text-xs font-medium text-slate-700">
            {user?.organization?.name || "Dispatch Spot Company"}
          </div>
          <div className="inline-flex rounded-full bg-slate-100 px-3 py-1.5 text-xs font-medium text-slate-700">
            {user?.role === "ORG_ADMIN" ? "Company Admin" : user?.role === "DISPATCHER" ? "Dispatcher" : user?.role || "Connected user"}
          </div>
          <div className={`inline-flex rounded-full px-3 py-1.5 text-xs font-medium ${user?.emailVerifiedAt ? "bg-emerald-50 text-emerald-700" : "bg-amber-50 text-amber-700"}`}>
            {user?.emailVerifiedAt ? "Email verified" : "Email verification needed"}
          </div>
          <div className={`inline-flex rounded-full px-3 py-1.5 text-xs font-medium ${user?.authSession?.challengeSatisfied ? "bg-blue-50 text-blue-700" : "bg-slate-100 text-slate-700"}`}>
            {user?.authSession?.challengeSatisfied ? (user?.authSession?.graceActive ? "Trusted 2FA session" : "2FA verified this session") : "Standard session"}
          </div>
          <div className="xl:hidden"><AppNotificationBell /></div>
          <button
            onClick={logout}
            disabled={working}
            className="rounded-full border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-700 xl:hidden"
          >
            {working ? "Signing out..." : "Log out"}
          </button>
        </div>
      </div>
    </header>
  );
}
