import { notFound, redirect } from 'next/navigation'
import { getSession } from '@/lib/auth'
import { getAccessibleProduct } from '@/lib/product-access'
import { prisma } from '@/lib/prisma'
import { SoloBoard } from '@/components/solo/solo-board'
import { NoActiveSprint } from '@/components/solo/no-active-sprint'
import type { SoloTask } from '@/components/solo/solo-board'
import type { UnassignedStory } from '@/components/solo/unassigned-stories-sheet'

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 sprint = await prisma.sprint.findFirst({
    where: { product_id: id, status: 'ACTIVE' },
  })

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

  const [rawTasks, rawUnassigned] = await Promise.all([
    prisma.task.findMany({
      where: {
        story: {
          sprint_id: sprint.id,
          assignee_id: session.userId,
        },
      },
      include: {
        story: {
          select: {
            id: true,
            code: true,
            title: true,
            tasks: { select: { id: true }, orderBy: { sort_order: 'asc' } },
          },
        },
      },
      orderBy: [
        { story: { pbi: { priority: 'asc' } } },
        { story: { pbi: { sort_order: 'asc' } } },
        { story: { sort_order: 'asc' } },
        { priority: 'asc' },
        { sort_order: 'asc' },
      ],
    }),
    prisma.story.findMany({
      where: { sprint_id: sprint.id, assignee_id: null },
      select: {
        id: true,
        code: true,
        title: true,
        tasks: {
          select: { id: true, title: true, description: true, priority: true, status: true },
          orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }],
        },
      },
      orderBy: { sort_order: 'asc' },
    }),
  ])

  const tasks: SoloTask[] = rawTasks.map(t => {
    const positionInStory = t.story.tasks.findIndex(st => st.id === t.id)
    const taskCode =
      t.story.code && positionInStory >= 0 ? `${t.story.code}.${positionInStory + 1}` : null
    return {
      id: t.id,
      title: t.title,
      description: t.description,
      implementation_plan: t.implementation_plan,
      priority: t.priority,
      sort_order: t.sort_order,
      status: t.status as SoloTask['status'],
      verify_only: t.verify_only,
      verify_required: t.verify_required as SoloTask['verify_required'],
      story_id: t.story.id,
      story_code: t.story.code,
      story_title: t.story.title,
      task_code: taskCode,
    }
  })

  const unassignedStories: UnassignedStory[] = rawUnassigned.map(s => ({
    id: s.id,
    code: s.code,
    title: s.title,
    tasks: s.tasks.map(t => ({
      id: t.id,
      title: t.title,
      description: t.description,
      priority: t.priority,
      status: t.status,
    })),
  }))

  return (
    <SoloBoard
      productId={id}
      sprintGoal={sprint.sprint_goal}
      tasks={tasks}
      unassignedStories={unassignedStories}
      isDemo={session.isDemo ?? false}
      currentUserId={session.userId}
      repoUrl={product.repo_url}
    />
  )
}
