import React, { useState } from 'react'
import { Link, usePage } from '@inertiajs/react'
import NovaSelect from '../components/ui/NovaSelect'

const navItems = [
  { label: 'Profile',       href: '/dashboard/profile',   icon: 'fa-solid fa-user' },
  // Future: { label: 'Notifications', href: '/dashboard/notifications', icon: 'fa-solid fa-bell' },
  // Future: { label: 'Privacy',       href: '/dashboard/privacy',       icon: 'fa-solid fa-shield-halved' },
]

function NavLink({ item, active, onClick }) {
  return (
    <Link
      href={item.href}
      onClick={onClick}
      className={`flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${
        active
          ? 'bg-accent/20 text-accent shadow-sm shadow-accent/10'
          : 'text-slate-400 hover:text-white hover:bg-white/5'
      }`}
    >
      <i className={`${item.icon} w-5 text-center text-base`} />
      <span>{item.label}</span>
    </Link>
  )
}

function SidebarContent({ isActive, onNavigate }) {
  return (
    <>
      <div className="mb-6">
        <h2 className="text-xs font-semibold uppercase tracking-wider text-slate-500 px-4 mb-2">Settings</h2>
      </div>

      <nav className="space-y-1 flex-1">
        {navItems.map((item) => (
          <NavLink key={item.href} item={item} active={isActive(item.href)} onClick={onNavigate} />
        ))}
      </nav>

      <div className="mt-auto pt-6 space-y-2">
        <Link
          href="/studio"
          className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm text-slate-400 hover:text-white hover:bg-white/5 transition-colors"
          onClick={onNavigate}
        >
          <i className="fa-solid fa-palette w-5 text-center" />
          Creator Studio
        </Link>
      </div>
    </>
  )
}

function SectionSidebar({ sections = [], activeSection, onSectionChange, dirtyMap = {} }) {
  return (
    <>
      <div className="mb-6">
        <h2 className="text-xs font-semibold uppercase tracking-wider text-slate-500 px-4 mb-2">Settings</h2>
      </div>

      <nav className="space-y-1 flex-1">
        {sections.map((section) => {
          const active = section.key === activeSection
          const isDirty = !!dirtyMap[section.key]
          return (
            <button
              key={section.key}
              type="button"
              onClick={() => onSectionChange?.(section.key)}
              className={`group relative w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${
                active
                  ? 'bg-accent/20 text-accent shadow-sm shadow-accent/10'
                  : 'text-slate-400 hover:text-white hover:bg-white/5'
              }`}
            >
              {section.icon ? <i className={`${section.icon} w-5 text-center text-base`} /> : null}
              <span className="flex flex-col items-start gap-0.5">
                <span className="flex items-center gap-2">
                  {section.label}
                  {isDirty && (
                    <span className="inline-block h-1.5 w-1.5 rounded-full bg-amber-400 animate-pulse" title="Unsaved changes" />
                  )}
                </span>
                {section.description && !active ? (
                  <span className="text-[11px] font-normal text-slate-500 leading-tight">{section.description}</span>
                ) : null}
              </span>
            </button>
          )
        })}
      </nav>
    </>
  )
}

export default function SettingsLayout({ children, title, sections = null, activeSection = null, onSectionChange = null, dirtyMap = {} }) {
  const { url } = usePage()
  const [mobileOpen, setMobileOpen] = useState(false)
  const hasSectionMode = Array.isArray(sections) && sections.length > 0 && typeof onSectionChange === 'function'

  const isActive = (href) => url.startsWith(href)

  const currentSection = hasSectionMode
    ? sections.find((section) => section.key === activeSection)
    : null

  return (
    <div className="min-h-screen bg-nova-900">
      {/* Mobile top bar */}
      <div className="lg:hidden px-4 py-3 border-b border-white/10 bg-nova-900/80 backdrop-blur-xl sticky top-16 z-30">
        {hasSectionMode ? (
          <div className="flex items-center gap-2">
            <div className="block flex-1">
              <span className="sr-only">Settings section</span>
              <NovaSelect
                className="w-full"
                value={activeSection || ''}
                onChange={(value) => onSectionChange(value)}
                options={sections.map((section) => ({ value: section.key, label: `${section.label}${dirtyMap[section.key] ? ' •' : ''}` }))}
                searchable={false}
              />
            </div>
            {dirtyMap[activeSection] ? (
              <span className="inline-flex items-center rounded-full bg-amber-400/15 px-2 py-1 text-[10px] font-semibold text-amber-300 border border-amber-400/20">
                Unsaved
              </span>
            ) : null}
          </div>
        ) : (
          <div className="flex items-center justify-between">
            <h1 className="text-lg font-bold text-white">Settings</h1>
            <button
              onClick={() => setMobileOpen(!mobileOpen)}
              className="text-slate-400 hover:text-white p-2"
              aria-label="Toggle navigation"
            >
              <i className={`fa-solid ${mobileOpen ? 'fa-xmark' : 'fa-bars'} text-xl`} />
            </button>
          </div>
        )}
      </div>

      {/* Mobile nav overlay (legacy mode only) */}
      {!hasSectionMode && mobileOpen && (
        <div className="lg:hidden fixed inset-0 z-40 bg-black/60 backdrop-blur-sm" onClick={() => setMobileOpen(false)}>
          <nav
            className="absolute left-0 top-0 bottom-0 w-72 bg-nova-900 border-r border-white/10 p-4 pt-20 space-y-1"
            onClick={(e) => e.stopPropagation()}
          >
            <SidebarContent isActive={isActive} onNavigate={() => setMobileOpen(false)} />
          </nav>
        </div>
      )}

      <div className="flex">
        {/* Desktop sidebar */}
        <aside className="hidden lg:flex flex-col w-64 min-h-[calc(100vh-4rem)] border-r border-white/10 bg-nova-900/60 backdrop-blur-xl p-4 pt-6 sticky top-16 self-start">
          {hasSectionMode ? (
            <SectionSidebar sections={sections} activeSection={activeSection} onSectionChange={onSectionChange} dirtyMap={dirtyMap} />
          ) : (
            <SidebarContent isActive={isActive} />
          )}
        </aside>

        {/* Main content */}
        <main className="flex-1 min-w-0 px-4 lg:px-8 pt-4 pb-8 max-w-5xl">
          {title && (
            <div className="mb-6">
              <h1 className="text-2xl font-bold text-white">{title}</h1>
              {currentSection?.description ? (
                <p className="text-sm text-slate-400 mt-1">{currentSection.description}</p>
              ) : null}
            </div>
          )}
          {children}
        </main>
      </div>
    </div>
  )
}
