import { useEffect, useState } from 'react'
import {
  loginBackgroundImages,
  loginBackgroundSwitchMs,
  pickRandomBackgroundIndex,
} from '../config/loginBackgrounds'
import { useAuthStore } from '../store/authStore'

export default function Login() {
  const login = useAuthStore((s) => s.login)
  const loading = useAuthStore((s) => s.loading)
  const error = useAuthStore((s) => s.error)
  const [theme, setTheme] = useState(() => localStorage.getItem('hotel-pos-theme') || 'dark')

  const [username, setUsername] = useState('admin')
  const [password, setPassword] = useState('')
  const [bgIndex, setBgIndex] = useState(() => pickRandomBackgroundIndex(loginBackgroundImages.length))

  useEffect(() => {
    const interval = setInterval(() => {
      setBgIndex((currentIndex) => pickRandomBackgroundIndex(loginBackgroundImages.length, currentIndex))
    }, loginBackgroundSwitchMs)

    return () => clearInterval(interval)
  }, [])

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('hotel-pos-theme', theme)
  }, [theme])

  const onSubmit = async (e) => {
    e.preventDefault()
    await login(username.trim(), password)
  }

  return (
    <div
      className="login-page"
      style={{
        '--login-bg-image': `url("${loginBackgroundImages[bgIndex]}")`,
      }}
    >
      <div className="login-theme-row">
        <button
          type="button"
          className="tb-theme-toggle login-theme-toggle"
          onClick={() => setTheme((t) => (t === 'dark' ? 'light' : 'dark'))}
          aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
          title={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
        >
          <span className="tb-theme-icon" aria-hidden>
            {theme === 'dark' ? '🌙' : '☀️'}
          </span>
          <span className="tb-theme-label">{theme === 'dark' ? 'Dark' : 'Light'}</span>
          <span className={`tb-theme-knob${theme === 'light' ? ' on' : ''}`} aria-hidden />
        </button>
      </div>
      <div className="login-card">
        <div className="login-brand">
          <img src="/one-island-resort.jpeg" alt="" className="login-logo" />
        </div>
        <h1 className="login-title">Staff sign in</h1>
        <p className="login-hint">Use the admin account created by the API</p>
        <form onSubmit={onSubmit} className="login-form">
          <div className="fgroup">
            <label className="lbl" htmlFor="login-user">
              Username
            </label>
            <input
              id="login-user"
              type="text"
              autoComplete="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              disabled={loading}
            />
          </div>
          <div className="fgroup">
            <label className="lbl" htmlFor="login-pass">
              Password
            </label>
            <input
              id="login-pass"
              type="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              disabled={loading}
            />
          </div>
          {error ? <div className="login-error">{String(error)}</div> : null}
          <button type="submit" className="btn btn-primary w100 login-submit" disabled={loading}>
            {loading ? 'Signing in…' : 'Sign in'}
          </button>
        </form>
      </div>
    </div>
  )
}
