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

export default async function AdminTeamsPage() {
  const teams = await db.team.findMany({
    include: {
      user: { select: { name: true, email: true } },
      players: { include: { player: { include: { country: true } } } },
    },
    orderBy: { createdAt: "desc" },
  });

  const pending = teams.filter((t) => t.status === "PENDING");
  const others = teams.filter((t) => t.status !== "PENDING");

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6">مدیریت تیم‌ها</h1>

      {pending.length > 0 && (
        <div className="mb-8">
          <h2 className="text-lg font-bold text-yellow-700 mb-3 flex items-center gap-2">
            <span className="w-2 h-2 bg-yellow-500 rounded-full inline-block"></span>
            در انتظار تایید ({pending.length})
          </h2>
          <div className="flex flex-col gap-4">
            {pending.map((t) => <TeamApprovalRow key={t.id} team={t} />)}
          </div>
        </div>
      )}

      <div>
        <h2 className="text-lg font-bold text-gray-700 mb-3">سایر تیم‌ها</h2>
        <div className="bg-white rounded-2xl shadow overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-gray-100 text-gray-600">
              <tr>
                <th className="text-right px-5 py-3">تیم</th>
                <th className="text-right px-5 py-3">مدیر</th>
                <th className="text-right px-5 py-3">ترکیب</th>
                <th className="text-right px-5 py-3">بازیکنان</th>
                <th className="text-right px-5 py-3">امتیاز</th>
                <th className="text-right px-5 py-3">وضعیت</th>
              </tr>
            </thead>
            <tbody>
              {others.map((t) => (
                <tr key={t.id} className="border-t hover:bg-gray-50">
                  <td className="px-5 py-3 font-medium">{t.name}</td>
                  <td className="px-5 py-3 text-gray-500">{t.user.name ?? t.user.email}</td>
                  <td className="px-5 py-3">{t.formation}</td>
                  <td className="px-5 py-3">{t.players.length}</td>
                  <td className="px-5 py-3 font-bold text-blue-700">{t.totalPoints}</td>
                  <td className="px-5 py-3">
                    <span className={`text-xs px-2 py-1 rounded-full font-medium ${
                      t.status === "APPROVED" ? "bg-green-100 text-green-700" :
                      t.status === "REJECTED" ? "bg-red-100 text-red-600" :
                      "bg-gray-100 text-gray-600"
                    }`}>
                      {t.status === "APPROVED" ? "تایید" : t.status === "REJECTED" ? "رد" : "پیش‌نویس"}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
