import { NavLink, useNavigate } from 'react-router-dom'
import {
  Banknote, ClipboardList, BarChart2, Wallet, Vault, FileText, Settings, LogOut,
} from 'lucide-react'
import { can, type User, type CashupCap } from '../types'

interface Props {
  user: User
  children: React.ReactNode
}

// `cap` gates the nav item's visibility; undefined = always shown (app access is enough).
const navItems: { to: string; label: string; icon: typeof Banknote; cap?: CashupCap }[] = [
  { to: '/daily',   label: 'Daily Cash Up',   icon: Banknote,      cap: 'count' },
  { to: '/history', label: 'History',          icon: ClipboardList },
  { to: '/report',  label: 'Weekly Report',    icon: BarChart2,     cap: 'reports' },
  { to: '/floats',  label: 'Float Management', icon: Wallet,        cap: 'floats' },
  { to: '/safe',    label: 'Safe Count',       icon: Vault,         cap: 'floats' },
  { to: '/summary', label: 'Cash Summary',     icon: FileText,      cap: 'reports' },
  { to: '/settings',label: 'Settings',         icon: Settings,      cap: 'settings' },
]

export function Layout({ user, children }: Props) {
  const navigate = useNavigate()

  async function logout() {
    await fetch('/cashup/api/auth/logout', { method: 'POST', credentials: 'include' })
    navigate('/login', { replace: true })
    window.location.reload()
  }

  return (
    <div style={{ display: 'flex', height: '100dvh', overflow: 'hidden' }}>
      {/* Sidebar */}
      <nav style={{
        width: '220px', flexShrink: 0, background: 'var(--navy)',
        display: 'flex', flexDirection: 'column', padding: '1rem 0',
        borderRight: '1px solid var(--surface-2)',
      }}>
        <div style={{ padding: '0 1rem 1rem', borderBottom: '1px solid var(--surface-2)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
            <Banknote size={20} strokeWidth={1.75} color="var(--gold)" />
            <span style={{ color: 'var(--gold)', fontWeight: 700, fontSize: '1rem' }}>Cash Up</span>
          </div>
          <p style={{ color: 'var(--text-muted)', fontSize: '0.75rem', marginTop: '0.25rem' }}>{user.name}</p>
        </div>

        <div style={{ flex: 1, padding: '0.5rem 0', overflowY: 'auto' }}>
          {navItems.filter(item => !item.cap || can(user, item.cap)).map(({ to, label, icon: Icon }) => (
            <NavLink key={to} to={to} style={({ isActive }) => ({
              display: 'flex', alignItems: 'center', gap: '0.625rem',
              padding: '0.625rem 1rem', textDecoration: 'none',
              color: isActive ? 'var(--gold)' : 'var(--text)',
              background: isActive ? 'var(--surface)' : 'transparent',
              borderLeft: isActive ? '2px solid var(--gold)' : '2px solid transparent',
              fontSize: '0.875rem', transition: 'background 0.15s',
            })}>
              <Icon size={15} strokeWidth={1.75} />
              {label}
            </NavLink>
          ))}
        </div>

        <div style={{ padding: '0.75rem 1rem', borderTop: '1px solid var(--surface-2)' }}>
          <button onClick={logout} style={{
            display: 'flex', alignItems: 'center', gap: '0.5rem',
            background: 'none', border: 'none', color: 'var(--text-muted)',
            fontSize: '0.875rem', padding: '0.375rem 0', width: '100%',
          }}>
            <LogOut size={14} strokeWidth={1.75} />
            Sign out
          </button>
        </div>
      </nav>

      {/* Content */}
      <main style={{ flex: 1, overflow: 'auto', background: 'var(--body-bg)' }}>
        {children}
      </main>
    </div>
  )
}

export function PageHeader({ title, subtitle }: { title: string; subtitle?: string }) {
  return (
    <div style={{ marginBottom: '1.5rem' }}>
      <h1 style={{ fontSize: '1.375rem', fontWeight: 700, color: 'var(--text-dark)' }}>{title}</h1>
      {subtitle && <p style={{ color: 'var(--text-mid)', fontSize: '0.875rem', marginTop: '0.25rem' }}>{subtitle}</p>}
    </div>
  )
}

export function Card({ children, style }: { children: React.ReactNode; style?: React.CSSProperties }) {
  return (
    <div style={{
      background: 'var(--card-bg)', border: '1px solid var(--card-border)',
      borderRadius: 'var(--radius)', padding: '1.25rem',
      boxShadow: 'var(--shadow-sm)', ...style,
    }}>
      {children}
    </div>
  )
}

export function Btn({
  children, onClick, variant = 'primary', disabled, small, type = 'button', style,
}: {
  children: React.ReactNode
  onClick?: () => void
  variant?: 'primary' | 'secondary' | 'danger' | 'ghost'
  disabled?: boolean
  small?: boolean
  type?: 'button' | 'submit'
  style?: React.CSSProperties
}) {
  const styles: Record<string, React.CSSProperties> = {
    primary:   { background: 'var(--gold)',     color: 'var(--navy-dark)', border: 'none' },
    secondary: { background: 'var(--card-bg)',  color: 'var(--text-dark)', border: '1px solid var(--card-border)' },
    danger:    { background: 'var(--danger)',   color: '#fff',             border: 'none' },
    ghost:     { background: 'transparent',    color: 'var(--text-mid)',   border: '1px solid var(--card-border)' },
  }
  return (
    <button
      type={type}
      onClick={onClick}
      disabled={disabled}
      style={{
        ...styles[variant],
        borderRadius: '6px',
        padding: small ? '0.35rem 0.75rem' : '0.55rem 1rem',
        fontSize: small ? '0.8rem' : '0.875rem',
        fontWeight: 600,
        opacity: disabled ? 0.5 : 1,
        cursor: disabled ? 'not-allowed' : 'pointer',
        ...style,
      }}
    >
      {children}
    </button>
  )
}

export function StatusBadge({ status }: { status: 'draft' | 'final' }) {
  const styles = {
    draft: { background: '#fef9c3', color: '#ca8a04' },
    final: { background: '#dcfce7', color: '#16a34a' },
  }
  return (
    <span style={{
      ...styles[status], fontSize: '0.75rem', fontWeight: 600,
      padding: '0.2rem 0.5rem', borderRadius: '4px', textTransform: 'uppercase',
    }}>
      {status}
    </span>
  )
}
