import { useState, FormEvent } from 'react'
import Logo from '../components/common/Logo'
import Input from '../components/common/Input'
import Button from '../components/common/Button'
import styles from './LoginPage.module.css'

interface LoginErrors {
  userId?: string
  password?: string
  general?: string
}

export default function LoginPage() {
  const [userId, setUserId] = useState('')
  const [password, setPassword] = useState('')
  const [errors, setErrors] = useState<LoginErrors>({})

  const validateForm = (): boolean => {
    const newErrors: LoginErrors = {}

    if (!userId.trim()) {
      newErrors.userId = '아이디를 바르게 입력해주세요'
    }

    if (!password.trim()) {
      newErrors.password = '비밀번호를 입력해주세요'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()

    if (!validateForm()) {
      return
    }

    // TODO: API 로그인 로직 구현
    setErrors({
      general: '존재하지 않는 아이디이거나\n비밀번호가 잘못 입력되었습니다'
    })
  }

  return (
    <div className={styles.container}>
      {/* Background blur effect */}
      <div className={styles.bgBlur} />

      {/* Header / GNB */}
      <header className={styles.gnb}>
        <Logo variant="light" />
      </header>

      {/* Title */}
      <div className={styles.titleArea}>
        <h1 className={styles.title}>머크코리아</h1>
        <h1 className={styles.title}>작업자 위치관제 시스템</h1>
      </div>

      {/* Form Area */}
      <form className={styles.formArea} onSubmit={handleSubmit}>
        <div className={styles.inputGroup}>
          <Input
            label="아이디"
            placeholder="아이디를 입력해주세요"
            value={userId}
            onChange={(e) => setUserId(e.target.value)}
            error={errors.userId}
          />

          <Input
            label="패스워드"
            placeholder="암호를 입력해주세요"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            showPasswordToggle
            error={errors.password || errors.general}
          />
        </div>

        <Button type="submit" fullWidth>
          로그인
        </Button>
      </form>
    </div>
  )
}
