"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { ArrowLeft, Bell, LogOut, Settings, User } from "lucide-react"

import { authApi } from "@/lib/api/auth"
import { clearStoredUser, displayName, getStoredUser } from "@/lib/auth-session"
import { AuthUser } from "@/types/auth"
import { cn } from "@/lib/utils"
import { ThemeToggle } from "@/components/theme-toggle"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"

/** Avatar initials from a display name: "ERP Admin" -> "EA", "erpadmin" -> "ER". */
function initials(name: string): string {
  const parts = name.trim().split(/\s+/).filter(Boolean)
  if (parts.length === 0) return "?"
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase()
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
}

const PROCUREMENT_TITLES: Record<string, string> = {
  "/dashboard/procurement": "Procurement",
  "/dashboard/procurement/requisitions": "Requisitions",
  "/dashboard/procurement/requisitions/new": "New Requisition",
  "/dashboard/procurement/rfqs": "RFQs",
  "/dashboard/procurement/rfqs/new": "New RFQ",
  "/dashboard/procurement/purchase-orders": "Purchase Orders",
  "/dashboard/procurement/purchase-orders/new": "New Purchase Order",
  "/dashboard/procurement/purchase-returns": "Purchase Returns",
  "/dashboard/procurement/purchase-returns/new": "New Purchase Return",
}

const LEDGER_TITLES: Record<string, string> = {
  "/dashboard/ledgers": "Ledgers",
  "/dashboard/ledgers/trial-balance": "Trial Balance",
  "/dashboard/ledgers/balance-sheet": "Balance Sheet",
  "/dashboard/ledgers/general-ledger": "General Ledger",
  "/dashboard/ledgers/profit-and-loss": "Profit & Loss",
  "/dashboard/ledgers/cash-flow": "Cash Flow",
  "/dashboard/ledgers/budget-vs-actual": "Budget vs Actual",
  "/dashboard/ledgers/tax-report": "Tax Report",
}

const ACCOUNTS_TITLES: Record<string, string> = {
  "/dashboard/accounts": "Accounts",
  "/dashboard/accounts/bank-accounts": "Cash / Bank Accounts",
  "/dashboard/accounts/bank-accounts/new": "New Bank Account",
  "/dashboard/accounts/cheque-books": "Cheque Books",
  "/dashboard/accounts/cheque-books/new": "New Cheque Book",
  "/dashboard/accounts/received-cheques": "Received Cheques",
  "/dashboard/accounts/received-cheques/new": "New Received Cheque",
}

const STOCK_TITLES: Record<string, string> = {
  "/dashboard/stock": "Stock Management",
  "/dashboard/stock/enquiry": "Stock Enquiry",
  "/dashboard/stock/ledger": "Stock Ledger",
  "/dashboard/stock/valuation": "Valuation",
  "/dashboard/stock/transfers": "Stock Transfers",
  "/dashboard/stock/transfers/new": "New Transfer",
  "/dashboard/stock/adjustments": "Stock Adjustments",
  "/dashboard/stock/adjustments/new": "New Adjustment",
  "/dashboard/stock/counts": "Stock Counts",
  "/dashboard/stock/counts/new": "New Count",
  "/dashboard/stock/reorder-alerts": "Reorder Alerts",
  "/dashboard/stock/wastage": "Wastage",
  "/dashboard/stock/wastage/new": "Record Wastage",
}

