import { useState } from 'react'
import { Outlet, NavLink } from 'react-router-dom'
import { useAuth } from '../core/auth/AuthContext'
import { apiClient } from '../core/api/api-client'
import HBLogo from './ui/HBLogo'

const NAV_ITEMS = [
  { to: '/dashboard', label: 'Dashboard' },
  { to: '/mitras', label: 'Mitra' },
  { to: '/sessions', label: 'Sesi' },
  { to: '/failed-pairings', label: 'Failed Pairings' },
  { to: '/users', label: 'Users' },
  { to: '/mitra-activity', label: 'Aktivitas Mitra' },
  { to: '/payment-catalog', label: 'Payment Catalog' },
  { to: '/settings', label: 'Settings' },
]

const PasswordChangeForm = ({ onDone }) => {
  const [current, setCurrent] = useState('')
  const [next, setNext] = useState('')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)

  const submit = async (e) => {
    e.preventDefault()
    setError('')
    setSaving(true)
    try {
      await apiClient.patch('/internal/control-center-users/me/password', {
        current_password: current,
        new_password: next,
      })
      setSuccess(true)
      setCurrent('')
      setNext('')
    } catch (err) {
      const code = err?.response?.data?.error?.code
      const msg = err?.response?.data?.error?.message
      if (code === 'INVALID_CREDENTIALS') setError('Password saat ini salah.')
      else if (code?.startsWith('PASSWORD_')) setError(msg || 'Password tidak memenuhi syarat.')
      else setError('Gagal mengubah password.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <form onSubmit={submit} className="hb-card" style={{ marginTop: 10, padding: 14 }}>
      <input
        type="password"
        placeholder="Password lama"
        value={current}
        onChange={(e) => setCurrent(e.target.value)}
        required
        style={{ marginBottom: 8 }}
      />
      <input
        type="password"
        placeholder="Password baru (min 8, huruf besar/kecil + angka)"
        value={next}
        onChange={(e) => setNext(e.target.value)}
        required
        minLength={8}
        style={{ marginBottom: 8 }}
      />
      {error && <p className="hb-error">{error}</p>}
      {success && <p className="hb-success">Password berhasil diubah.</p>}
      <div style={{ display: 'flex', gap: 8 }}>
        <button type="submit" disabled={saving} style={{ flex: 1 }}>
          {saving ? 'Menyimpan…' : 'Simpan'}
        </button>
        <button type="button" className="hb-btn-secondary" onClick={onDone}>
          Tutup
        </button>
      </div>
    </form>
  )
}

export default function Layout() {
  const { user, logout } = useAuth()
  const [showPwForm, setShowPwForm] = useState(false)

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: 'var(--hb-bg)' }}>
      <nav
        style={{
          width: 260,
          padding: '24px 20px',
          background: 'var(--hb-surface)',
          borderRight: '1px solid var(--hb-border)',
          display: 'flex',
          flexDirection: 'column',
          gap: 24,
          position: 'sticky',
          top: 0,
          height: '100vh',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <HBLogo size={44} />
          <div style={{ lineHeight: 1.15 }}>
            <div
              style={{
                fontFamily: 'var(--hb-font-display)',
                fontWeight: 700,
                fontSize: 17,
                color: 'var(--hb-ink)',
                letterSpacing: '-0.02em',
              }}
            >
              Halo Bestie
            </div>
            <div
              style={{
                fontSize: 11,
                fontWeight: 600,
                color: 'var(--hb-brand-dark)',
                textTransform: 'uppercase',
                letterSpacing: '0.08em',
              }}
            >
              Control Center
            </div>
          </div>
        </div>

        <ul
          style={{
            listStyle: 'none',
            padding: 0,
            margin: 0,
            display: 'flex',
            flexDirection: 'column',
            gap: 4,
            flex: 1,
          }}
        >
          {NAV_ITEMS.map((item) => (
            <li key={item.to}>
              <NavLink
                to={item.to}
                className={({ isActive }) => `hb-nav-link${isActive ? ' active' : ''}`}
              >
                {item.label}
              </NavLink>
            </li>
          ))}
        </ul>

        <div
          style={{
            paddingTop: 16,
            borderTop: '1px solid var(--hb-border)',
          }}
        >
          <p
            className="hb-soft"
            style={{
              fontSize: 12,
              margin: '0 0 10px',
              wordBreak: 'break-all',
            }}
          >
            {user?.email}
          </p>
          <div style={{ display: 'flex', gap: 8 }}>
            <button
              type="button"
              className="hb-btn-ghost"
              onClick={() => setShowPwForm((v) => !v)}
              style={{ flex: 1, minHeight: 36, fontSize: 13 }}
            >
              Ganti password
            </button>
            <button
              type="button"
              className="hb-btn-secondary"
              onClick={logout}
              style={{ minHeight: 36, fontSize: 13 }}
            >
              Logout
            </button>
          </div>
          {showPwForm && <PasswordChangeForm onDone={() => setShowPwForm(false)} />}
        </div>
      </nav>

      <main style={{ flex: 1, padding: '28px 32px', minWidth: 0 }}>
        <Outlet />
      </main>
    </div>
  )
}
