'use client'

import { useTransition } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { Pencil } from 'lucide-react'
import { useShallow } from 'zustand/react/shallow'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { CodeBadge } from '@/components/shared/code-badge'
import { PanelNavBar } from '@/components/shared/panel-nav-bar'
import { PRIORITY_BORDER } from '@/components/backlog/backlog-card'
import { useSprintWorkspaceStore } from '@/stores/sprint-workspace/store'
import { selectTasksForActiveStory } from '@/stores/sprint-workspace/selectors'
import type {
  SprintWorkspaceTask,
  SprintWorkspaceTaskDetail,
} from '@/stores/sprint-workspace/types'
import { updateTaskStatusAction } from '@/actions/tasks'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { debugProps } from '@/lib/debug'
import { cn } from '@/lib/utils'

const STATUS_CYCLE: Record<string, 'TO_DO' | 'IN_PROGRESS' | 'DONE'> = {
  TO_DO: 'IN_PROGRESS',
  IN_PROGRESS: 'DONE',
  DONE: 'TO_DO',
  EXCLUDED: 'TO_DO',
}
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',
  DONE: 'bg-status-done/15 text-status-done border-status-done/30',
  EXCLUDED: 'bg-surface-container-low text-muted-foreground border-border',
  FAILED: 'bg-status-failed/15 text-status-failed border-status-failed/30',
  REVIEW: 'bg-status-review/15 text-status-review border-status-review/30',
}
const STATUS_LABELS: Record<string, string> = {
  TO_DO: 'To Do',
  IN_PROGRESS: 'Bezig',
  REVIEW: 'Review',
  DONE: 'Klaar',
  FAILED: 'Mislukt',
  EXCLUDED: 'Uitgesloten',
}

// Behouden voor type-compat met SprintBoardClient props (verdwijnt zodra
// SprintBoardClient ook geen tasks-prop meer doorgeeft — T-883).
export interface Task {
  id: string
  code: string | null
  title: string
  description: string | null
  priority: number
  status: string
  story_id: string
  sprint_id: string | null
}

type WorkspaceTask = SprintWorkspaceTask | SprintWorkspaceTaskDetail

interface TaskListProps {
  sprintId: string
  productId: string
  isDemo: boolean
}

function TaskRow({
  task, code, isDemo, onStatusToggle, onEdit,
}: {
  task: WorkspaceTask
  code: string | null
  isDemo: boolean
  onStatusToggle: () => void
  onEdit: () => void
}) {
  return (
    <div className="group px-2 py-1">
      <div
        className={cn(
          'flex items-start gap-2 rounded border border-border px-3 py-2 transition-colors bg-surface-container hover:bg-surface-container-high cursor-pointer',
          PRIORITY_BORDER[task.priority],
        )}
        onClick={() => onEdit()}
        role="button"
        tabIndex={0}
        aria-label={`Bewerk taak: ${task.title}`}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault()
            onEdit()
          }
        }}
      >
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2">
            <p className={cn(
              'text-sm leading-snug line-clamp-2 flex-1',
              task.status === 'DONE' && 'line-through text-muted-foreground',
              task.status === 'EXCLUDED' && 'text-muted-foreground/70 italic',
            )}>
              {task.title}
            </p>
            {code && <CodeBadge code={code} className="shrink-0 mt-0.5" />}
          </div>
          <div className="mt-1.5">
            <button
              onClick={(e) => { e.stopPropagation(); onStatusToggle() }}
              disabled={isDemo}
              aria-label={`Status: ${STATUS_LABELS[task.status]}`}
            >
              <Badge className={cn(
                'text-[10px] px-1.5 py-0 border cursor-pointer hover:opacity-80 transition-opacity',
                STATUS_COLORS[task.status],
              )}>
                {STATUS_LABELS[task.status]}
              </Badge>
            </button>
          </div>
        </div>
        <DemoTooltip show={isDemo}>
          <button
            onClick={(e) => { e.stopPropagation(); if (!isDemo) onEdit() }}
            className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground p-0.5 rounded shrink-0 mt-0.5 disabled:opacity-40 disabled:cursor-not-allowed"
            aria-label="Bewerk taak"
            disabled={isDemo}
          >
            <Pencil size={14} />
          </button>
        </DemoTooltip>
      </div>
    </div>
  )
}

export function TaskList({ sprintId: _sprintId, productId: _productId, isDemo }: TaskListProps) {
  const storyId = useSprintWorkspaceStore((s) => s.context.activeStoryId)
  const orderedTasks = useSprintWorkspaceStore(
    useShallow(selectTasksForActiveStory),
  )
  const [, startTransition] = useTransition()
  const router = useRouter()
  const pathname = usePathname()

  const doneCount = orderedTasks.filter(t => t.status === 'DONE').length

  function handleStatusToggle(task: WorkspaceTask) {
    startTransition(async () => {
      await updateTaskStatusAction(task.id, STATUS_CYCLE[task.status] ?? 'TO_DO')
    })
  }

  function openCreateDialog() {
    if (!storyId) return
    router.push(`${pathname}?newTask=1&storyId=${storyId}`)
  }

  function openEditDialog(taskId: string) {
    useSprintWorkspaceStore.getState().setActiveTask(taskId)
  }

  return (
    <div className="flex flex-col h-full" {...debugProps('task-list', 'TaskList', 'components/sprint/task-list.tsx')}>
      <PanelNavBar
        title="Taken"
        actions={
          <>
            <span className="text-xs text-muted-foreground">{doneCount}/{orderedTasks.length} klaar</span>
            <DemoTooltip show={isDemo}>
              <Button
                size="sm"
                className="h-7 text-xs"
                disabled={isDemo}
                onClick={() => !isDemo && openCreateDialog()}
              >
                + Taak
              </Button>
            </DemoTooltip>
          </>
        }
      />

      <div className="flex-1 overflow-y-auto" data-debug-id="task-list__items">
        {orderedTasks.length === 0 ? (
          <div className="text-center mt-8 space-y-3" data-debug-id="task-list__empty">
            <p className="text-sm text-muted-foreground">Geen taken voor deze story.</p>
            <DemoTooltip show={isDemo}>
              <Button
                size="sm"
                variant="outline"
                disabled={isDemo}
                onClick={() => !isDemo && openCreateDialog()}
              >
                Maak eerste taak aan
              </Button>
            </DemoTooltip>
          </div>
        ) : (
          <>
            {orderedTasks.map((task) => (
              <TaskRow
                key={task.id}
                task={task}
                code={task.code}
                isDemo={isDemo}
                onStatusToggle={() => handleStatusToggle(task)}
                onEdit={() => openEditDialog(task.id)}
              />
            ))}
          </>
        )}
      </div>
    </div>
  )
}
