import Link from 'next/link'
import { notFound } from 'next/navigation'
import { serverGet } from '@/lib/api'
import type { Gym } from '@/lib/types'
import { money, ldJson } from '@/lib/format'

const SITE = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'

async function getGym(id: string): Promise<Gym | null> {
  try { const r = await serverGet<{ data: Gym } | Gym>(`/gyms/${id}`, 300); return (r as { data?: Gym }).data ?? (r as Gym) } catch { return null }
}

export async function generateMetadata({ params }: { params: { id: string } }) {
  const g = await getGym(params.id)
  if (!g) return { title: 'Gym' }
  const desc = (g as { description?: string }).description?.slice(0, 155) || `${g.name} — ${g.city || 'fitness facility'} on Fitorza. View amenities, activities and check-in rates.`
  return {
    title: g.name,
    description: desc,
    alternates: { canonical: `/gyms/${params.id}` },
    openGraph: {
      title: g.name,
      description: desc,
      type: 'website',
      url: `/gyms/${params.id}`,
      images: g.photos?.[0] ? [{ url: g.photos[0] }] : undefined,
    },
  }
}

export default async function GymDetail({ params }: { params: { id: string } }) {
  const g = await getGym(params.id) as (Gym & { amenities?: string[]; activities?: string[]; description?: string; contact_phone?: string }) | null
  if (!g) notFound()

  const gymLd = {
    '@context': 'https://schema.org',
    '@type': 'ExerciseGym',
    name: g.name,
    url: `${SITE}/gyms/${g.id}`,
    image: g.photos?.[0] || undefined,
    description: g.description || undefined,
    telephone: g.contact_phone || undefined,
    address: g.city ? { '@type': 'PostalAddress', addressLocality: g.city } : undefined,
    amenityFeature: g.amenities?.length ? g.amenities.map((a) => ({ '@type': 'LocationFeatureSpecification', name: a })) : undefined,
  }

  return (
    <div className="container-x py-6">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: ldJson(gymLd) }} />
      <nav className="mb-4 text-xs text-muted"><Link href="/gyms">Gyms</Link> / <span className="text-ink">{g.name}</span></nav>
      <div className="card flex aspect-[21/9] items-center justify-center overflow-hidden bg-soft">
        {g.photos?.[0] ? /* eslint-disable-next-line @next/next/no-img-element */ <img src={g.photos[0]} alt={g.name} className="h-full w-full object-cover" /> : <span className="text-3xl font-bold text-hair">{g.name}</span>}
      </div>
      <div className="mt-5 grid gap-6 md:grid-cols-[1fr_320px]">
        <div>
          <h1 className="h-section">{g.name}</h1>
          <div className="text-sm text-muted">{g.city} · {g.facility_type} · {g.gender_access}</div>
          {g.description && <p className="mt-4 text-sm leading-relaxed text-muted">{g.description}</p>}
          {!!g.amenities?.length && (
            <div className="mt-5"><h2 className="mb-2 font-bold">Amenities</h2><div className="flex flex-wrap gap-2">{g.amenities.map((a) => <span key={a} className="tag bg-soft text-muted">{a}</span>)}</div></div>
          )}
          {!!g.activities?.length && (
            <div className="mt-5"><h2 className="mb-2 font-bold">Activities</h2><div className="flex flex-wrap gap-2">{g.activities.map((a) => <span key={a} className="tag bg-soft text-muted">{a}</span>)}</div></div>
          )}
        </div>
        <aside className="card h-fit p-5">
          {g.checkin_rate != null && <div className="text-2xl font-extrabold text-brand-strong">{money(g.checkin_rate)}<span className="text-sm font-normal text-muted"> / check-in</span></div>}
          {g.contact_phone && <div className="mt-2 text-sm text-muted">Call: {g.contact_phone}</div>}
          <Link href="/plans" className="btn btn-primary mt-4 w-full">Get membership</Link>
          <p className="mt-3 text-[12px] text-muted">Check-in booking and QR access are available in the Fitorza app.</p>
        </aside>
      </div>
    </div>
  )
}
