"use client";

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

type Round = {
  id: string;
  number: number;
  name: string;
  deadline: Date;
};

export default function RoundForm({ editRound }: { editRound?: Round }) {
  const router = useRouter();
  const [form, setForm] = useState({
    number: editRound?.number.toString() ?? "",
    name: editRound?.name ?? "",
    deadline: editRound ? String(editRound.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 method = editRound ? "PUT" : "POST";
    const body = editRound
      ? { id: editRound.id, ...form, number: parseInt(form.number, 10) }
      : { ...form, number: parseInt(form.number, 10) };

    const res = await fetch("/api/rounds", {
      method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });

    if (res.ok) {
      setForm({ number: "", name: "", deadline: "" });
      router.refresh();
      router.push("/admin/rounds");
    } 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 ? "در حال ذخیره..." : editRound ? "ویرایش دور" : "افزودن دور"}
      </button>
    </form>
  );
}
