import { notFound } from 'next/navigation'
import { Suspense } from 'react'
import { Navbar } from '@/components/navbar'
import { getMovieById, getEpisodes, getMoviesByCategory } from '@/lib/data'
import { MovieDetailClient } from './movie-detail-client'
import { MovieSection } from '@/components/movie-section'

interface MoviePageProps {
  params: Promise<{ id: string }>
}

export async function generateMetadata({ params }: MoviePageProps) {
  const { id } = await params
  const movie = await getMovieById(id)
  
  if (!movie) {
    return {
      title: 'Movie Not Found - WatchFlix',
    }
  }

  return {
    title: `${movie.title} - WatchFlix`,
    description: movie.description || `Watch ${movie.title} on WatchFlix`,
  }
}

export default async function MoviePage({ params }: MoviePageProps) {
  const { id } = await params
  const [movie, episodes] = await Promise.all([
    getMovieById(id),
    getEpisodes(id),
  ])

  if (!movie) {
    notFound()
  }

  return (
    <main className="min-h-screen bg-[#0b0b0b]">
      <Navbar />
      
      <div className="pt-20 md:pt-24">
        <MovieDetailClient movie={movie} episodes={episodes} />
      </div>

      {/* Related Movies */}
      <div className="py-8">
        <Suspense fallback={<RelatedSkeleton />}>
          <RelatedMovies category={movie.category} currentId={movie.id} />
        </Suspense>
      </div>

      {/* Footer */}
      <footer className="py-12 px-4 sm:px-6 lg:px-8 max-w-[1800px] mx-auto">
        <div className="text-center text-gray-500 text-sm">
          <p className="font-[family-name:var(--font-poppins)] text-xl font-bold text-[#e50914] mb-2">
            WATCHFLIX
          </p>
          <p>&copy; {new Date().getFullYear()} WatchFlix. All rights reserved.</p>
        </div>
      </footer>
    </main>
  )
}

async function RelatedMovies({ category, currentId }: { category: string; currentId: string }) {
  const movies = await getMoviesByCategory(category)
  const relatedMovies = movies.filter((m) => m.id !== currentId).slice(0, 10)
  
  if (relatedMovies.length === 0) return null
  
  return <MovieSection title="More Like This" movies={relatedMovies} />
}

function RelatedSkeleton() {
  return (
    <section className="py-6 md:py-8">
      <div className="px-4 sm:px-6 lg:px-8 max-w-[1800px] mx-auto">
        <h2 className="text-xl md:text-2xl font-bold font-[family-name:var(--font-poppins)] text-white mb-4">
          More Like This
        </h2>
        <div className="flex gap-4 overflow-hidden">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="flex-shrink-0 w-[160px] md:w-[200px]">
              <div className="rounded-xl overflow-hidden bg-[#141414]">
                <div className="aspect-[2/3] skeleton" />
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  )
}
