"use client"

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

import { cn } from "@/lib/utils"
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"

function titleFromPath(pathname: string) {
  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

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

  return (
    <header className="mb-6 flex items-center justify-between gap-2 rounded-3xl bg-white py-4 pr-4 pl-14 shadow-sm ring-1 ring-black/5 lg:gap-4 lg:p-4">
      <div className="flex items-center 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-slate-500 hover:bg-slate-50 hover:text-slate-700"
          >
            <ArrowLeft className="size-5" />
          </button>
        )}
        <h1 className="text-base font-bold tracking-tight text-slate-900 sm:text-xl">{title}</h1>
      </div>

      <div className="flex items-center gap-2 sm:gap-3">
        <Popover>
          <PopoverTrigger
            render={
              <button
                type="button"
                aria-label="Notifications"
                className="relative flex size-10 shrink-0 items-center justify-center rounded-full text-slate-500 hover:bg-slate-50 hover:text-slate-700"
              />
            }
          >
            <Bell className="size-5" />
            {unreadCount > 0 && (
              <Badge className="absolute top-1.5 right-1.5 size-2 rounded-full bg-indigo-600 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-black/5 px-4 py-3">
              <p className="text-sm font-semibold text-slate-900">Notifications</p>
              {unreadCount > 0 && (
                <button
                  type="button"
                  onClick={markAllAsRead}
                  className="text-xs font-medium text-indigo-600 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-black/5 px-4 py-3 last:border-0",
                      notification.unread && "bg-indigo-50/50"
                    )}
                  >
                    <span
                      className={cn(
                        "mt-1.5 size-2 shrink-0 rounded-full",
                        notification.unread ? "bg-indigo-600" : "bg-transparent"
                      )}
                    />
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium text-slate-900">{notification.title}</p>
                      <p className="truncate text-sm text-muted-foreground">
                        {notification.description}
                      </p>
                      <p className="mt-1 text-xs text-slate-400">{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-slate-50">
            <Avatar>
              <AvatarFallback className="bg-indigo-50 font-semibold text-indigo-600">
                JM
              </AvatarFallback>
            </Avatar>
            <span className="hidden text-sm font-semibold text-slate-700 sm:block">
              John Martinez
            </span>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-80 p-2">
            <div className="px-2 py-2.5">
              <p className="text-base font-semibold text-slate-900">John Martinez</p>
              <p className="text-sm font-normal text-muted-foreground">john52martinez@gmail.com</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"
              render={<Link href="/login" />}
              className="gap-3 px-3 py-2.5 text-base [&_svg:not([class*='size-'])]:size-5"
            >
              <LogOut />
              Log out
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  )
}
