import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Gamepad2, User, Lock, X, Minus, Shield, ArrowLeft } from 'lucide-react'
import { useAuthStore } from '../store/auth'
import { NeonButton } from '../components/ui/NeonButton'
import { Input } from '../components/ui/Input'

export function LoginPage() {
  const navigate = useNavigate()
  const { login, verify2fa, isLoading, error, clearError, requires2fa, reset2fa } = useAuthStore()
  const [formData, setFormData] = useState({
    login: '',
    password: '',
  })
  const [twoFactorCode, setTwoFactorCode] = useState('')

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const success = await login(formData.login, formData.password)
    if (success) {
      navigate('/')
    }
  }

  const handle2faSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const success = await verify2fa(twoFactorCode)
    if (success) {
      navigate('/')
    }
  }

  const handleBack = () => {
    reset2fa()
    setTwoFactorCode('')
  }

  return (
    <div className="min-h-screen bg-dark-900 flex flex-col">
      {/* Custom title bar */}
      <div className="titlebar h-8 bg-dark-950 flex items-center justify-between px-2 border-b border-dark-700">
        <div className="flex items-center gap-2">
          <Gamepad2 className="w-4 h-4 text-neon-500" />
          <span className="text-xs font-medium text-gray-400">Game Marathon Tracker</span>
        </div>
        <div className="flex items-center">
          <button
            onClick={() => window.electronAPI.minimizeToTray()}
            className="w-8 h-8 flex items-center justify-center hover:bg-dark-700 transition-colors"
          >
            <Minus className="w-4 h-4 text-gray-400" />
          </button>
          <button
            onClick={() => window.electronAPI.quitApp()}
            className="w-8 h-8 flex items-center justify-center hover:bg-red-600 transition-colors"
          >
            <X className="w-4 h-4 text-gray-400" />
          </button>
        </div>
      </div>

      {/* Login form */}
      <div className="flex-1 flex items-center justify-center p-6">
        <div className="w-full max-w-sm">
          {/* Logo */}
          <div className="text-center mb-8">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-neon-500/10 border border-neon-500/30 mb-4">
              {requires2fa ? (
                <Shield className="w-8 h-8 text-neon-500" />
              ) : (
                <Gamepad2 className="w-8 h-8 text-neon-500" />
              )}
            </div>
            <h1 className="text-2xl font-display font-bold text-white mb-2">
              {requires2fa ? 'Подтверждение' : 'Game Marathon'}
            </h1>
            <p className="text-gray-400 text-sm">
              {requires2fa
                ? 'Введите код из Telegram'
                : 'Войдите в свой аккаунт'}
            </p>
          </div>

          {requires2fa ? (
            /* 2FA Form */
            <form onSubmit={handle2faSubmit} className="space-y-4">
              <Input
                label="Код подтверждения"
                type="text"
                value={twoFactorCode}
                onChange={(e) => {
                  setTwoFactorCode(e.target.value.replace(/\D/g, '').slice(0, 6))
                  clearError()
                }}
                icon={<Shield className="w-5 h-5" />}
                placeholder="000000"
                maxLength={6}
                required
                autoFocus
              />

              {error && (
                <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
                  <p className="text-sm text-red-400">{error}</p>
                </div>
              )}

              <NeonButton
                type="submit"
                className="w-full"
                size="lg"
                isLoading={isLoading}
                disabled={twoFactorCode.length !== 6}
              >
                Подтвердить
              </NeonButton>

              <button
                type="button"
                onClick={handleBack}
                className="w-full flex items-center justify-center gap-2 text-gray-400 hover:text-white transition-colors py-2"
              >
                <ArrowLeft className="w-4 h-4" />
                Назад
              </button>
            </form>
          ) : (
            /* Login Form */
            <form onSubmit={handleSubmit} className="space-y-4">
              <Input
                label="Логин"
                type="text"
                value={formData.login}
                onChange={(e) => {
                  setFormData({ ...formData, login: e.target.value })
                  clearError()
                }}
                icon={<User className="w-5 h-5" />}
                placeholder="Введите логин"
                required
              />

              <Input
                label="Пароль"
                type="password"
                value={formData.password}
                onChange={(e) => {
                  setFormData({ ...formData, password: e.target.value })
                  clearError()
                }}
                icon={<Lock className="w-5 h-5" />}
                placeholder="Введите пароль"
                required
              />

              {error && (
                <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
                  <p className="text-sm text-red-400">{error}</p>
                </div>
              )}

              <NeonButton
                type="submit"
                className="w-full"
                size="lg"
                isLoading={isLoading}
              >
                Войти
              </NeonButton>
            </form>
          )}

          {/* Footer */}
          {!requires2fa && (
            <p className="text-center text-gray-500 text-xs mt-6">
              Нет аккаунта? Зарегистрируйтесь на сайте
            </p>
          )}
        </div>
      </div>
    </div>
  )
}