function titleFromPath(pathname: string) {
  if (pathname === "/dashboard/receiving/grn") return "Goods Receipt Notes"
  if (pathname === "/dashboard/receiving/grn/new") return "Create Goods Receipt Note"
  if (/^\/dashboard\/receiving\/grn\/[^/]+$/.test(pathname)) return "Goods Receipt Note"

  if (LEDGER_TITLES[pathname]) return LEDGER_TITLES[pathname]

  if (ACCOUNTS_TITLES[pathname]) return ACCOUNTS_TITLES[pathname]
  if (/^\/dashboard\/accounts\/cheque-books\/[^/]+$/.test(pathname)) return "Cheque Book"

  if (STOCK_TITLES[pathname]) return STOCK_TITLES[pathname]
  if (/^\/dashboard\/stock\/transfers\/[^/]+$/.test(pathname)) return "Stock Transfer"
  if (/^\/dashboard\/stock\/counts\/[^/]+$/.test(pathname)) return "Stock Count"

  if (PROCUREMENT_TITLES[pathname]) return PROCUREMENT_TITLES[pathname]
  if (/^\/dashboard\/procurement\/requisitions\/[^/]+$/.test(pathname)) return "Requisition"
  if (/^\/dashboard\/procurement\/rfqs\/[^/]+$/.test(pathname)) return "RFQ"
  if (/^\/dashboard\/procurement\/purchase-orders\/[^/]+$/.test(pathname)) return "Purchase Order"

  if (pathname === "/dashboard/warehouse") return "Warehouses"
  if (/^\/dashboard\/warehouse\/[^/]+$/.test(pathname)) return "Warehouse"

  if (pathname === "/dashboard/vendors") return "Vendors"
  if (/^\/dashboard\/vendors\/[^/]+$/.test(pathname)) return "View Vendor"

  if (pathname === "/dashboard/products") return "Items"
  if (pathname === "/dashboard/products/new") return "New Item"
  if (pathname === "/dashboard/products/uoms") return "Units of Measure"
  if (pathname === "/dashboard/products/categories") return "Categories"
  if (pathname.startsWith("/dashboard/products/categories/")) return "Subcategories"
  if (pathname === "/dashboard/products/brands") return "Brands"
  if (pathname === "/dashboard/products/item-types") return "Item Types"
  if (pathname === "/dashboard/products/settings") return "Product Configuration"
  if (pathname === "/dashboard/settings/company-profile") return "Company Profile"
  if (/^\/dashboard\/products\/[^/]+$/.test(pathname)) return "Item"

  const segment = pathname.split("/").filter(Boolean).pop() ?? "dashboard"
  return segment.charAt(0).toUpperCase() + segment.slice(1)
}

interface Notification {
  id: string
  title: string
  description: string
  time: string
  unread: boolean
}

const initialNotifications: Notification[] = [
  {
    id: "1",
    title: "New order received",
    description: "Order #3210 placed by John Martinez",
    time: "2m ago",
    unread: true,
  },
  {
    id: "2",
    title: "Low stock alert",
    description: "SKU-2291 has dropped below its reorder threshold",
    time: "1h ago",
    unread: true,
  },
  {
    id: "3",
    title: "Payment failed",
    description: "Order #3207 payment was declined",
    time: "3h ago",
    unread: false,
  },
  {
    id: "4",
    title: "New customer",
    description: "Grace Kim just created an account",
    time: "1d ago",
    unread: false,
  },
]

