import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { GlassCard } from "@/components/ui/glass-card";
import { TeamBadge } from "@/components/teams/TeamBadge";

export default async function FixturesPage({
  params,
}: {
  params: Promise<{ leagueId: string; competitionId: string }>;
}) {
  const { leagueId, competitionId } = await params;
  const supabase = await createClient();

  const { data: matches } = await supabase
    .from("matches")
    .select(
      `*, home:home_team_id(id, name, logo_path), away:away_team_id(id, name, logo_path)`
    )
    .eq("competition_id", competitionId)
    .order("matchday")
    .order("round");

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Fixtures</h1>
      <GlassCard>
        <ul className="divide-y divide-white/10">
          {matches?.map((m) => {
            const home = m.home as { id: string; name: string; logo_path: string | null };
            const away = m.away as { id: string; name: string; logo_path: string | null };
            return (
              <li key={m.id} className="py-4">
                <Link
                  href={`/leagues/${leagueId}/competitions/${competitionId}/matches/${m.id}`}
                  className="flex flex-wrap items-center justify-between gap-4 hover:opacity-90"
                >
                  <div className="flex items-center gap-4">
                    <TeamBadge name={home?.name} logoPath={home?.logo_path} />
                    <span className="text-lg font-semibold">
                      {m.status === "completed"
                        ? `${m.home_score} – ${m.away_score}`
                        : "vs"}
                    </span>
                    <TeamBadge name={away?.name} logoPath={away?.logo_path} />
                  </div>
                  <div className="text-right text-xs text-[var(--color-muted)]">
                    {m.matchday && <span>MD {m.matchday} · </span>}
                    <span className="capitalize">{m.status.replace(/_/g, " ")}</span>
                    {m.venue && <p className="mt-0.5">{m.venue}</p>}
                  </div>
                </Link>
              </li>
            );
          })}
        </ul>
      </GlassCard>
    </div>
  );
}
