"use client";

import { signIn } from "next-auth/react";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    const res = await signIn("credentials", { email, password, redirect: false });
    if (res?.error) {
      setError("ایمیل یا رمز عبور اشتباه است");
      setLoading(false);
    } else {
      router.push("/team");
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <div className="text-5xl mb-3">⚽</div>
          <h1 className="text-2xl font-bold">ورود به فانتزی جام جهانی</h1>
        </div>
        <form onSubmit={handleSubmit} className="bg-white p-8 rounded-2xl shadow-lg">
          {error && (
            <div className="bg-red-50 text-red-600 text-sm px-4 py-3 rounded-xl mb-4">
              {error}
            </div>
          )}
          <div className="mb-4">
            <label className="block text-sm font-medium mb-1">ایمیل</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full border-2 rounded-xl px-4 py-3 focus:outline-none focus:border-green-500 transition"
              required
            />
          </div>
          <div className="mb-6">
            <label className="block text-sm font-medium mb-1">رمز عبور</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full border-2 rounded-xl px-4 py-3 focus:outline-none focus:border-green-500 transition"
              required
            />
          </div>
          <button
            type="submit"
            disabled={loading}
            className="w-full bg-green-700 text-white py-3 rounded-xl font-bold text-lg hover:bg-green-800 transition disabled:opacity-50"
          >
            {loading ? "در حال ورود..." : "ورود"}
          </button>
          <p className="text-center text-sm mt-4 text-gray-500">
            حساب نداری؟{" "}
            <Link href="/register" className="text-green-600 hover:underline font-medium">
              ثبت‌نام
            </Link>
          </p>
        </form>
      </div>
    </div>
  );
}