export function Header() {
  const pathname = usePathname() || "/"
  const router = useRouter()
  const title = titleFromPath(pathname)
  const showBackButton = pathname !== "/dashboard"
  const [notifications, setNotifications] = useState(initialNotifications)
  const unreadCount = notifications.filter((n) => n.unread).length

  // Read after mount so the first client render matches the server render.
  const [user, setUser] = useState<AuthUser | null>(null)

  useEffect(() => {
    setUser(getStoredUser())
  }, [])

  const markAllAsRead = () =>
    setNotifications((prev) => prev.map((n) => ({ ...n, unread: false })))

  async function handleLogout() {
    try {
      // Always call it, even without a userId: AuthHex returns none on login, so the
      // server resolves the user from the session token. Skipping the call would leave
      // the erp_at cookie alive and the "logout" would be cosmetic.
      await authApi.logout(user?.userId ?? null)
    } catch {
      // A failed logout must not strand the user in the app: the cookie may already be
      // gone or upstream may be down. Clear locally and leave either way — worst case the
      // server-side session lapses on its own.
    } finally {
      clearStoredUser()
      router.push("/login")
      router.refresh()
    }
  }

  return (
    <header className="mx-3 mt-3 mb-3 flex items-center justify-between gap-2 rounded-3xl bg-card py-4 pr-3 pl-12 shadow-sm ring-1 ring-foreground/10 sm:mx-6 sm:pr-4 sm:pl-14 lg:mx-8 lg:mt-4 lg:mb-4 lg:gap-4 lg:p-4">
      <div className="flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
        {showBackButton && (
          <button
            type="button"
            onClick={() => router.back()}
            aria-label="Go back"
            className="flex size-9 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
          >
            <ArrowLeft className="size-5" />
          </button>
        )}
        <h1 className="min-w-0 truncate text-base font-bold tracking-tight text-foreground sm:text-xl">{title}</h1>
      </div>

      <div className="flex shrink-0 items-center gap-1.5 sm:gap-3">
        <ThemeToggle />

        <Popover>
          <PopoverTrigger
            render={
              <button
                type="button"
                aria-label="Notifications"
                className="relative flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
              />
            }
          >
            <Bell className="size-5" />
            {unreadCount > 0 && (
              <Badge className="absolute top-1.5 right-1.5 size-2 rounded-full bg-primary p-0" />
            )}
          </PopoverTrigger>
          <PopoverContent
            align="end"
            className="w-[calc(100vw-2rem)] max-w-sm sm:w-96"
          >
            <div className="flex items-center justify-between border-b border-foreground/10 px-4 py-3">
              <p className="text-sm font-semibold text-foreground">Notifications</p>
              {unreadCount > 0 && (
                <button
                  type="button"
                  onClick={markAllAsRead}
                  className="text-xs font-medium text-primary hover:underline"
                >
                  Mark all as read
                </button>
              )}
            </div>

            <div className="max-h-80 overflow-y-auto">
              {notifications.length === 0 ? (
                <p className="p-6 text-center text-sm text-muted-foreground">
                  You&apos;re all caught up.
                </p>
              ) : (
                notifications.map((notification) => (
                  <div
                    key={notification.id}
                    className={cn(
                      "flex gap-3 border-b border-foreground/10 px-4 py-3 last:border-0",
                      notification.unread && "bg-primary/10"
                    )}
                  >
                    <span
                      className={cn(
                        "mt-1.5 size-2 shrink-0 rounded-full",
                        notification.unread ? "bg-primary" : "bg-transparent"
                      )}
                    />
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium text-foreground">{notification.title}</p>
                      <p className="truncate text-sm text-muted-foreground">
                        {notification.description}
                      </p>
                      <p className="mt-1 text-xs text-muted-foreground">{notification.time}</p>
                    </div>
                  </div>
                ))
              )}
            </div>
          </PopoverContent>
        </Popover>

        <DropdownMenu>
          <DropdownMenuTrigger className="flex items-center gap-2 rounded-full py-1 pr-2 pl-1 outline-none hover:bg-muted">
            <Avatar>
              <AvatarFallback className="bg-primary/10 font-semibold text-primary">
                {user ? initials(displayName(user)) : "?"}
              </AvatarFallback>
            </Avatar>
            <span className="hidden text-sm font-semibold text-foreground sm:block">
              {user ? displayName(user) : "Signed in"}
            </span>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-80 p-2">
            <div className="px-2 py-2.5">
              <p className="text-base font-semibold text-foreground">
                {user ? displayName(user) : "Signed in"}
              </p>
              {user?.email && <p className="text-sm font-normal text-muted-foreground">{user.email}</p>}
            </div>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              render={<Link href="/dashboard/profile" />}
              className="gap-3 px-3 py-2.5 text-base [&_svg:not([class*='size-'])]:size-5"
            >
              <User />
              Profile
            </DropdownMenuItem>
            <DropdownMenuItem
              render={<Link href="/dashboard/settings" />}
              className="gap-3 px-3 py-2.5 text-base [&_svg:not([class*='size-'])]:size-5"
            >
              <Settings />
              Settings
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              variant="destructive"
              onClick={handleLogout}
              className="gap-3 px-3 py-2.5 text-base [&_svg:not([class*='size-'])]:size-5"
            >
              <LogOut />
              Log out
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  )
}
