"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"

const API_URL =
  process.env.NEXT_PUBLIC_API_URL ||
  "https://wordpress-manager-2026.backend.devuocloud.com"

export default function LoginForm() {
  const router = useRouter()
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError("")

    try {
      const res = await fetch(`${API_URL}/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password })
      })

      if (!res.ok) throw new Error("Credenciales inválidas")

      const data = await res.json()
      document.cookie = `token=${data.token}; path=/; max-age=86400; SameSite=Lax`

      router.push("/dashboard")
      router.refresh()
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200 px-6">
      <div className="w-full max-w-md bg-white/90 backdrop-blur rounded-3xl shadow-2xl p-10 border border-gray-200">
        <div className="text-center mb-10">
          <h1 className="text-5xl font-extrabold text-orange-600 tracking-tight">
            UO
          </h1>
          <p className="text-gray-500 mt-2 text-sm">Wordpress Manager</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-600">Email</label>
            <input
              type="email"
              required
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="tu@email.com"
              className="w-full rounded-xl border border-gray-300 bg-white px-4 py-3 focus:ring-2 focus:ring-orange-500 focus:border-orange-500 outline-none transition"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-600">Password</label>
            <input
              type="password"
              required
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="••••••••"
              className="w-full rounded-xl border border-gray-300 bg-white px-4 py-3 focus:ring-2 focus:ring-orange-500 focus:border-orange-500 outline-none transition"
            />
          </div>

          {error && (
            <div className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-xl p-3">
              {error}
            </div>
          )}

          <button
            disabled={loading}
            className="w-full rounded-xl bg-orange-600 hover:bg-orange-700 text-white font-semibold py-3 transition disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {loading ? "Ingresando..." : "Log in"}
          </button>
        </form>

        <p className="text-xs text-gray-400 text-center mt-8">© UO Solutions</p>
      </div>
    </div>
  )
}
