"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { signOut } from "next-auth/react";
import { Logo } from "@/components/Logo";
import { SignOutButton } from "@/components/SignOutButton";
import { MobileMenuButton, MobileSidebar, dashboardSidebarLinkClass } from "@/components/MobileSidebar";

const NAV_LINKS = [
  { href: "/dashboard", label: "Create", match: (path: string) => path === "/dashboard" },
  {
    href: "/dashboard/history",
    label: "History",
    match: (path: string) => path.startsWith("/dashboard/history"),
  },
  {
    href: "/dashboard/settings",
    label: "Settings",
    match: (path: string) => path.startsWith("/dashboard/settings"),
  },
] as const;

type Props = {
  channelTitle?: string | null;
};

export function DashboardNav({ channelTitle }: Props) {
  const pathname = usePathname();
  const [menuOpen, setMenuOpen] = useState(false);

  return (
    <>
      <header className="border-b border-gray-800 bg-surface">
        <div className="mx-auto flex max-w-4xl items-center justify-between px-6 py-4">
          <div className="min-w-0">
            <Logo href="/dashboard" size="sm" />
            {channelTitle && (
              <p className="truncate text-xs text-gray-500">Channel: {channelTitle}</p>
            )}
          </div>

          <div className="hidden items-center gap-4 sm:flex">
            <nav className="flex items-center gap-4">
              {NAV_LINKS.map(({ href, label, match }) => {
                const active = match(pathname);
                return (
                  <Link
                    key={href}
                    href={href}
                    className={`text-sm font-medium transition-colors duration-200 ${
                      active ? "text-white" : "text-gray-400 hover:text-white"
                    }`}
                  >
                    {label}
                  </Link>
                );
              })}
            </nav>
            <SignOutButton />
          </div>

          <MobileMenuButton
            open={menuOpen}
            onClick={() => setMenuOpen((prev) => !prev)}
          />
        </div>
      </header>

      <MobileSidebar open={menuOpen} onClose={() => setMenuOpen(false)} title="Dashboard">
        {NAV_LINKS.map(({ href, label, match }) => (
          <Link
            key={href}
            href={href}
            onClick={() => setMenuOpen(false)}
            className={dashboardSidebarLinkClass(match(pathname))}
          >
            {label}
          </Link>
        ))}
        <button
          type="button"
          onClick={() => {
            setMenuOpen(false);
            signOut({ callbackUrl: "/" });
          }}
          className={`${dashboardSidebarLinkClass(false, true)} w-full text-left`}
        >
          Sign out
        </button>
      </MobileSidebar>
    </>
  );
}
