"use client";

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

type Group = { id: string; name: string };

export default function CountryForm({
  groups,
  initial,
  countryId,
}: {
  groups: Group[];
  initial?: { name: string; code: string; flagUrl?: string | null; groupId?: string | null };
  countryId?: string;
}) {
  const router = useRouter();
  const [form, setForm] = useState({
    name: initial?.name ?? "",
    code: initial?.code ?? "",
    flagUrl: initial?.flagUrl ?? "",
    groupId: initial?.groupId ?? "",
  });
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    const payload = { ...form, groupId: form.groupId || null, flagUrl: form.flagUrl || null };
    const res = await fetch(countryId ? `/api/countries/${countryId}` : "/api/countries", {
      method: countryId ? "PUT" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    if (res.ok) { router.push("/admin/countries"); 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="text" value={form.name} onChange={(e) => setForm({ ...form, name: 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">کد (مثلاً IRN)</label>
        <input type="text" value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value.toUpperCase() })}
          maxLength={3}
          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.flagUrl} onChange={(e) => setForm({ ...form, flagUrl: 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" />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">گروه</label>
        <select value={form.groupId} onChange={(e) => setForm({ ...form, groupId: e.target.value })}
          className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500">
          <option value="">بدون گروه</option>
          {groups.map((g) => <option key={g.id} value={g.id}>گروه {g.name}</option>)}
        </select>
      </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 ? "در حال ذخیره..." : countryId ? "ذخیره تغییرات" : "افزودن تیم"}
      </button>
    </form>
  );
}
