'use client'

import { useSprintWorkspaceStore } from '@/stores/sprint-workspace/store'
import { selectActiveTask } from '@/stores/sprint-workspace/selectors'
import { isDetail } from '@/stores/sprint-workspace/types'
import { TaskDialog } from '@/app/_components/tasks/task-dialog'
import { taskStatusFromApi } from '@/lib/task-status'
import type { TaskStatus } from '@prisma/client'

interface Props {
  productId: string
  isDemo: boolean
}

export function SprintTaskDialogMount({ productId, isDemo }: Props) {
  const task = useSprintWorkspaceStore(selectActiveTask)
  const setActiveTask = useSprintWorkspaceStore((s) => s.setActiveTask)

  if (!task || !isDetail(task)) return null

  const status = (taskStatusFromApi(String(task.status)) ?? 'TO_DO') as TaskStatus
  const createdAt = task.created_at instanceof Date ? task.created_at : new Date(task.created_at)

  return (
    <TaskDialog
      task={{
        id: task.id,
        code: task.code,
        title: task.title,
        description: task.description,
        implementation_plan: task.implementation_plan ?? null,
        priority: task.priority,
        status,
        created_at: createdAt,
      }}
      productId={productId}
      onClose={() => setActiveTask(null)}
      isDemo={isDemo}
    />
  )
}
