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

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

export default function LoginPage() {
  const [username, setUsername] = useState('')
  const [pin, setPin] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  const { login } = useAuthStore()
  const navigate = useNavigate()

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

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

  return (
    <div className="min-h-screen bg-gray-100 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-lg p-8 w-full max-w-sm">
        <h1 className="text-2xl font-bold text-primary-800 text-center mb-1">POS Manager</h1>
        <p className="text-center text-gray-500 text-sm mb-6">Πίνακας Διαχείρισης</p>

        <form onSubmit={handleSubmit} className="space-y-4">
          <input
            className="w-full border border-gray-300 rounded-xl px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-primary-600"
            placeholder="Όνομα χρήστη"
            value={username}
            onChange={e => setUsername(e.target.value)}
            autoComplete="off"
            autoFocus
          />

          {/* PIN display */}
          <div className="flex justify-center gap-3 py-2">
            {Array.from({ length: 4 }).map((_, i) => (
              <div
                key={i}
                className={`w-4 h-4 rounded-full border-2 transition-colors ${
                  i < pin.length ? 'bg-primary-700 border-primary-700' : 'border-gray-300'
                }`}
              />
            ))}
          </div>

          {/* PIN pad */}
          <div className="grid grid-cols-3 gap-3">
            {DIGITS.map((d, i) => (
              <button
                key={i}
                type={d === '' ? 'button' : 'button'}
                onClick={() => pressDigit(d)}
                disabled={d === ''}
                className={`h-14 rounded-xl text-xl font-semibold transition-colors ${
                  d === ''
                    ? 'invisible'
                    : d === '⌫'
                    ? 'bg-gray-100 hover:bg-gray-200 text-gray-600'
                    : 'bg-gray-100 hover:bg-primary-100 active:bg-primary-200 text-gray-800'
                }`}
              >
                {d}
              </button>
            ))}
          </div>

          {error && <p className="text-center text-red-600 text-sm">{error}</p>}

          <button
            type="submit"
            disabled={loading || !username.trim() || pin.length < 4}
            className="w-full bg-primary-700 hover:bg-primary-800 disabled:opacity-40 text-white font-semibold py-3 rounded-xl transition-colors"
          >
            {loading ? 'Σύνδεση…' : 'Σύνδεση'}
          </button>
        </form>
      </div>
    </div>
  )
}
