'use client'

import { useState } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { ViewAsSwitcher } from './view-as-switcher'
import { CommentsBell, type CommentItem } from './comments-bell'
import { exitViewAs } from '@/app/actions/view-as'

type NavLink = {
  href: string
  label: string
  ownerOnly?: boolean
  /** Optional submenu items. When present, the top-level link shows a
   * hover-dropdown listing them. The top-level href is still clickable
   * (jumps to a landing page). */
  submenu?: { href: string; label: string }[]
}

const LINKS: NavLink[] = [
  { href: '/', label: 'Summary' },
  { href: '/entries', label: 'Entries' },
  {
    href: '/projects',
    label: 'Projects',
    submenu: [{ href: '/projects/manage', label: 'Manage' }],
  },
  { href: '/invoices', label: 'Invoices', ownerOnly: true },
  { href: '/import', label: 'Import' },
  { href: '/team', label: 'Team' },
  {
    href: '/tools',
    label: 'Tools',
    ownerOnly: true,
    submenu: [
      {
        href: '/tools/cc-expenses',
        label: 'Bill Through Credit Card Expenses',
      },
    ],
  },
]

type Candidate = {
  id: string
  email: string
  full_name: string | null
}

type Props = {
  effective: {
    full_name: string | null
    email: string
    is_super_admin: boolean
    org_role: string | null
    is_viewing_as: boolean
    view_as_label: string | null
  }
  orgName: string | null
  switcherCandidates: Candidate[]
  canTransfer: boolean
  commentItems: CommentItem[]
  unresolvedCommentCount: number
  currentUserId: string | null
}

export function Nav({
  effective,
  orgName,
  switcherCandidates,
  canTransfer,
  commentItems,
  unresolvedCommentCount,
  currentUserId,
}: Props) {
  const path = usePathname()
  const showSwitcher =
    effective.is_super_admin && !effective.is_viewing_as && switcherCandidates.length > 0

  const visibleLinks = LINKS.filter((l) => !l.ownerOnly || canTransfer)
  const [openDropdown, setOpenDropdown] = useState<string | null>(null)

  return (
    <>
      <header className="nav">
        <div className="nav-inner">
          <div className="nav-brand">{orgName ?? 'Work'}</div>
          <nav className="nav-links">
            {visibleLinks.map((l) => {
              const active =
                l.href === '/' ? path === '/' : path.startsWith(l.href)
              if (!l.submenu) {
                return (
                  <Link
                    key={l.href}
                    href={l.href}
                    className={active ? 'nav-link nav-link-active' : 'nav-link'}
                  >
                    {l.label}
                  </Link>
                )
              }
              const isOpen = openDropdown === l.href
              return (
                <div
                  key={l.href}
                  style={{ position: 'relative' }}
                  onMouseEnter={() => setOpenDropdown(l.href)}
                  onMouseLeave={() => setOpenDropdown(null)}
                >
                  <Link
                    href={l.href}
                    className={active ? 'nav-link nav-link-active' : 'nav-link'}
                  >
                    {l.label} <span style={{ fontSize: '0.7em' }}>▾</span>
                  </Link>
                  {isOpen && (
                    <div
                      style={{
                        position: 'absolute',
                        top: '100%',
                        left: 0,
                        minWidth: '16rem',
                        background: '#fff',
                        border: '1px solid #ccc',
                        borderRadius: 4,
                        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                        padding: '0.3rem 0',
                        zIndex: 50,
                      }}
                    >
                      {l.submenu.map((s) => (
                        <Link
                          key={s.href}
                          href={s.href}
                          className="nav-link"
                          style={{
                            display: 'block',
                            padding: '0.4rem 0.8rem',
                            fontSize: '0.9em',
                            color: '#222',
                          }}
                        >
                          {s.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              )
            })}
          </nav>
          <div className="nav-user">
            <span className="nav-user-name">
              {effective.full_name || effective.email}
              <span
                className="muted"
                style={{ marginLeft: '0.4rem', fontSize: '0.78em' }}
              >
                (
                {effective.is_super_admin
                  ? 'super admin'
                  : (effective.org_role ?? 'no role')}
                )
              </span>
            </span>
            <CommentsBell
              unresolvedCount={unresolvedCommentCount}
              comments={commentItems}
              currentUserId={currentUserId}
            />
            {showSwitcher && <ViewAsSwitcher candidates={switcherCandidates} />}
            <form action="/auth/signout" method="post">
              <button type="submit" className="nav-signout">
                Sign out
              </button>
            </form>
          </div>
        </div>
      </header>
      {effective.is_viewing_as && (
        <div
          style={{
            background: '#fde68a',
            color: '#78350f',
            padding: '0.4rem 1rem',
            textAlign: 'center',
            fontSize: '0.85rem',
          }}
        >
          Viewing as <strong>{effective.view_as_label}</strong>. Some actions
          are restricted to match their role.{' '}
          <form action={exitViewAs} style={{ display: 'inline' }}>
            <button
              type="submit"
              style={{
                background: 'transparent',
                border: 'none',
                color: '#78350f',
                textDecoration: 'underline',
                padding: 0,
                cursor: 'pointer',
                font: 'inherit',
              }}
            >
              Exit view
            </button>
          </form>
        </div>
      )}
    </>
  )
}
