"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;
    flagImage?: string | null;
    groupId?: string | null;
    confederation?: string | null;
    qualificationMethod?: string | null;
    qualificationDate?: string | null;
    participationHistory?: string | null;
    bestResult?: string | null;
    description?: string | null;
  };
  countryId?: string;
}) {
  const router = useRouter();
  const [form, setForm] = useState({
    name: initial?.name ?? "",
    code: initial?.code ?? "",
    flagUrl: initial?.flagUrl ?? "",
    flagImage: initial?.flagImage ?? "",
    groupId: initial?.groupId ?? "",
    confederation: initial?.confederation ?? "",
    qualificationMethod: initial?.qualificationMethod ?? "",
    qualificationDate: initial?.qualificationDate ?? "",
    participationHistory: initial?.participationHistory ?? "",
    bestResult: initial?.bestResult ?? "",
    description: initial?.description ?? "",
  });
  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,
      flagImage: form.flagImage || null,
      confederation: form.confederation || null,
      qualificationMethod: form.qualificationMethod || null,
      qualificationDate: form.qualificationDate || null,
      participationHistory: form.participationHistory || null,
      bestResult: form.bestResult || null,
      description: form.description || 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 max-w-3xl">
      <h3 className="text-lg font-bold mb-2">اطلاعات پایه</h3>
      
      <div className="grid grid-cols-2 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>

      <div className="grid grid-cols-2 gap-4">
        <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>
          <input
            type="text"
            value={form.flagImage}
            onChange={(e) => setForm({ ...form, flagImage: e.target.value })}
            placeholder="Flag_of_Iran.webp"
            className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500"
          />
          <p className="text-xs text-gray-500 mt-1">فایل باید در public/imgs/flags باشد</p>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <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>
        <div>
          <label className="block text-sm font-medium mb-1">کنفدراسیون</label>
          <select
            value={form.confederation}
            onChange={(e) => setForm({ ...form, confederation: 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>
            <option value="UEFA">UEFA (اروپا)</option>
            <option value="AFC">AFC (آسیا)</option>
            <option value="CAF">CAF (آفریقا)</option>
            <option value="CONMEBOL">CONMEBOL (آمریکای جنوبی)</option>
            <option value="CONCACAF">CONCACAF (آمریکای شمالی)</option>
            <option value="OFC">OFC (اقیانوسیه)</option>
          </select>
        </div>
      </div>

      <hr className="my-2" />
      <h3 className="text-lg font-bold mb-2">اطلاعات راه‌یابی</h3>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">شیوه راه‌یابی</label>
          <input
            type="text"
            value={form.qualificationMethod}
            onChange={(e) => setForm({ ...form, qualificationMethod: 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>
          <input
            type="text"
            value={form.qualificationDate}
            onChange={(e) => setForm({ ...form, qualificationDate: 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>

      <div>
        <label className="block text-sm font-medium mb-1">سابقه شرکت در مسابقات</label>
        <input
          type="text"
          value={form.participationHistory}
          onChange={(e) => setForm({ ...form, participationHistory: 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>
        <input
          type="text"
          value={form.bestResult}
          onChange={(e) => setForm({ ...form, bestResult: 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>
        <textarea
          value={form.description}
          onChange={(e) => setForm({ ...form, description: e.target.value })}
          rows={4}
          placeholder="توضیحات کامل درباره تیم..."
          className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500"
        />
      </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>
  );
}
