import { useState } from 'react'
import type { FormEvent } from 'react'
import {
  Eye,
  EyeOff,
  LockKeyhole,
  Moon,
  Sun,
  UserRound,
} from 'lucide-react'

import { authService } from '../../features/auth/api/authService'
import { useTheme } from '../../shared/theme/useTheme'
import LogoIcon from '../../assets/LogoIcon.svg'
import LogoIconWhite from '../../assets/LogoIconWhite.svg'

import './LoginPage.scss'

type LoginPageProps = {
  onSuccess: () => void
}

export function LoginPage({ onSuccess }: LoginPageProps) {
  const [username, setUsername] = useState('admin@fleet.local')
  const [password, setPassword] = useState('123456')
  const [isPasswordVisible, setIsPasswordVisible] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const { isDark, toggleTheme } = useTheme()
  const logo = isDark ? LogoIconWhite : LogoIcon
  const canSubmit = Boolean(username.trim()) && Boolean(password.trim())

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!canSubmit || loading) return

    try {
      setLoading(true)
      setError(null)
      await authService.login(username.trim(), password)
      onSuccess()
    } catch (loginError) {
      setError(
        loginError instanceof Error
          ? loginError.message
          : 'Не удалось войти',
      )
    } finally {
      setLoading(false)
    }
  }

  return (
    <main className="login-page">
      <button
        className={`login-theme-button ${isDark ? 'is-dark' : 'is-light'}`}
        type="button"
        aria-label={isDark ? 'Включить светлую тему' : 'Включить тёмную тему'}
        aria-pressed={isDark}
        onClick={(event) => toggleTheme(event.currentTarget)}
      >
        {isDark ? <Moon size={18} /> : <Sun size={18} />}
      </button>

      <form className="login-card" onSubmit={handleSubmit}>
        <div className="login-card__header">
          <span className="login-card__logo">
            <img src={logo} height={40} width={40} alt="Fleet BLE Monitor" />
          </span>

          <div>
            <p>Авторизуйтесь для доступа <br></br>к Fleet BLE Monitor</p>
          </div>
        </div>

        <label className="login-field">
          <span className="login-field__label">Логин или email</span>

          <span className="login-field__control">
            <UserRound size={18} />

            <input
              value={username}
              onChange={(event) => setUsername(event.target.value)}
              placeholder="Введите логин или email"
              autoComplete="username"
            />
          </span>
        </label>

        <label className="login-field">
          <span className="login-field__label">Пароль</span>

          <span className="login-field__control">
            <LockKeyhole size={18} />

            <input
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              placeholder="Введите пароль"
              type={isPasswordVisible ? 'text' : 'password'}
              autoComplete="current-password"
            />

            <button
              className="login-field__password-toggle"
              type="button"
              aria-label={isPasswordVisible ? 'Скрыть пароль' : 'Показать пароль'}
              aria-pressed={isPasswordVisible}
              onClick={() => setIsPasswordVisible((value) => !value)}
            >
              {isPasswordVisible ? <EyeOff size={18} /> : <Eye size={18} />}
            </button>
          </span>
        </label>

        {error && (
          <div className="login-error">
            {error}
          </div>
        )}

        <button className="login-button" type="submit" disabled={loading || !canSubmit}>
          {loading ? 'Входим...' : 'Войти'}
        </button>
      </form>
    </main>
  )
}
