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

const stageLabel: Record<string, string> = {
  GROUP: "مرحله گروهی",
  ROUND_OF_16: "یک‌هشتم نهایی",
  QUARTER_FINAL: "یک‌چهارم نهایی",
  SEMI_FINAL: "نیمه‌نهایی",
  THIRD_PLACE: "رده‌بندی",
  FINAL: "فینال",
};

const statusStyle: Record<string, string> = {
  SCHEDULED: "bg-gray-100 text-gray-600",
  LIVE: "bg-red-100 text-red-600 animate-pulse",
  FINISHED: "bg-green-100 text-green-700",
};

const statusLabel: Record<string, string> = {
  SCHEDULED: "برنامه‌ریزی شده",
  LIVE: "🔴 زنده",
  FINISHED: "پایان یافته",
};

export default async function MatchesPage() {
  const matches = await db.match.findMany({
    include: { homeTeam: true, awayTeam: true, round: true },
    orderBy: { matchDate: "asc" },
  });

  const grouped = matches.reduce((acc, m) => {
    const key = m.stage;
    if (!acc[key]) acc[key] = [];
    acc[key].push(m);
    return acc;
  }, {} as Record<string, typeof matches>);

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

      {Object.entries(grouped).map(([stage, stageMatches]) => (
        <div key={stage} className="mb-10">
          <h2 className="text-xl font-bold text-green-800 mb-4 border-b-2 border-green-200 pb-2">
            {stageLabel[stage] ?? stage}
          </h2>
          <div className="flex flex-col gap-3">
            {stageMatches.map((m) => (
              <div key={m.id} className="bg-white rounded-2xl shadow p-5 flex items-center justify-between">
                <div className="flex items-center gap-4 flex-1 justify-end">
                  <span className="font-bold text-lg">{m.homeTeam.name}</span>
                  <span className="text-2xl">{m.homeTeam.flagUrl ?? "🏳️"}</span>
                </div>
                <div className="mx-6 text-center min-w-[100px]">
                  {m.status === "FINISHED" || m.status === "LIVE" ? (
                    <div className="text-3xl font-bold">
                      {m.homeScore} - {m.awayScore}
                    </div>
                  ) : (
                    <div className="text-sm text-gray-500">
                      {new Date(m.matchDate).toLocaleDateString("fa-IR")}
                    </div>
                  )}
                  <span className={`text-xs px-2 py-0.5 rounded-full mt-1 inline-block ${statusStyle[m.status]}`}>
                    {statusLabel[m.status]}
                  </span>
                </div>
                <div className="flex items-center gap-4 flex-1 justify-start">
                  <span className="text-2xl">{m.awayTeam.flagUrl ?? "🏳️"}</span>
                  <span className="font-bold text-lg">{m.awayTeam.name}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}

      {matches.length === 0 && (
        <div className="text-center text-gray-400 py-20">هنوز بازی‌ای ثبت نشده</div>
      )}
    </div>
  );
}
