import { requireAuth } from "@/lib/session";
import { db } from "@/lib/db";
import ProfileForm from "./ProfileForm";

export default async function ProfilePage() {
  const session = await requireAuth();
  const userId = (session.user as any).id;

  const user = await db.user.findUnique({
    where: { id: userId },
    include: {
      team: {
        include: {
          players: { include: { player: { include: { country: true } } } },
        },
      },
    },
  });

  if (!user) return null;

  return (
    <div className="max-w-3xl mx-auto py-10 px-6">
      <h1 className="text-3xl font-bold mb-8">پروفایل</h1>
      <div className="grid grid-cols-2 gap-6">
        <ProfileForm user={{ id: user.id, name: user.name ?? "", email: user.email }} />

        <div className="bg-white rounded-2xl shadow p-6">
          <h2 className="font-bold text-lg mb-4">آمار من</h2>
          <div className="flex flex-col gap-3">
            <div className="flex justify-between">
              <span className="text-gray-500">نام تیم</span>
              <span className="font-medium">{user.team?.name ?? "-"}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">امتیاز کل</span>
              <span className="font-bold text-blue-700">{user.team?.totalPoints ?? 0}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">بودجه باقی‌مانده</span>
              <span className="font-medium text-green-700">
                {user.team
                  ? (user.team.budget - user.team.players.reduce((s, tp) => s + tp.player.price, 0)).toFixed(1)
                  : 100}M
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">تعداد بازیکنان</span>
              <span className="font-medium">{user.team?.players.length ?? 0} / 15</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
