"use client";

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

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    if (!form.deadline) {
      setError("ددلاین را انتخاب کنید.");
      return;
    }

    setLoading(true);
    setError("");
    const res = await fetch("/api/gameweeks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...form, number: parseInt(form.number, 10) }),
    });
    if (res.ok) {
      setForm({ number: "", name: "", deadline: "" });
      router.refresh();
    } else {
      const d = await res.json();
      setError(d.error ?? "خطا در ذخیره");
    }
    setLoading(false);
  }

  return (
    <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow p-6 flex flex-col gap-4">
      {error && <p className="text-red-500 text-sm bg-red-50 px-3 py-2 rounded-lg">{error}</p>}
      <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>
      <PersianDateField
        label="ددلاین انتخاب تیم"
        value={form.deadline}
        onChange={(value) => setForm({ ...form, deadline: value })}
        mode="datetime"
        required
      />
      <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>
  );
}
