import { db } from "@/lib/db";
import type { Prisma } from "@/lib/generated/prisma";
import Link from "next/link";
import CountryFlag from "@/components/CountryFlag";

type CountryWithAdminListData = Prisma.CountryGetPayload<{
  include: {
    group: true;
    _count: { select: { players: true } };
  };
}>;

export default async function AdminCountriesPage() {
  const countries: CountryWithAdminListData[] = await db.country.findMany({
    include: {
      group: true,
      _count: { select: { players: true } },
    },
    orderBy: { name: "asc" },
  });

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">تیم‌های ملی</h1>
        <Link href="/admin/countries/new" className="bg-green-700 text-white px-5 py-2 rounded-xl hover:bg-green-800 transition font-medium">
          + تیم جدید
        </Link>
      </div>
      <div className="grid grid-cols-1 gap-4">
        {countries.map((c) => (
          <div key={c.id} className="bg-white rounded-2xl shadow p-5 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
                <CountryFlag
                  flagImage={c.flagImage}
                  flagEmoji={c.flagUrl}
                  countryName={c.name}
                  size="md"
                />
              </div>
              <div>
                <div className="font-bold">{c.name}</div>
                <div className="text-sm text-gray-500">
                  {c.code} · 
                  {c.confederation && ` ${c.confederation} · `}
                  گروه {c.group?.name ?? "-"} · {c._count.players} بازیکن · 
                  ترکیب: {c.defaultFormation} · 
                  {(c.defaultLineupPlayerIds?.length ?? 0) > 0 ? `✓ ${c.defaultLineupPlayerIds.length} بازیکن` : "بدون ترکیب"}
                </div>
              </div>
            </div>
            <div className="flex gap-2">
              <Link href={`/admin/countries/${c.id}/lineup`} 
                className="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-700 transition font-medium">
                ترکیب پیش‌فرض
              </Link>
              <Link href={`/admin/countries/${c.id}/edit`} 
                className="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg text-sm hover:bg-gray-300 transition font-medium">
                ویرایش
              </Link>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
