import Link from "next/link"
import { getEventById } from "@/lib/mock-data"
import { MatchDetailView } from "@/components/betting/match-detail-view"
import {
  fetchEvents,
  fetchOddsForEvent,
  apiEventToAppEvent,
  get1X2ForEvent,
  apiOddsToSections,
} from "@/lib/betting-api"
import type { Event } from "@/lib/mock-data"

export default async function EventPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  let event: Event | undefined = getEventById(id)
  let apiSections: { id: string; title: string; outcomes: { label: string; odds: number }[] }[] | undefined

  const numericId = id.trim() !== "" && !Number.isNaN(Number(id)) ? Number(id) : null
  if (numericId !== null) {
    try {
      const [eventsRes, oddsRes] = await Promise.all([
        fetchEvents({ page_size: 500, page: 1 }),
        fetchOddsForEvent(numericId),
      ])
      const apiEvent = (eventsRes.data ?? []).find((e) => e.id === numericId)
      if (apiEvent) {
        event = apiEventToAppEvent(apiEvent, get1X2ForEvent(oddsRes.data ?? [], apiEvent.id))
      } else {
        event = {
          id: String(numericId),
          sport: "Football",
          sportIcon: "⚽",
          league: "",
          country: "",
          homeTeam: "Home",
          awayTeam: "Away",
          time: "",
          date: "",
          isLive: false,
          markets: [],
          totalMarkets: 0,
        }
      }
      apiSections = apiOddsToSections(oddsRes.data ?? [])
    } catch {
      if (!event) event = undefined
    }
  }

  if (!event) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[40vh] gap-4">
        <p className="text-white/80">Match not found.</p>
        <Link href="/" className="text-brand-primary font-bold hover:underline">
          Back to home
        </Link>
      </div>
    )
  }

  return <MatchDetailView event={event} apiSections={apiSections} />
}
