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

const API_URL = import.meta.env.VITE_API_URL || ''

// ─── Waiter card ──────────────────────────────────────────────────────────────

function WaiterCard({ waiter, onClick }) {
  const initials = (waiter.full_name || waiter.nickname || '?')
    .split(' ')
    .map(w => w[0])
    .join('')
    .slice(0, 2)
    .toUpperCase()

  return (
    <button
      onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '14px 16px',
        background: 'var(--bg2)',
        border: '1px solid var(--border)',
        borderRadius: 14,
        cursor: 'pointer',
        width: '100%',
        textAlign: 'left',
        position: 'relative',
        transition: 'border-color 0.15s',
        boxSizing: 'border-box',
      }}
    >
      {/* Avatar */}
      <div style={{
        width: 48, height: 48, borderRadius: '50%', flexShrink: 0,
        background: waiter.avatar_url ? 'transparent' : 'var(--bg3)',
        border: `2px solid ${waiter.on_shift ? '#22c55e' : 'var(--border)'}`,
        overflow: 'hidden',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 18, fontWeight: 700, color: 'var(--text)',
      }}>
        {waiter.avatar_url
          ? <img src={`${API_URL}${waiter.avatar_url}`} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : initials
        }
      </div>

      {/* Name block */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', wordBreak: 'break-word', whiteSpace: 'normal', lineHeight: 1.3 }}>
          {waiter.full_name || waiter.nickname || '—'}
        </div>
        {waiter.nickname && waiter.full_name && (
          <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{waiter.nickname}</div>
        )}
      </div>

      {/* On-shift dot */}
      {waiter.on_shift && (
        <span style={{
          width: 10, height: 10, borderRadius: '50%',
          background: '#22c55e',
          flexShrink: 0,
          boxShadow: '0 0 6px #22c55e88',
        }} title="Σε βάρδια" />
      )}

      <span style={{ color: 'var(--muted)', fontSize: 18, flexShrink: 0 }}>›</span>
    </button>
  )
}

// ─── Main page ────────────────────────────────────────────────────────────────

export default function LoginPage() {
  const { login } = useAuthStore()
  const navigate = useNavigate()

  const [waiters, setWaiters] = useState([])
  const [loadingWaiters, setLoadingWaiters] = useState(true)
  const [serverUnreachable, setServerUnreachable] = useState(false)
  const [selectedWaiter, setSelectedWaiter] = useState(null)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    client.get('/api/auth/waiters')
      .then(r => { setWaiters(r.data); setServerUnreachable(false) })
      .catch(err => {
        // No response = network error = server unreachable
        if (!err.response) setServerUnreachable(true)
        setWaiters([])
      })
      .finally(() => setLoadingWaiters(false))
  }, [])

  async function handlePin(pin) {
    if (!selectedWaiter) return
    setError('')
    setLoading(true)
    try {
      // We send waiter id as identifier; backend matches by id+pin
      const { data } = await client.post('/api/auth/login-by-id', { waiter_id: selectedWaiter.id, pin })
      login({ id: data.user.id, username: data.user.username, role: data.user.role }, data.access_token)
      navigate('/tables')
    } catch (err) {
      setError(err.response?.data?.detail || 'Λανθασμένο PIN')
    } finally {
      setLoading(false)
    }
  }

  // ── Waiter picker screen ───────────────────────────────────────────────────

  if (!selectedWaiter) {
    // Sort: on-shift first, then alphabetical
    const sorted = [...waiters].sort((a, b) => {
      if (a.on_shift !== b.on_shift) return a.on_shift ? -1 : 1
      return (a.full_name || a.nickname || '').localeCompare(b.full_name || b.nickname || '')
    })

    return (
      <div className="page">
        {/* Static header — never scrolls */}
        <div style={{ flexShrink: 0, padding: '40px 16px 20px', textAlign: 'center' }}>
          <h1 className="app-title" style={{ marginBottom: 10 }}>TableServe</h1>
          <p className="app-subtitle">Ποιος είσαι;</p>
        </div>

        {/* Scrollable card list */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '4px 16px 40px' }}>
          <div style={{ maxWidth: 480, margin: '0 auto' }}>
            {loadingWaiters ? (
              <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 32 }}>Φόρτωση…</p>
            ) : serverUnreachable ? (
              <div style={{ textAlign: 'center', padding: 32 }}>
                <div style={{ fontSize: 48, marginBottom: 16 }}>🔌</div>
                <p style={{ fontSize: 17, fontWeight: 700, color: '#ef4444', marginBottom: 8 }}>
                  Δεν βρέθηκε ο Server
                </p>
                <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.6, marginBottom: 24 }}>
                  Δεν είναι δυνατή η σύνδεση με τον Manager.<br />
                  Δεν μπορεί να ξεκινήσει βάρδια χωρίς σύνδεση.
                </p>
                <button
                  className="btn btn--secondary"
                  onClick={() => {
                    setLoadingWaiters(true)
                    setServerUnreachable(false)
                    client.get('/api/auth/waiters')
                      .then(r => { setWaiters(r.data); setServerUnreachable(false) })
                      .catch(err => { if (!err.response) setServerUnreachable(true) })
                      .finally(() => setLoadingWaiters(false))
                  }}
                >
                  ⟳ Επανάληψη
                </button>
              </div>
            ) : waiters.length === 0 ? (
              <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 32 }}>Δεν βρέθηκαν σερβιτόροι</p>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'stretch' }}>
                {sorted.map(w => (
                  <WaiterCard key={w.id} waiter={w} onClick={() => { setError(''); setSelectedWaiter(w) }} />
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    )
  }

  // ── PIN screen ─────────────────────────────────────────────────────────────

  const initials = (selectedWaiter.full_name || selectedWaiter.nickname || '?')
    .split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()

  return (
    <div className="page page--centered">
      <div className="login-box">
        <h1 className="app-title">TableServe</h1>

        {/* Selected waiter mini-card */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          background: 'var(--bg2)', border: '1px solid var(--border)',
          borderRadius: 12, padding: '10px 14px', marginBottom: 4,
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
            background: selectedWaiter.avatar_url ? 'transparent' : 'var(--bg3)',
            border: `2px solid ${selectedWaiter.on_shift ? '#22c55e' : 'var(--border)'}`,
            overflow: 'hidden',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 15, fontWeight: 700, color: 'var(--text)',
          }}>
            {selectedWaiter.avatar_url
              ? <img src={`${API_URL}${selectedWaiter.avatar_url}`} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              : initials
            }
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>
              {selectedWaiter.full_name || selectedWaiter.nickname}
            </div>
            {selectedWaiter.nickname && selectedWaiter.full_name && (
              <div style={{ fontSize: 12, color: 'var(--muted)' }}>{selectedWaiter.nickname}</div>
            )}
          </div>
          <button
            onClick={() => { setSelectedWaiter(null); setError('') }}
            style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 13, padding: '4px 8px' }}
          >
            Αλλαγή
          </button>
        </div>

        <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, marginBottom: 12 }}>Εισάγετε PIN</p>

        <PinPad onSubmit={handlePin} loading={loading} />

        {error && <p className="error-msg">{error}</p>}
      </div>
    </div>
  )
}
