"use client";

import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { LocaleSwitcher } from "@/src/components/LocaleSwitcher";
import { logout } from "@/src/lib/api/auth-session";
import { LogOut, Search, Building2, ArrowLeft } from "lucide-react";
import { useEffect, useState } from "react";
import { fetchMe, type Me } from "@/src/lib/api/me";
import { useNavHistory } from "@/src/lib/app/navigation-history";
import { TENANT_MENU } from "@/src/lib/app/menu-tenant";
import { ProfileDropdown } from "@/src/components/shared/ProfileDropdown";
import { CountrySelector } from "@/src/components/app/CountrySelector";

const NAVY  = "#1e1b4b";
const NAVY2 = "#312e81";
const TEAL  = "#818cf8";

type Props = { locale: string };

export default function TenantTopbar({ locale }: Props) {
  const router   = useRouter();
  const tCommon  = useTranslations("common");
  const tTopbar  = useTranslations("tenant.topbar");
  const tMenu    = useTranslations("tenant.menu");

  const { canGoBack, previousPath } = useNavHistory();

  const [me, setMe] = useState<Me | null>(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const data = await fetchMe();
        if (mounted) setMe(data);
      } catch {
        if (mounted) setMe(null);
      }
    })();
    return () => { mounted = false; };
  }, []);

  const tenantName = me?.active_tenant?.name ?? "—";
  const username   = me?.username ?? "—";
  const firstName  = me?.first_name ?? "";
  const lastName   = me?.last_name ?? "";
  const displayName = [firstName, lastName].filter(Boolean).join(" ") || username;
  const initials   = (firstName[0] ?? username[0] ?? "?").toUpperCase();

  // Resolve previous page name from tracked path
  const prevPageName = (() => {
    if (!previousPath) return ""
    const match = TENANT_MENU.find(item => previousPath.includes(item.href))
    return match ? tMenu(match.key as any) : ""
  })()

  async function onLogout() {
    try { await logout(); } finally { router.replace(`/${locale}/login`); }
  }

  return (
    <header className="sticky top-0 z-20">
      <div
        className="flex items-center justify-between gap-4 px-6 py-3"
        style={{
          background: "#fff",
          borderBottom: "1px solid rgba(15,23,42,0.07)",
          boxShadow: "0 1px 8px rgba(26,53,120,0.05)",
        }}
      >
        {/* ── LEFT : back button + tenant info ──────────────────────────── */}
        <div className="flex items-center gap-2.5 min-w-0">
          {/* Back button — visible only when there is in-app history */}
          {canGoBack && (
            <button
              onClick={() => router.back()}
              className="inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm font-medium transition-all shrink-0"
              style={{
                background: `${NAVY}08`,
                border: `1px solid ${NAVY}18`,
                color: NAVY,
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLElement).style.background = `${NAVY}14`
                ;(e.currentTarget as HTMLElement).style.borderColor = `${NAVY}30`
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLElement).style.background = `${NAVY}08`
                ;(e.currentTarget as HTMLElement).style.borderColor = `${NAVY}18`
              }}
            >
              <ArrowLeft className="h-4 w-4 shrink-0" />
              {prevPageName && (
                <span className="hidden sm:inline max-w-[120px] truncate">{prevPageName}</span>
              )}
            </button>
          )}

          <div
            className="h-8 w-8 rounded-lg flex items-center justify-center shrink-0"
            style={{ background: `${NAVY}12`, border: `1px solid ${NAVY}18` }}
          >
            <Building2 className="h-4 w-4" style={{ color: NAVY }} />
          </div>
          <div className="min-w-0">
            <div className="text-sm font-semibold text-slate-900 truncate leading-tight">{tenantName}</div>
            <div className="text-[11px] text-slate-400 leading-tight">@{username}</div>
          </div>
        </div>

        {/* ── CENTER : search ────────────────────────────────────────────── */}
        <div
          className="hidden md:flex flex-1 max-w-sm items-center gap-2 rounded-xl px-3 py-2 transition"
          style={{
            background: "rgba(15,23,42,.04)",
            border: "1px solid rgba(15,23,42,.07)",
          }}
          onFocus={(e) => {
            (e.currentTarget as HTMLElement).style.borderColor = TEAL
            ;(e.currentTarget as HTMLElement).style.boxShadow = `0 0 0 3px rgba(129,140,248,0.12)`
          }}
          onBlur={(e) => {
            (e.currentTarget as HTMLElement).style.borderColor = "rgba(15,23,42,.07)"
            ;(e.currentTarget as HTMLElement).style.boxShadow = "none"
          }}
        >
          <Search className="h-4 w-4 shrink-0 text-slate-400" />
          <input
            className="flex-1 bg-transparent text-sm text-slate-700 outline-none placeholder:text-slate-400"
            placeholder={tTopbar("search_placeholder")}
          />
        </div>

        {/* ── RIGHT : actions ────────────────────────────────────────────── */}
        <div className="flex items-center gap-2 shrink-0">
          <CountrySelector />

          <LocaleSwitcher />

          <ProfileDropdown accentColor={NAVY} secondaryColor={TEAL} />

          {/* Logout */}
          <button
            onClick={onLogout}
            className="inline-flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition hover:bg-red-50"
            style={{
              border: "1px solid rgba(15,23,42,.08)",
              color: "#64748b",
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLElement).style.borderColor = "rgba(239,68,68,0.25)"
              ;(e.currentTarget as HTMLElement).style.color = "#dc2626"
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLElement).style.borderColor = "rgba(15,23,42,.08)"
              ;(e.currentTarget as HTMLElement).style.color = "#64748b"
            }}
          >
            <LogOut className="h-4 w-4" />
            <span className="hidden sm:inline">{tCommon("logout")}</span>
          </button>
        </div>
      </div>

      {/* ── Accent bar ─────────────────────────────────────────────────── */}
      <div
        className="h-[2px] w-full"
        style={{
          background: `linear-gradient(90deg, ${NAVY} 0%, ${NAVY2} 40%, ${TEAL} 100%)`,
        }}
      />
    </header>
  );
}
