import { useState } from "react"
import { useAuth } from "../../context/AuthContext"
import { login as loginApi } from "../../api/auth/login"
import { register as registerApi } from "../../api/auth/register"

type LoginModalProps = {
  onClose: () => void
}

export default function LoginModal({ onClose }: LoginModalProps) {
  const [isRegister, setIsRegister] = useState(false)
  const [username, setUsername] = useState("")
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const { login } = useAuth() // global auth fonksiyonu

  const handleSubmit = async () => {
    try {
      if (isRegister) {
        const data = await registerApi(username, email, password)
        login(data.user, data.token)
      } else {
        const data = await loginApi(email, password)
        login(data.user, data.token)
      }
      onClose()
    } catch (err) {
      alert("Giriş/Kayıt başarısız")
    }
  }

  return (
    <div className="fixed inset-0 flex items-center justify-center bg-black/60">
      <div className="bg-background p-8 rounded-2xl w-96 shadow-xl relative">
        <button onClick={onClose} className="absolute top-3 right-3">×</button>
        <h2 className="text-xl font-semibold mb-6 text-center">
          {isRegister ? "Kayıt Ol" : "Giriş Yap"}
        </h2>

        {isRegister && (
          <input
            type="text"
            placeholder="Kullanıcı adı"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            className="w-full mb-3 p-3 rounded bg-surface border"
          />
        )}

        <input
          type="email"
          placeholder="E-posta"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="w-full mb-3 p-3 rounded bg-surface border"
        />
        <input
          type="password"
          placeholder="Şifre"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          className="w-full mb-5 p-3 rounded bg-surface border"
        />

        <div className="flex justify-center">
          <button onClick={handleSubmit} className="bg-primary text-white px-6 py-2 rounded">
            {isRegister ? "Kayıt Ol" : "Giriş Yap"}
          </button>
        </div>

        <p className="text-sm text-center mt-5">
          {isRegister ? "Zaten hesabın var mı?" : "Hesabın yok mu?"}
          <button
            onClick={() => setIsRegister(!isRegister)}
            className="text-primary hover:underline ml-1"
          >
            {isRegister ? "Giriş Yap" : "Kayıt Ol"}
          </button>
        </p>
      </div>
    </div>
  )
}
