'use client'

import { useRouter } from 'next/navigation'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { PanelNavBar } from '@/components/shared/panel-nav-bar'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { useShallow } from 'zustand/react/shallow'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { selectTasksForActiveStory } from '@/stores/product-workspace/selectors'
import type {
  BacklogTask,
  TaskDetail,
} from '@/stores/product-workspace/types'
import { BacklogCard } from './backlog-card'
import { debugProps } from '@/lib/debug'
import { EmptyPanel } from './empty-panel'
import { cn } from '@/lib/utils'

const STATUS_COLORS: Record<string, string> = {
  TO_DO: 'bg-status-todo/15 text-status-todo border-status-todo/30',
  IN_PROGRESS: 'bg-status-in-progress/15 text-status-in-progress border-status-in-progress/30',
  REVIEW: 'bg-status-review/15 text-status-review border-status-review/30',
  DONE: 'bg-status-done/15 text-status-done border-status-done/30',
}
const STATUS_LABELS: Record<string, string> = {
  TO_DO: 'To Do',
  IN_PROGRESS: 'Bezig',
  REVIEW: 'Review',
  DONE: 'Klaar',
}

function TaskCard({
  task,
  onClick,
}: {
  task: BacklogTask | TaskDetail
  onClick: () => void
}) {
  return (
    <BacklogCard
      title={task.title}
      priority={task.priority}
      onClick={onClick}
      badge={
        <Badge
          className={cn(
            'text-[10px] px-1.5 py-0 border',
            STATUS_COLORS[task.status] ?? STATUS_COLORS.TO_DO,
          )}
        >
          {STATUS_LABELS[task.status] ?? task.status}
        </Badge>
      }
    />
  )
}

interface TaskPanelProps {
  productId: string
  isDemo: boolean
  closePath: string
}

// PBI-74 / T-851: leest tasks voor active story via selectTasksForActiveStory.
export function TaskPanel({ isDemo, closePath }: TaskPanelProps) {
  const router = useRouter()
  const selectedStoryId = useProductWorkspaceStore((s) => s.context.activeStoryId)
  const rawTasks = useProductWorkspaceStore(useShallow(selectTasksForActiveStory)) as
    | (BacklogTask | TaskDetail)[]

  const tasks: (BacklogTask | TaskDetail)[] | null = selectedStoryId
    ? rawTasks
    : null

  const navActions = (
    <DemoTooltip show={isDemo}>
      <Button
        size="sm"
        className="h-7 text-xs"
        disabled={isDemo || !selectedStoryId}
        onClick={() => {
          if (!selectedStoryId) return
          router.push(`${closePath}?newTask=1&storyId=${selectedStoryId}`)
        }}
        {...debugProps('task-panel__actions')}
      >
        + Nieuwe taak
      </Button>
    </DemoTooltip>
  )

  const dp = debugProps('task-panel', 'TaskPanel', 'components/backlog/task-panel.tsx')

  if (tasks === null) {
    return (
      <div className="flex flex-col h-full" {...dp}>
        <PanelNavBar title="Taken" actions={navActions} />
        <EmptyPanel message="Selecteer een story om de taken te bekijken." />
      </div>
    )
  }

  if (tasks.length === 0) {
    return (
      <div className="flex flex-col h-full" {...dp}>
        <PanelNavBar title="Taken" actions={navActions} />
        <EmptyPanel
          message="Nog geen taken voor deze story."
          action={{
            label: 'Nieuwe taak',
            onClick: () => router.push(`${closePath}?newTask=1&storyId=${selectedStoryId}`),
            disabled: isDemo,
          }}
        />
      </div>
    )
  }

  return (
    <div className="flex flex-col h-full" {...dp}>
      <PanelNavBar title="Taken" actions={navActions} />
      <div className="flex-1 overflow-y-auto p-3">
        <div className="grid grid-cols-2 gap-2">
          {tasks.map((task) => (
            <TaskCard
              key={task.id}
              task={task}
              onClick={() => router.push(`${closePath}?editTask=${task.id}`)}
            />
          ))}
        </div>
      </div>
    </div>
  )
}
