import { useState, useEffect, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { User, Lock, KeyRound } from 'lucide-react'
import useAuthStore from '../store/authStore'
import client from '../api/client'
import Button from '../ui/Button'
import { LabelledInput } from '../ui/Input'

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

function PinDots({ length, filled }) {
  return (
    <div className="flex justify-center gap-3 py-2">
      {Array.from({ length }).map((_, i) => (
        <div key={i} className={`w-3.5 h-3.5 rounded-full border-2 transition-colors ${
          i < filled ? 'bg-sky-500 border-sky-500' : 'border-slate-300'
        }`} />
      ))}
    </div>
  )
}

function PinPad({ pin, onChange, disabled }) {
  function press(d) {
    if (disabled) return
    if (d === '⌫') { onChange(p => p.slice(0, -1)); return }
    if (d === '') return
    if (pin.length >= 6) return
    onChange(p => p + d)
  }
  return (
    <div className="grid grid-cols-3 gap-3">
      {DIGITS.map((d, i) => (
        <button
          key={i}
          type="button"
          onClick={() => press(d)}
          disabled={d === '' || disabled}
          className={`h-14 rounded-xl text-xl font-semibold transition-colors ${
            d === ''
              ? 'invisible'
              : d === '⌫'
              ? 'bg-slate-100 hover:bg-slate-200 text-slate-600'
              : 'bg-slate-100 hover:bg-sky-100 active:bg-sky-200 text-slate-800'
          } disabled:opacity-50`}
        >
          {d}
        </button>
      ))}
    </div>
  )
}

// ─── Manager picker (multi-manager + login=none) ──────────────────────────────

function ManagerPicker({ managers, onSelect }) {
  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <h1 className="text-xl font-bold text-slate-900">Select account</h1>
        <p className="text-[13px] text-slate-500">Choose your manager account to continue.</p>
      </div>
      <div className="space-y-2">
        {managers.map(m => (
          <button
            key={m.id}
            onClick={() => onSelect(m)}
            className="w-full flex items-center gap-3 rounded-xl border border-slate-200 bg-white p-4 text-left transition hover:border-sky-300 hover:bg-sky-50 active:bg-sky-100"
          >
            <div className="flex h-9 w-9 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[13px] flex-shrink-0">
              {(m.full_name || m.username).charAt(0).toUpperCase()}
            </div>
            <div>
              <p className="text-[13px] font-semibold text-slate-800">{m.full_name || m.username}</p>
              <p className="text-[12px] text-slate-400">{m.username}</p>
            </div>
          </button>
        ))}
      </div>
    </div>
  )
}

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

