'use client'

import { useState, useCallback } from 'react'
import Link from 'next/link'
import { useFlowRun } from '@/hooks/useFlowRun'
import StreamingTerminal from '@/components/StreamingTerminal'
import ConfirmDialog from '@/components/ConfirmDialog'

const FLOW_KEY = 'redeploy_all'

const STEPS = [
  'git status Scrum4Me (show current state)',
  'git fetch Scrum4Me (fetch remote refs)',
  'git log (commits ahead of upstream)',
  'git pull --ff-only Scrum4Me (aborts if dirty)',
  'npm ci (install dependencies)',
  'prisma migrate deploy (apply migrations)',
  'npm run build (build application)',
  'systemctl restart scrum4me-web',
  'smoke test: curl /api/products (expect 200 or 401)',
  'git status scrum4me-docker (show current state)',
  'git fetch scrum4me-docker (fetch remote refs)',
  'git pull --ff-only scrum4me-docker (aborts if dirty)',
  'git pull --ff-only scrum4me-mcp (lokale sync)',
  'rebuild worker image — cache-busted MCP clone',
  'docker compose up -d --force-recreate worker-idea',
  'wait for worker pre-flight to pass',
]

export default function FlowPanel() {
  const [pendingDryRun, setPendingDryRun] = useState<boolean | null>(null)
  const [completedFlowRunId, setCompletedFlowRunId] = useState<string | null>(null)

  const handleComplete = useCallback((flowRunId: string) => {
    setCompletedFlowRunId(flowRunId)
  }, [])

  const flowRun = useFlowRun(handleComplete)

  const handleConfirm = useCallback(() => {
    if (pendingDryRun === null) return
    const dryRun = pendingDryRun
    setPendingDryRun(null)
    setCompletedFlowRunId(null)
    flowRun.startFlow(FLOW_KEY, dryRun)
  }, [pendingDryRun, flowRun])

  const handleReset = useCallback(() => {
    flowRun.reset()
    setCompletedFlowRunId(null)
  }, [flowRun])

  return (
    <div className="space-y-6">
      <div className="rounded-lg border border-border p-5 space-y-4">
        <div>
          <p className="text-sm text-muted-foreground">
            Volledige stack-redeploy: eerst de hoofd-app (scrum4me-web — pull,
            migrate, build, restart), dan de MCP-worker (cache-busted image
            rebuild zodat de nieuwe scrum4me-mcp code wordt opgepikt).
          </p>
          <p className="mt-1 text-xs text-muted-foreground font-mono">
            repos: Scrum4Me · scrum4me-docker · scrum4me-mcp
          </p>
        </div>
        <ol className="space-y-1">
          {STEPS.map((step, i) => (
            <li key={i} className="flex gap-2 text-xs font-mono text-muted-foreground">
              <span className="text-border min-w-[1.5rem]">{i + 1}.</span>
              <span>{step}</span>
            </li>
          ))}
        </ol>
      </div>

      <div className="flex items-center gap-3">
        <button
          onClick={() => setPendingDryRun(false)}
          disabled={flowRun.status === 'running'}
          className="rounded-lg bg-foreground text-background px-4 py-2 text-sm font-medium hover:opacity-90 disabled:opacity-50 transition-opacity"
        >
          Run
        </button>
        <button
          onClick={() => setPendingDryRun(true)}
          disabled={flowRun.status === 'running'}
          className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted/50 disabled:opacity-50 transition-colors"
        >
          Dry Run
        </button>
        {flowRun.status !== 'idle' && flowRun.status !== 'running' && (
          <button
            onClick={handleReset}
            className="text-xs text-muted-foreground hover:text-foreground transition-colors"
          >
            Reset
          </button>
        )}
      </div>

      {flowRun.status !== 'idle' && (
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">Output</span>
            {completedFlowRunId && (
              <Link
                href={`/audit/${completedFlowRunId}`}
                className="text-xs text-muted-foreground hover:text-foreground transition-colors"
              >
                View in audit log →
              </Link>
            )}
          </div>
          <StreamingTerminal
            lines={flowRun.lines}
            status={flowRun.status}
            error={flowRun.error}
          />
        </div>
      )}

      <ConfirmDialog
        open={pendingDryRun !== null}
        title={pendingDryRun ? 'Dry Run: Redeploy All' : 'Run: Redeploy All'}
        commandPreview={
          pendingDryRun
            ? `[DRY RUN] flow: ${FLOW_KEY}\n\nAll steps will be shown without executing.`
            : `flow: ${FLOW_KEY}\n\nSteps:\n${STEPS.map((s, i) => `  ${i + 1}. ${s}`).join('\n')}`
        }
        onConfirm={handleConfirm}
        onCancel={() => setPendingDryRun(null)}
      />
    </div>
  )
}
