'use client'

import { useState, useTransition } from 'react'
import { toast } from 'sonner'
import {
  startSprintRunAction,
  resumeSprintAction,
  resumePausedSprintRunAction,
  cancelSprintRunAction,
  type PreFlightBlocker,
} from '@/actions/sprint-runs'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { type PauseContext, pauseReasonLabel } from '@/lib/pause-context'

type SprintStatusValue = 'OPEN' | 'CLOSED' | 'ARCHIVED' | 'FAILED'
type SprintRunStatusValue =
  | 'QUEUED'
  | 'RUNNING'
  | 'PAUSED'
  | 'DONE'
  | 'FAILED'
  | 'CANCELLED'
  | null

interface Props {
  sprintId: string
  productId: string
  sprintStatus: SprintStatusValue
  activeSprintRunId: string | null
  activeSprintRunStatus: SprintRunStatusValue
  pauseContext: PauseContext | null
  isDemo: boolean
}

const BLOCKER_LABELS: Record<PreFlightBlocker['type'], string> = {
  task_no_plan: 'Task zonder implementation plan',
  open_question: 'Openstaande vraag aan jou',
  pbi_blocked: 'PBI is geblokkeerd of gefaald',
  task_cross_repo: 'Task met afwijkende repo (niet toegestaan in SPRINT_BATCH)',
}

function blockerHref(productId: string, blocker: PreFlightBlocker): string {
  switch (blocker.type) {
    case 'task_no_plan':
      return `/products/${productId}/sprint?editTask=${blocker.id}`
    case 'open_question':
      return `/products/${productId}/sprint`
    case 'pbi_blocked':
      return `/products/${productId}`
    case 'task_cross_repo':
      return `/products/${productId}/sprint?editTask=${blocker.id}`
  }
}

export function SprintRunControls({
  sprintId,
  productId,
  sprintStatus,
  activeSprintRunId,
  activeSprintRunStatus,
  pauseContext,
  isDemo,
}: Props) {
  const [pending, startTransition] = useTransition()
  const [blockers, setBlockers] = useState<PreFlightBlocker[] | null>(null)

  const hasActiveRun =
    activeSprintRunId !== null &&
    (activeSprintRunStatus === 'QUEUED' ||
      activeSprintRunStatus === 'RUNNING' ||
      activeSprintRunStatus === 'PAUSED')

  const canStart = sprintStatus === 'OPEN' && !hasActiveRun
  const canResume = sprintStatus === 'FAILED'
  const canResumePaused =
    activeSprintRunStatus === 'PAUSED' && pauseContext !== null
  const canCancel = hasActiveRun

  function handleStart() {
    startTransition(async () => {
      const result = await startSprintRunAction({ sprint_id: sprintId })
      if (result.ok) {
        toast.success(`Sprint gestart (${result.jobs_count} taak(s) klaar)`)
      } else if (result.error === 'PRE_FLIGHT_BLOCKED' && 'blockers' in result) {
        setBlockers(result.blockers)
      } else {
        toast.error(result.error)
      }
    })
  }

  function handleResume() {
    startTransition(async () => {
      const result = await resumeSprintAction({ sprint_id: sprintId })
      if (result.ok) {
        toast.success(`Sprint hervat (${result.jobs_count} taak(s) klaar)`)
      } else if (result.error === 'PRE_FLIGHT_BLOCKED' && 'blockers' in result) {
        setBlockers(result.blockers)
      } else {
        toast.error(result.error)
      }
    })
  }

  function handleResumePaused() {
    if (!activeSprintRunId || !pauseContext) return
    if (
      !confirm(
        `Sprint hervatten? Bevestig dat het ${pauseReasonLabel(
          pauseContext.pause_reason,
        ).toLowerCase()} is opgelost.`,
      )
    )
      return
    startTransition(async () => {
      const result = await resumePausedSprintRunAction({
        sprint_run_id: activeSprintRunId,
      })
      if (result.ok) toast.success('Sprint hervat')
      else toast.error(result.error)
    })
  }

  function handleCancel() {
    if (!activeSprintRunId) return
    if (!confirm('Sprint annuleren? Openstaande taken blijven TO_DO.')) return
    startTransition(async () => {
      const result = await cancelSprintRunAction({ sprint_run_id: activeSprintRunId })
      if (result.ok) toast.success('Sprint geannuleerd')
      else toast.error(result.error)
    })
  }

  return (
    <>
      {canResumePaused && pauseContext && (
        <div className="rounded-md border border-warning/40 bg-warning-container/20 p-3 mb-2">
          <div className="text-xs uppercase tracking-wide text-on-warning-container">
            Gepauzeerd: {pauseReasonLabel(pauseContext.pause_reason)}
          </div>
          <a
            href={pauseContext.pr_url}
            target="_blank"
            rel="noreferrer"
            className="text-sm text-primary hover:underline break-all"
          >
            {pauseContext.pr_url}
          </a>
          {pauseContext.conflict_files.length > 0 && (
            <ul className="mt-1 text-xs text-muted-foreground">
              {pauseContext.conflict_files.slice(0, 5).map((f) => (
                <li key={f}>· {f}</li>
              ))}
              {pauseContext.conflict_files.length > 5 && (
                <li>· + {pauseContext.conflict_files.length - 5} meer</li>
              )}
            </ul>
          )}
          <Button
            size="sm"
            onClick={handleResumePaused}
            disabled={pending || isDemo}
            className="text-xs mt-2"
          >
            Hervat gepauzeerde sprint
          </Button>
        </div>
      )}
      <div className="flex items-center gap-2" data-debug-id="sprint-run-controls">
        {canStart && (
          <Button
            size="sm"
            onClick={handleStart}
            disabled={pending || isDemo}
            className="text-xs"
            data-debug-id="sprint-run-controls__start"
          >
            Start Sprint
          </Button>
        )}
        {canResume && (
          <Button
            size="sm"
            onClick={handleResume}
            disabled={pending || isDemo}
            variant="default"
            className="text-xs"
            data-debug-id="sprint-run-controls__start"
          >
            Hervat sprint
          </Button>
        )}
        {canCancel && (
          <Button
            size="sm"
            onClick={handleCancel}
            disabled={pending || isDemo}
            variant="outline"
            className="text-xs"
            data-debug-id="sprint-run-controls__cancel"
          >
            Annuleer sprint-run
          </Button>
        )}
      </div>

      <Dialog open={blockers !== null} onOpenChange={(open) => { if (!open) setBlockers(null) }}>
        <DialogContent className="max-w-lg" data-debug-id="sprint-run-controls__blockers-dialog">
          <DialogHeader>
            <DialogTitle>Sprint kan nog niet starten</DialogTitle>
            <DialogDescription>
              Los eerst onderstaande punten op. Klik op een item om er direct naar
              te navigeren.
            </DialogDescription>
          </DialogHeader>

          <ul className="flex flex-col gap-2 max-h-80 overflow-y-auto">
            {blockers?.map((b, i) => (
              <li
                key={`${b.type}-${b.id}-${i}`}
                className="rounded-md border border-border bg-surface-container-low px-3 py-2"
              >
                <div className="text-xs uppercase tracking-wide text-muted-foreground">
                  {BLOCKER_LABELS[b.type]}
                </div>
                <a
                  href={blockerHref(productId, b)}
                  className="text-sm text-primary hover:underline break-words"
                >
                  {b.label}
                </a>
              </li>
            ))}
          </ul>

          <DialogFooter>
            <Button variant="outline" onClick={() => setBlockers(null)}>
              Sluit
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
