import { db } from "@/lib/db";
import StatsForm from "./StatsForm";

export default async function AdminStatsPage({
  searchParams,
}: {
  searchParams: { matchId?: string };
}) {
  const matches = await db.match.findMany({
    include: { homeTeam: true, awayTeam: true },
    orderBy: { matchDate: "desc" },
  });

  const selectedMatch = searchParams.matchId
    ? await db.match.findUnique({
        where: { id: searchParams.matchId },
        include: {
          homeTeam: { include: { players: true } },
          awayTeam: { include: { players: true } },
          playerStats: { include: { player: true } },
        },
      })
    : null;

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6">ثبت آمار بازیکنان</h1>

      <div className="mb-6">
        <label className="block text-sm font-medium mb-2">انتخاب بازی</label>
        <form method="GET">
          <select
            name="matchId"
            defaultValue={searchParams.matchId ?? ""}
            onChange={(e) => {
              if (typeof window !== "undefined") {
                window.location.href = `/admin/stats?matchId=${(e.target as HTMLSelectElement).value}`;
              }
            }}
            className="border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500 w-full max-w-md"
          >
            <option value="">انتخاب بازی...</option>
            {matches.map((m) => (
              <option key={m.id} value={m.id}>
                {m.homeTeam.name} vs {m.awayTeam.name} - {new Date(m.matchDate).toLocaleDateString("fa-IR")}
              </option>
            ))}
          </select>
        </form>
      </div>

      {selectedMatch && <StatsForm match={selectedMatch} />}
    </div>
  );
}
