import { db } from "@/lib/db";
import PositionBadge from "@/components/PositionBadge";

export default async function PlayersPage({
  searchParams,
}: {
  searchParams: { position?: string; country?: string };
}) {
  const players = await db.player.findMany({
    where: {
      ...(searchParams.position ? { position: searchParams.position as any } : {}),
      ...(searchParams.country ? { countryId: searchParams.country } : {}),
    },
    include: { country: true },
    orderBy: { totalPoints: "desc" },
  });

  const countries = await db.country.findMany({ orderBy: { name: "asc" } });

  return (
    <div className="max-w-6xl mx-auto py-10 px-6">
      <h1 className="text-3xl font-bold mb-8">بازیکنان</h1>

      {/* فیلترها */}
      <div className="flex gap-3 mb-6 flex-wrap">
        {["", "GK", "DEF", "MID", "FWD"].map((pos) => (
          <a
            key={pos}
            href={pos ? `?position=${pos}` : "/players"}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition ${
              searchParams.position === pos || (!searchParams.position && !pos)
                ? "bg-green-700 text-white"
                : "bg-white text-gray-700 hover:bg-gray-100 shadow"
            }`}
          >
            {pos === "" ? "همه" : pos === "GK" ? "دروازه‌بان" : pos === "DEF" ? "مدافع" : pos === "MID" ? "هافبک" : "مهاجم"}
          </a>
        ))}
      </div>

      {/* جدول */}
      <div className="bg-white rounded-2xl shadow overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-green-800 text-white">
            <tr>
              <th className="text-right px-5 py-4">#</th>
              <th className="text-right px-5 py-4">بازیکن</th>
              <th className="text-right px-5 py-4">پست</th>
              <th className="text-right px-5 py-4">تیم ملی</th>
              <th className="text-right px-5 py-4">قیمت</th>
              <th className="text-right px-5 py-4">امتیاز</th>
            </tr>
          </thead>
          <tbody>
            {players.map((p, i) => (
              <tr key={p.id} className="border-t hover:bg-green-50 transition">
                <td className="px-5 py-4 text-gray-400">{i + 1}</td>
                <td className="px-5 py-4 font-semibold">{p.name}</td>
                <td className="px-5 py-4">
                  <PositionBadge position={p.position} />
                </td>
                <td className="px-5 py-4 text-gray-600">{p.country.name}</td>
                <td className="px-5 py-4 text-green-700 font-bold">{p.price}M</td>
                <td className="px-5 py-4 font-bold text-blue-700">{p.totalPoints}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
