import { getLibrary } from '@/lib/libraries'
import { notFound, redirect } from 'next/navigation'
import { getServerSession } from '@/lib/auth'
import { getLibraryAccessLevel } from '@/lib/users'
import ComicsView from '@/components/comics/ComicsView'
import GamesView from '@/components/games/GamesView'
import MixedView from '@/components/mixed/MixedView'
import MoviesView from '@/components/movies/MoviesView'
import TvView from '@/components/tv/TvView'
import ScanLibraryButton from '@/components/ScanLibraryButton'

interface Props {
  params: Promise<{ id: string }>
  searchParams: Promise<{ path?: string }>
}

export default async function LibraryPage({ params, searchParams }: Props) {
  const { id } = await params
  const { path: subpath } = await searchParams

  const session = await getServerSession()
  if (!session.userId) redirect('/login')

  const library = getLibrary(id)
  if (!library) notFound()

  let readOnly = false
  if (session.role !== 'admin') {
    const accessLevel = getLibraryAccessLevel(session.userId, id)
    if (!accessLevel) notFound()
    readOnly = accessLevel === 'read'
  }

  return (
    <div>
      {library.type !== 'mixed' && (
        <div className="flex items-center gap-2 mb-6">
          <a href="/" className="text-sm transition-colors" style={{ color: 'var(--text-secondary)' }}>
            Libraries
          </a>
          <span style={{ color: 'var(--text-secondary)' }}>/</span>
          <span className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>
            {library.name}
          </span>
          {session.role === 'admin' && (
            <div className="ml-auto">
              <ScanLibraryButton libraryId={id} />
            </div>
          )}
        </div>
      )}
      {library.type === 'mixed' && session.role === 'admin' && (
        <div className="flex justify-end mb-2">
          <ScanLibraryButton libraryId={id} />
        </div>
      )}

      {library.type === 'comics' && <ComicsView libraryId={id} readOnly={readOnly} />}
      {library.type === 'games' && <GamesView libraryId={id} readOnly={readOnly} />}
      {library.type === 'mixed' && <MixedView libraryId={id} libraryName={library.name} initialPath={subpath ?? ''} readOnly={readOnly} />}
      {library.type === 'movies' && <MoviesView libraryId={id} readOnly={readOnly} />}
      {library.type === 'tv' && <TvView libraryId={id} readOnly={readOnly} />}
    </div>
  )
}
