'use client'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { useState } from 'react'
import { Button } from '@/components/ui/button'

const NAV = [
  { href: '/dashboard', label: 'Quick Deploy' },
  { href: '/dashboard/sandboxes', label: 'Sandboxes' },
  { href: '/dashboard/templates', label: 'Templates' },
  { href: '/dashboard/environments', label: 'Environments' },
  { href: '/dashboard/history', label: 'History' },
]

export function DashboardNav() {
  const pathname = usePathname()
  const router = useRouter()
  const [busy, setBusy] = useState(false)

  async function logout() {
    setBusy(true)
    try {
      const base = (process.env.NEXT_PUBLIC_BASE_PATH ?? '').replace(/\/$/, '')
      await fetch(`${base}/api/logout`, { method: 'POST', credentials: 'include' })
    } finally {
      router.push('/')
    }
  }

  return (
    <header className="border-b">
      <div className="container flex h-14 items-center justify-between gap-6">
        <div className="flex items-center gap-6">
          <Link href="/dashboard" className="font-semibold tracking-tight">SDP</Link>
          <nav className="flex gap-1 text-sm">
            {NAV.map((n) => {
              const active = n.href === '/dashboard'
                ? pathname === '/dashboard'
                : pathname?.startsWith(n.href)
              return (
                <Link
                  key={n.href}
                  href={n.href}
                  className={
                    'rounded-md px-3 py-1.5 transition-colors ' +
                    (active
                      ? 'bg-zinc-900 text-zinc-50'
                      : 'text-zinc-700 hover:bg-zinc-100')
                  }
                >
                  {n.label}
                </Link>
              )
            })}
          </nav>
        </div>
        <Button variant="outline" size="sm" onClick={logout} disabled={busy}>
          {busy ? 'Logging out…' : 'Logout'}
        </Button>
      </div>
    </header>
  )
}