export default function LoginPage() {
  const [settings, setSettings] = useState(null)
  const [managers, setManagers] = useState([])
  const [loadingInit, setLoadingInit] = useState(true)

  const [selectedManager, setSelectedManager] = useState(null)
  const [manualMode, setManualMode] = useState(false)
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [pin, setPin] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const { login } = useAuthStore()
  const navigate = useNavigate()
  const location = useLocation()
  const autoLoginAttempted = useRef(false)
  // manualLogout comes either from nav state (logout button) or sessionStorage (auto-logout)
  const manualLogout = location.state?.manualLogout === true
    || sessionStorage.getItem('pos_manual_logout') === 'true'

  // Write to sessionStorage when nav state says manualLogout, clear it on successful login
  useEffect(() => {
    if (location.state?.manualLogout) {
      sessionStorage.setItem('pos_manual_logout', 'true')
    }
  }, [])

  // Load security config + manager list in parallel (both public, no auth needed)
  useEffect(() => {
    Promise.all([
      client.get('/api/setup/security-config').catch(() => ({ data: { login_method: 'password', autofill_username: true } })),
      client.get('/api/auth/managers').catch(() => ({ data: [] })),
    ]).then(([configRes, managersRes]) => {
      setSettings(configRes.data)
      setManagers(managersRes.data)
    }).finally(() => setLoadingInit(false))
  }, [])

  const loginMethod    = settings?.login_method ?? 'password'
  const autofill       = settings?.autofill_username !== false
  const singleManager  = managers.length === 1 ? managers[0] : null

  // Suppressed in manual mode so the free-text input is shown instead
  const effectiveUsername = manualMode ? null
    : (selectedManager?.username || (autofill && singleManager ? singleManager.username : null))

  // Auto-login: none method + single manager → attempt exactly once, skip if manual logout
  useEffect(() => {
    if (!loadingInit && loginMethod === 'none' && singleManager && !manualLogout && !autoLoginAttempted.current) {
      autoLoginAttempted.current = true
      handleAutoLogin(singleManager.username)
    }
  }, [loadingInit, loginMethod, singleManager])

  function clearManualLogoutFlag() {
    sessionStorage.removeItem('pos_manual_logout')
  }

  async function handleAutoLogin(uname) {
    setLoading(true)
    try {
      const { data } = await client.post('/api/auth/login-no-auth', { username: uname })
      if (!data.user.perm_access_dashboard) { setLoading(false); return }
      clearManualLogoutFlag()
      login(data.user, data.access_token)
      navigate('/dashboard', { replace: true })
    } catch {
      setLoading(false)
    }
  }

  async function handleSubmit(e) {
    e?.preventDefault()
    const uname = effectiveUsername || username.trim()
    if (!uname) return
    if (loginMethod === 'password' && !password) return
    if (loginMethod === 'pin' && pin.length < 4) return

    setError('')
    setLoading(true)
    try {
      const body = { username: uname }
      if (loginMethod === 'password') body.password = password
      else if (loginMethod === 'pin') body.pin = pin

      const { data } = await client.post('/api/auth/login', body)
      if (!data.user.perm_access_dashboard) {
        setError('This account does not have manager access.')
        setPin('')
        setPassword('')
        return
      }
      clearManualLogoutFlag()
      login(data.user, data.access_token)
      navigate('/dashboard', { replace: true })
    } catch (err) {
      setError(err.response?.data?.detail || 'Invalid credentials')
      setPin('')
      setPassword('')
    } finally {
      setLoading(false)
    }
  }

  // Auto-submit on 4-digit PIN entry
  useEffect(() => {
    if (loginMethod === 'pin' && pin.length === 4) handleSubmit()
  }, [pin])

  // Show spinner while loading OR while auto-login is in progress (none mode, not manual logout)
  if (loadingInit || (loginMethod === 'none' && singleManager && !manualLogout && !manualMode)) {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center">
        <div className="w-6 h-6 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
      </div>
    )
  }

  // Multi-manager + none method: show picker first
  const needsPicker = loginMethod === 'none' && managers.length > 1 && !selectedManager

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-sky-50 flex items-center justify-center p-4">
      <div className="w-full max-w-sm">
        <div className="bg-white rounded-2xl shadow-xl shadow-slate-200/60 border border-slate-100 p-8">

          {needsPicker ? (
            <ManagerPicker managers={managers} onSelect={m => { setSelectedManager(m); handleAutoLogin(m.username) }} />
          ) : (
            <form onSubmit={handleSubmit} className="space-y-5">
              <div className="text-center space-y-1">
                <div className="flex justify-center mb-3">
                  <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-sky-500">
                    <KeyRound className="h-6 w-6 text-white" />
                  </div>
                </div>
                <h1 className="text-xl font-bold text-slate-900">Sign In</h1>
                <p className="text-[13px] text-slate-500">
                  {loginMethod === 'password' ? 'Enter your username and password'
                    : loginMethod === 'pin' ? 'Enter your username and PIN'
                    : 'Select your account'}
                </p>
              </div>

              {/* Username section */}
              {manualMode ? (
                <LabelledInput
                  icon={User}
                  placeholder="Username"
                  value={username}
                  onChange={e => setUsername(e.target.value)}
                  autoComplete="off"
                  autoFocus
                />
              ) : effectiveUsername ? (
                <div className="space-y-1">
                  <div className="flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
                    <div className="flex h-8 w-8 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[12px] flex-shrink-0">
                      {effectiveUsername.charAt(0).toUpperCase()}
                    </div>
                    <div>
                      <p className="text-[13px] font-medium text-slate-700">{effectiveUsername}</p>
                      <p className="text-[11px] text-slate-400">Manager</p>
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={() => { setManualMode(true); setSelectedManager(null); setUsername(''); setPassword(''); setPin(''); setError('') }}
                    className="text-[11px] text-slate-400 hover:text-sky-600 transition-colors w-full text-right pr-1"
                  >
                    Sign in as different account
                  </button>
                </div>
              ) : managers.length > 0 ? (
                <div className="space-y-2">
                  {managers.map(m => (
                    <button
                      key={m.id}
                      type="button"
                      onClick={() => setUsername(m.username)}
                      className={`w-full flex items-center gap-3 rounded-xl border p-3 text-left transition ${
                        username === m.username
                          ? 'border-sky-400 bg-sky-50'
                          : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
                      }`}
                    >
                      <div className="flex h-8 w-8 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[12px] flex-shrink-0">
                        {(m.full_name || m.username).charAt(0).toUpperCase()}
                      </div>
                      <div>
                        <p className="text-[13px] font-medium text-slate-800">{m.full_name || m.username}</p>
                        <p className="text-[11px] text-slate-400">{m.username}</p>
                      </div>
                    </button>
                  ))}
                  <button
                    type="button"
                    onClick={() => { setManualMode(true); setUsername(''); setPassword(''); setPin(''); setError('') }}
                    className="text-[11px] text-slate-400 hover:text-sky-600 transition-colors w-full text-right pr-1"
                  >
                    Sign in as different account
                  </button>
                </div>
              ) : (
                <LabelledInput
                  icon={User}
                  placeholder="Username"
                  value={username}
                  onChange={e => setUsername(e.target.value)}
                  autoComplete="off"
                  autoFocus
                />
              )}

              {/* Password input */}
              {loginMethod === 'password' && (
                <LabelledInput
                  icon={Lock}
                  placeholder="Password"
                  value={password}
                  onChange={e => setPassword(e.target.value)}
                  type="password"
                  autoComplete="current-password"
                  autoFocus={!!effectiveUsername}
                />
              )}

              {/* PIN pad */}
              {loginMethod === 'pin' && (
                <div className="space-y-3">
                  <PinDots length={4} filled={pin.length} />
                  <PinPad pin={pin} onChange={setPin} disabled={loading} />
                </div>
              )}

              {error && <p className="text-center text-[13px] text-rose-500">{error}</p>}

              {/* None mode: just a Log In button */}
              {loginMethod === 'none' && (
                <Button
                  type="button"
                  variant="primary"
                  disabled={loading || (!effectiveUsername && !username.trim())}
                  className="w-full justify-center py-3"
                  onClick={() => handleAutoLogin(effectiveUsername || username.trim())}
                >
                  {loading ? 'Signing in…' : 'Log In'}
                </Button>
              )}

              {/* Password mode: submit button */}
              {loginMethod === 'password' && (
                <Button
                  type="submit"
                  variant="primary"
                  disabled={loading || (!effectiveUsername && !username.trim()) || !password}
                  className="w-full justify-center py-3"
                >
                  {loading ? 'Signing in…' : 'Sign In'}
                </Button>
              )}

              {/* PIN mode: auto-submits, show verifying text */}
              {loading && loginMethod === 'pin' && (
                <p className="text-center text-[13px] text-slate-400">Verifying…</p>
              )}

            </form>
          )}
        </div>

        <p className="text-center text-[11px] text-slate-400 mt-4">Xenia POS · Manager Dashboard</p>
      </div>
    </div>
  )
}
