import { Outlet, useNavigate } from 'react-router-dom'
import { useState, useEffect, useRef, useCallback } from 'react'
import Sidebar from '../components/Sidebar'
import useAuthStore from '../store/authStore'
import client from '../api/client'

const SETTINGS_KEY = 'manager_lock_timeout'
const DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫']

// ─── Lock Screen overlay ───────────────────────────────────────────────────────

function LockScreen({ username, onUnlock }) {
  const [pin, setPin] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  function pressDigit(d) {
    if (d === '⌫') { setPin(p => p.slice(0, -1)); setError(''); return }
    if (d === '') return
    if (pin.length >= 6) return
    setPin(p => p + d)
  }

  async function handleSubmit() {
    if (pin.length < 4) return
    setError('')
    setLoading(true)
    try {
      const { data } = await client.post('/api/auth/login', { username, pin })
      const role = data.user.role
      if (role !== 'manager' && role !== 'sysadmin') {
        setError('Δεν έχεις δικαιώματα διαχειριστή.')
        setPin('')
        return
      }
      onUnlock(data.user, data.access_token)
    } catch {
      setError('Λανθασμένο PIN')
      setPin('')
    } finally {
      setLoading(false)
    }
  }

  // Auto-submit when 4 digits entered (most PINs are 4)
  useEffect(() => {
    if (pin.length === 4) handleSubmit()
  }, [pin])

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(17,19,21,0.92)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      backdropFilter: 'blur(6px)',
    }}>
      <div style={{
        background: 'white', borderRadius: 24,
        padding: '36px 32px', width: '100%', maxWidth: 340,
        boxShadow: '0 24px 64px rgba(0,0,0,0.4)',
        textAlign: 'center',
      }}>
        <div style={{ fontSize: 40, marginBottom: 12 }}>🔒</div>
        <div style={{ fontSize: 20, fontWeight: 700, color: '#111315', marginBottom: 4 }}>
          Κλειδωμένο
        </div>
        <div style={{ fontSize: 14, color: '#5a6169', marginBottom: 24 }}>
          {username}
        </div>

        {/* PIN dots */}
        <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginBottom: 24 }}>
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} style={{
              width: 14, height: 14, borderRadius: '50%', border: '2px solid',
              borderColor: i < pin.length ? '#3758c9' : '#d1d5db',
              background: i < pin.length ? '#3758c9' : 'transparent',
              transition: 'all 120ms',
            }} />
          ))}
        </div>

        {/* PIN pad */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 16 }}>
          {DIGITS.map((d, i) => (
            <button
              key={i}
              onClick={() => pressDigit(d)}
              disabled={d === '' || loading}
              style={{
                height: 56, borderRadius: 14, border: 'none', cursor: d === '' ? 'default' : 'pointer',
                fontSize: 20, fontWeight: 600,
                background: d === '' ? 'transparent' : d === '⌫' ? '#f3f4f6' : '#f3f4f6',
                color: d === '⌫' ? '#6b7280' : '#111315',
                visibility: d === '' ? 'hidden' : 'visible',
                transition: 'background 80ms',
              }}
              onMouseDown={e => { if (d !== '') e.currentTarget.style.background = '#e5e7eb' }}
              onMouseUp={e => { if (d !== '') e.currentTarget.style.background = '#f3f4f6' }}
              onMouseLeave={e => { if (d !== '') e.currentTarget.style.background = '#f3f4f6' }}
            >
              {d}
            </button>
          ))}
        </div>

        {error && (
          <p style={{ fontSize: 13, color: '#dc2626', marginBottom: 8 }}>{error}</p>
        )}
        {loading && (
          <p style={{ fontSize: 13, color: '#6b7280' }}>Επαλήθευση…</p>
        )}
      </div>
    </div>
  )
}

// ─── AppLayout ─────────────────────────────────────────────────────────────────

export default function AppLayout() {
  const { user, token, savedUsername, login, logout, lock, unlock, locked } = useAuthStore()
  const [clock, setClock] = useState(new Date())
  const navigate = useNavigate()
  const lastActivityRef = useRef(Date.now())
  const lockTimerRef = useRef(null)

  // ── Rehydrate user from token on mount ──────────────────────────────────────
  useEffect(() => {
    if (token && !user) {
      client.get('/auth/me').then(r => login(r.data, token)).catch(() => logout())
    }
  }, [token])

  // ── Clock ────────────────────────────────────────────────────────────────────
  useEffect(() => {
    const id = setInterval(() => setClock(new Date()), 1000)
    return () => clearInterval(id)
  }, [])

  // ── Auto-lock timer ──────────────────────────────────────────────────────────
  const getTimeoutMs = useCallback(() => {
    const raw = localStorage.getItem(SETTINGS_KEY)
    const mins = parseInt(raw, 10)
    if (!isNaN(mins) && mins > 0) return mins * 60 * 1000
    return null  // 0 or unset = disabled
  }, [])

  const resetActivityTimer = useCallback(() => {
    lastActivityRef.current = Date.now()
  }, [])

  useEffect(() => {
    if (!user || locked) return

    const EVENTS = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll', 'click']
    EVENTS.forEach(e => window.addEventListener(e, resetActivityTimer, { passive: true }))

    function checkIdle() {
      const timeoutMs = getTimeoutMs()
      if (!timeoutMs) return
      if (Date.now() - lastActivityRef.current >= timeoutMs) {
        lock()
      }
    }

    lockTimerRef.current = setInterval(checkIdle, 10_000)

    return () => {
      EVENTS.forEach(e => window.removeEventListener(e, resetActivityTimer))
      clearInterval(lockTimerRef.current)
    }
  }, [user, locked, getTimeoutMs, resetActivityTimer, lock])

  // ── Handlers ─────────────────────────────────────────────────────────────────
  function handleLogout() {
    logout()
    navigate('/login', { replace: true })
  }

  function handleUnlock(u, t) {
    unlock(u, t)
  }

  const timeStr = clock.toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
  const displayName = user?.username || savedUsername || ''

  return (
    <div className="flex h-screen overflow-hidden">
      {/* Lock overlay — rendered on top of everything */}
      {locked && displayName && (
        <LockScreen username={displayName} onUnlock={handleUnlock} />
      )}

      <Sidebar />
      <div className="flex flex-col flex-1 min-w-0">
        {/* Top bar */}
        <header className="flex items-center justify-between px-6 py-3 bg-white border-b border-gray-200 shrink-0">
          <span className="text-lg font-semibold text-gray-700 tabular-nums">{timeStr}</span>
          <div className="flex items-center gap-3">
            {/* Lock button */}
            <button
              onClick={lock}
              title="Κλείδωμα"
              style={{
                height: 30, width: 30, borderRadius: 8,
                border: '1px solid #dfe2e6', background: 'white',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 15, cursor: 'pointer', color: '#5a6169',
                transition: 'background 120ms, color 120ms',
              }}
              onMouseEnter={e => { e.currentTarget.style.background = '#f3f4f6'; e.currentTarget.style.color = '#374151' }}
              onMouseLeave={e => { e.currentTarget.style.background = 'white'; e.currentTarget.style.color = '#5a6169' }}
            >🔒</button>
            <span className="text-sm text-gray-500">{user?.username}</span>
            <button
              onClick={handleLogout}
              className="text-sm text-red-600 hover:text-red-800 font-medium transition-colors"
            >
              Αποσύνδεση
            </button>
          </div>
        </header>
        {/* Page content */}
        <main className="flex-1 overflow-y-auto p-6">
          <Outlet />
        </main>
      </div>
    </div>
  )
}
