import { notFound, redirect } from 'next/navigation'
import { getSession } from '@/lib/auth'
import { getAccessibleProduct } from '@/lib/product-access'
import { getSprintSwitcherData } from '@/lib/sprint-switcher-data'
import { getSoloWorkspaceSnapshot } from '@/lib/solo-workspace-server'
import { SoloBoard } from '@/components/solo/solo-board'
import { SoloHydrationWrapper } from '@/components/solo/solo-hydration-wrapper'
import { NoActiveSprint } from '@/components/solo/no-active-sprint'
import { SprintSwitcher } from '@/components/shared/sprint-switcher'

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

export default async function SoloProductPage({ params }: Props) {
  const { id } = await params
  const session = await getSession()
  if (!session.userId) redirect('/login')

  const product = await getAccessibleProduct(id, session.userId)
  if (!product) notFound()

  const initialData = await getSoloWorkspaceSnapshot(id, session.userId)
  const switcherData = await getSprintSwitcherData(id, {
    activeSprintId: initialData?.sprint.id ?? null,
  })

  const switcherBar = (
    <div className="px-4 py-3 border-b border-border bg-surface-container-low shrink-0 flex items-center justify-center">
      <SprintSwitcher
        productId={id}
        sprints={switcherData.sprintItems}
        activeSprint={switcherData.activeSprintItem}
        buildingSprintIds={switcherData.buildingSprintIds}
      />
    </div>
  )

  if (!initialData) {
    return (
      <div className="flex flex-col h-full">
        {switcherBar}
        <NoActiveSprint productId={id} productName={product.name} />
      </div>
    )
  }

  return (
    <div className="flex flex-col h-full">
      {switcherBar}
      <div className="flex-1 min-h-0">
        <SoloHydrationWrapper initialData={initialData}>
          <SoloBoard
            key={initialData.sprint.id}
            productId={id}
            sprintGoal={initialData.sprint.sprint_goal}
            isDemo={session.isDemo ?? false}
            repoUrl={product.repo_url}
          />
        </SoloHydrationWrapper>
      </div>
    </div>
  )
}
