"use client";

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

export default function GameweekForm() {
  const router = useRouter();
  const [form, setForm] = useState({ number: "", name: "", deadline: "" });
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    const res = await fetch("/api/gameweeks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...form, number: parseInt(form.number) }),
    });
    if (res.ok) {
      setForm({ number: "", name: "", deadline: "" });
      router.refresh();
    }
    setLoading(false);
  }

  return (
    <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow p-6 flex flex-col gap-4">
      <div>
        <label className="block text-sm font-medium mb-1">شماره هفته</label>
        <input type="number" min="1" value={form.number} onChange={(e) => setForm({ ...form, number: e.target.value })}
          className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500" required />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">نام</label>
        <input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
          placeholder="مثلاً: مرحله گروهی - روز ۱"
          className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500" required />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">deadline انتخاب تیم</label>
        <input type="datetime-local" value={form.deadline} onChange={(e) => setForm({ ...form, deadline: e.target.value })}
          className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500" required />
      </div>
      <button type="submit" disabled={loading}
        className="bg-green-700 text-white py-3 rounded-xl font-bold hover:bg-green-800 transition disabled:opacity-50">
        {loading ? "در حال ذخیره..." : "افزودن هفته"}
      </button>
    </form>
  );
}
