import { notFound, redirect } from 'next/navigation'
import { getSession } from '@/lib/auth'
import { getAccessibleProduct } from '@/lib/product-access'
import { prisma } from '@/lib/prisma'
import { SplitPane } from '@/components/split-pane/split-pane'
import { PbiList } from '@/components/backlog/pbi-list'
import { StoryPanel } from '@/components/backlog/story-panel'
import type { Story } from '@/components/backlog/story-panel'
import { StartSprintButton } from '@/components/sprint/start-sprint-button'
import { ActivateProductButton } from '@/components/shared/activate-product-button'
import Link from 'next/link'

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

export default async function ProductBacklogPage({ 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 [activeSprint, user] = await Promise.all([
    prisma.sprint.findFirst({ where: { product_id: id, status: 'ACTIVE' } }),
    prisma.user.findUnique({ where: { id: session.userId! }, select: { active_product_id: true } }),
  ])

  const pbis = await prisma.pbi.findMany({
    where: { product_id: id },
    orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }],
  })

  const stories = await prisma.story.findMany({
    where: { product_id: id },
    orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }],
    select: {
      id: true,
      code: true,
      title: true,
      description: true,
      acceptance_criteria: true,
      priority: true,
      status: true,
      pbi_id: true,
      created_at: true,
    },
  })

  // Group stories by PBI id
  const storiesByPbi: Record<string, Story[]> = {}
  for (const story of stories) {
    if (!storiesByPbi[story.pbi_id]) storiesByPbi[story.pbi_id] = []
    storiesByPbi[story.pbi_id].push(story)
  }

  const isDemo = session.isDemo ?? false

  return (
    <div className="flex flex-col h-full">
      {/* Product header */}
      <div className="px-4 py-3 border-b border-border bg-surface-container-low shrink-0 flex items-center justify-between">
        <div>
          <h1 className="font-medium text-foreground">{product.name}</h1>
          {product.description && (
            <p className="text-xs text-muted-foreground mt-0.5">{product.description}</p>
          )}
        </div>
        <div className="flex items-center gap-3">
          {user?.active_product_id !== id && (
            <ActivateProductButton productId={id} isDemo={isDemo} redirectTo={`/products/${id}`} />
          )}
          {activeSprint ? (
            <Link href={`/products/${id}/sprint`} className="text-xs text-primary hover:underline font-medium">
              Sprint actief →
            </Link>
          ) : (
            !isDemo && <StartSprintButton productId={id} />
          )}
          <Link
            href={`/products/${id}/settings`}
            className="text-xs text-muted-foreground hover:text-foreground"
          >
            Instellingen
          </Link>
        </div>
      </div>

      {/* Split pane */}
      <div className="flex-1 overflow-hidden">
        <SplitPane
          storageKey={`backlog-${id}`}
          left={
            <PbiList
              productId={id}
              pbis={pbis.map((p: (typeof pbis)[number]) => ({ id: p.id, code: p.code, title: p.title, priority: p.priority, description: p.description, created_at: p.created_at }))}
              isDemo={isDemo}
            />
          }
          right={
            <StoryPanel
              productId={id}
              storiesByPbi={storiesByPbi}
              isDemo={isDemo}
            />
          }
        />
      </div>
    </div>
  )
}
