'use client'

import { useRef, useState, useTransition } from 'react'
import Link from 'next/link'
import { toast } from 'sonner'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { useSoloStore } from '@/stores/solo-store'
import { enqueueClaudeJobAction, cancelClaudeJobAction } from '@/actions/claude-jobs'
import { cn } from '@/lib/utils'
import type { SoloTask } from './solo-board'

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-in-progress/15 text-status-in-progress border-status-in-progress/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',
}

interface TaskDetailDialogProps {
  task: SoloTask | null
  productId: string
  isDemo: boolean
  onClose: () => void
}

interface TaskDetailContentProps {
  task: SoloTask
  productId: string
  isDemo: boolean
  onClose: () => void
}

type SaveState = 'idle' | 'saving' | 'saved'

function TaskDetailContent({ task, productId, isDemo, onClose }: TaskDetailContentProps) {
  const { updatePlan } = useSoloStore()
  const job = useSoloStore(s => s.claudeJobsByTaskId[task.id])
  const connectedWorkers = useSoloStore(s => s.connectedWorkers)
  const [localPlan, setLocalPlan] = useState(task.implementation_plan ?? '')
  const [saveState, setSaveState] = useState<SaveState>('idle')
  const [, startTransition] = useTransition()
  const [jobPending, startJobTransition] = useTransition()
  const fadeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
  const savedPlanRef = useRef(task.implementation_plan ?? '')

  function handleEnqueue() {
    startJobTransition(async () => {
      const result = await enqueueClaudeJobAction(task.id)
      if ('error' in result) {
        toast.error(result.error)
      } else {
        toast.success('Agent ingeschakeld')
      }
    })
  }

  function handleCancel() {
    if (!job) return
    startJobTransition(async () => {
      const result = await cancelClaudeJobAction(job.job_id)
      if ('error' in result) toast.error(result.error)
    })
  }

  function handleBlur() {
    if (isDemo || localPlan === savedPlanRef.current) return

    setSaveState('saving')
    if (fadeTimer.current) clearTimeout(fadeTimer.current)

    // fetch naar Route Handler i.p.v. Server Action — Server Actions
    // kappen anders de open SSE-stream van het Solo Paneel af. Zie
    // notitie in solo-board.tsx handleDragEnd.
    startTransition(async () => {
      try {
        const res = await fetch(`/api/tasks/${task.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({ implementation_plan: localPlan }),
        })
        if (!res.ok) {
          setSaveState('idle')
          toast.error('Implementatieplan opslaan mislukt')
          return
        }
        savedPlanRef.current = localPlan
        updatePlan(task.id, localPlan || null)
        setSaveState('saved')
        fadeTimer.current = setTimeout(() => setSaveState('idle'), 2000)
      } catch {
        setSaveState('idle')
        toast.error('Implementatieplan opslaan mislukt')
      }
    })
  }

  return (
    <>
      <DialogHeader>
        <div className="flex items-start gap-3 pr-8">
          <DialogTitle className="text-sm font-medium leading-snug flex-1">
            {task.title}
          </DialogTitle>
          {task.task_code && (
            <span className="font-mono text-[11px] text-muted-foreground border border-border rounded-md bg-surface-container px-1.5 py-0.5 shrink-0">
              {task.task_code}
            </span>
          )}
          <Badge className={cn('text-xs border shrink-0', STATUS_COLORS[task.status])}>
            {STATUS_LABELS[task.status]}
          </Badge>
        </div>
        <p className="text-xs text-muted-foreground">
          {task.story_code && <span className="font-mono mr-1">{task.story_code}</span>}
          {task.story_title}
        </p>
      </DialogHeader>

      {task.description && (
        <div>
          <p className="text-xs font-medium text-muted-foreground mb-1.5">Beschrijving</p>
          <p className="text-sm text-foreground whitespace-pre-wrap">{task.description}</p>
        </div>
      )}

      <div>
        <p className="text-xs font-medium text-muted-foreground mb-1.5">Implementatieplan</p>
        <DemoTooltip show={isDemo}>
          <Textarea
            value={localPlan}
            onChange={(e) => setLocalPlan(e.target.value)}
            onBlur={handleBlur}
            placeholder="Voeg een implementatieplan toe…"
            className="resize-none text-sm min-h-[120px]"
            readOnly={isDemo}
          />
        </DemoTooltip>
        <div className="flex justify-end mt-1 h-4">
          {saveState === 'saving' && (
            <span className="text-xs text-muted-foreground">Bezig met opslaan…</span>
          )}
          {saveState === 'saved' && (
            <span className="text-xs text-status-done">Opgeslagen</span>
          )}
        </div>
      </div>

      <div className="-mx-4 -mb-4 flex flex-wrap items-center gap-2 border-t bg-muted/50 px-4 py-3 rounded-b-xl">
        <Link
          href={`/products/${productId}/sprint/planning`}
          className="text-xs text-primary hover:underline mr-auto"
          onClick={onClose}
        >
          Open in Sprint Board ↗
        </Link>

        {!isDemo && !job && (
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger
                render={
                  <Button
                    size="sm"
                    className="h-7 text-xs"
                    onClick={handleEnqueue}
                    disabled={jobPending || connectedWorkers === 0}
                  >
                    Voer uit
                  </Button>
                }
              />
              {connectedWorkers === 0 && (
                <TooltipContent side="top" className="max-w-xs text-xs">
                  Geen Claude Code-sessie verbonden. Start claude lokaal en zeg &apos;wacht op jobs&apos;.
                </TooltipContent>
              )}
            </Tooltip>
          </TooltipProvider>
        )}

        {job?.status === 'queued' && (
          <span className="text-xs text-muted-foreground">Wacht op agent…</span>
        )}

        {(job?.status === 'claimed' || job?.status === 'running') && (
          <>
            <span className="text-xs text-muted-foreground">Bezig: {job.summary ?? '…'}</span>
            <Button size="sm" variant="outline" className="h-7 text-xs" onClick={handleCancel} disabled={jobPending}>
              Annuleer
            </Button>
          </>
        )}

        {job?.status === 'done' && (
          <span className="text-xs text-status-done">
            Klaar{job.branch ? ` — branch ${job.branch}` : ''}
          </span>
        )}

        {job?.status === 'failed' && (
          <span className="text-xs text-error">Mislukt: {job.error}</span>
        )}
      </div>
    </>
  )
}

export function TaskDetailDialog({ task, productId, isDemo, onClose }: TaskDetailDialogProps) {
  return (
    <Dialog open={!!task} onOpenChange={(open) => { if (!open) onClose() }}>
      <DialogContent className="sm:max-w-lg">
        {task && (
          <TaskDetailContent
            key={task.id}
            task={task}
            productId={productId}
            isDemo={isDemo}
            onClose={onClose}
          />
        )}
      </DialogContent>
    </Dialog>
  )
}
