import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { register, login, me } from '../api/auth'
import { useAuth } from '../store/auth'

export default function Register() {
  const [email, setEmail]       = useState('')
  const [password, setPassword] = useState('')
  const [confirm, setConfirm]   = useState('')
  const [error, setError]       = useState('')
  const [loading, setLoading]   = useState(false)
  const { setUser }             = useAuth()
  const navigate                = useNavigate()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    if (password !== confirm) { setError('Şifreler eşleşmiyor'); return }
    setLoading(true)
    try {
      await register(email, password)
      const data = await login(email, password)
      localStorage.setItem('access_token', data.access_token)
      localStorage.setItem('refresh_token', data.refresh_token)
      const user = await me()
      setUser(user)
      navigate('/kimlik-dogrulama')
    } catch (err: any) {
      setError(err.response?.data?.detail ?? 'Kayıt başarısız')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="row justify-content-center">
      <div className="col-md-5">
        <div className="card card-md">
          <div className="card-body">
            <h2 className="card-title text-center mb-4">Kayıt Ol</h2>
            {error && <div className="alert alert-danger">{error}</div>}
            <form onSubmit={handleSubmit}>
              <div className="mb-3">
                <label className="form-label">E-posta</label>
                <input type="email" className="form-control" value={email}
                  onChange={e => setEmail(e.target.value)} required autoFocus />
              </div>
              <div className="mb-3">
                <label className="form-label">Şifre</label>
                <input type="password" className="form-control" value={password}
                  onChange={e => setPassword(e.target.value)} required minLength={8} />
              </div>
              <div className="mb-3">
                <label className="form-label">Şifre Tekrar</label>
                <input type="password" className="form-control" value={confirm}
                  onChange={e => setConfirm(e.target.value)} required />
              </div>
              <div className="form-footer">
                <button type="submit" className="btn btn-primary w-100" disabled={loading}>
                  {loading ? <span className="spinner-border spinner-border-sm me-2" /> : null}
                  Kayıt Ol
                </button>
              </div>
            </form>
          </div>
        </div>
        <div className="text-center text-muted mt-3">
          Hesabın var mı? <Link to="/giris">Giriş Yap</Link>
        </div>
      </div>
    </div>
  )
}
