'use client'

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

type Phase = 'edit' | 'writing' | 'validating' | 'validated' | 'saving' | 'saved'

type DialogPending = 'validate' | 'save' | null

type Props = {
  initialContent: string
  initialError: string | null
}

const VALIDATE_PREVIEW =
  'cat > /srv/scrum4me/caddy/Caddyfile.new \\\n  && mv /srv/scrum4me/caddy/Caddyfile.new /srv/scrum4me/caddy/Caddyfile\ncaddy validate --config /srv/scrum4me/caddy/Caddyfile'

const SAVE_PREVIEW = 'caddy reload --config /srv/scrum4me/caddy/Caddyfile'

export default function CaddyEditor({ initialContent, initialError }: Props) {
  const [content, setContent] = useState(initialContent)
  const [phase, setPhase] = useState<Phase>('edit')
  const [dialogPending, setDialogPending] = useState<DialogPending>(null)

  const writeFlow = useFlowRun()
  const validateFlow = useFlowRun()
  const reloadFlow = useFlowRun()

  // Chain: write done → start validate
  useEffect(() => {
    if (phase === 'writing' && writeFlow.status === 'done') {
      setPhase('validating')
      validateFlow.start('caddy_validate')
    } else if (phase === 'writing' && (writeFlow.status === 'failed' || writeFlow.status === 'error')) {
      setPhase('edit')
    }
  }, [writeFlow.status, phase, validateFlow.start])

  // Validate done → validated phase
  useEffect(() => {
    if (phase === 'validating' && validateFlow.status === 'done') {
      setPhase('validated')
    } else if (phase === 'validating' && (validateFlow.status === 'failed' || validateFlow.status === 'error')) {
      setPhase('edit')
    }
  }, [validateFlow.status, phase])

  // Reload done → saved
  useEffect(() => {
    if (phase === 'saving' && reloadFlow.status === 'done') {
      setPhase('saved')
    } else if (phase === 'saving' && (reloadFlow.status === 'failed' || reloadFlow.status === 'error')) {
      setPhase('validated')
    }
  }, [reloadFlow.status, phase])

  const handleValidateConfirm = useCallback(() => {
    setDialogPending(null)
    setPhase('writing')
    writeFlow.reset()
    validateFlow.reset()
    writeFlow.start('caddy_write_config', [], content)
  }, [content, writeFlow.reset, writeFlow.start, validateFlow.reset])

  const handleSaveConfirm = useCallback(() => {
    setDialogPending(null)
    setPhase('saving')
    reloadFlow.reset()
    reloadFlow.start('caddy_reload')
  }, [reloadFlow.reset, reloadFlow.start])

  const handleEditAgain = () => {
    writeFlow.reset()
    validateFlow.reset()
    reloadFlow.reset()
    setPhase('edit')
  }

  const isActive = phase === 'writing' || phase === 'validating' || phase === 'saving'

  return (
    <div className="space-y-6">
      {initialError && (
        <div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive">
          Failed to load current config: {initialError}
        </div>
      )}

      {/* Textarea */}
      <div className="space-y-2">
        <div className="flex items-center justify-between">
          <h2 className="text-base font-medium tracking-tight">Caddyfile</h2>
          {phase === 'saved' && (
            <span className="inline-flex items-center gap-1.5 text-sm text-green-600 dark:text-green-400">
              <span className="size-2 rounded-full bg-green-500" />
              Reloaded successfully
            </span>
          )}
          {phase === 'validated' && (
            <span className="inline-flex items-center gap-1.5 text-sm text-green-600 dark:text-green-400">
              <span className="size-2 rounded-full bg-green-500" />
              Config is valid
            </span>
          )}
        </div>
        <textarea
          value={content}
          onChange={(e) => {
            setContent(e.target.value)
            // Reset validated state if user edits after validation
            if (phase === 'validated' || phase === 'saved') setPhase('edit')
          }}
          readOnly={isActive}
          rows={24}
          spellCheck={false}
          className="w-full rounded-lg border border-border bg-zinc-950 p-4 font-mono text-xs text-zinc-100 focus:outline-none focus:ring-1 focus:ring-ring resize-y disabled:opacity-50"
        />
      </div>

      {/* Action buttons */}
      <div className="flex items-center gap-3">
        {(phase === 'edit' || phase === 'validated' || phase === 'saved') && (
          <button
            onClick={() => setDialogPending('validate')}
            disabled={isActive || !content.trim()}
            className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted/50 disabled:opacity-50 transition-colors"
          >
            Validate
          </button>
        )}
        {(phase === 'validated') && (
          <button
            onClick={() => setDialogPending('save')}
            disabled={isActive}
            className="rounded-lg bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-700 disabled:opacity-50 transition-colors"
          >
            Save + Reload
          </button>
        )}
        {(phase === 'validated' || phase === 'saved') && (
          <button
            onClick={handleEditAgain}
            className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted/50 transition-colors"
          >
            Edit again
          </button>
        )}
        {phase === 'saved' && (
          <Link
            href="/caddy"
            className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted/50 transition-colors"
          >
            ← Back to Caddy
          </Link>
        )}
      </div>

      {/* Write flow terminal (step 1 of validate) */}
      {(phase === 'writing' || phase === 'validating' || (writeFlow.status !== 'idle' && writeFlow.lines.length > 0)) && (
        <div className="space-y-1">
          <p className="text-xs text-muted-foreground">Writing config…</p>
          <StreamingTerminal
            lines={writeFlow.lines}
            status={writeFlow.status === 'done' ? 'done' : writeFlow.status}
            error={writeFlow.error}
          />
        </div>
      )}

      {/* Validate flow terminal (step 2 of validate) */}
      {(phase === 'validating' || phase === 'validated' || (validateFlow.status !== 'idle')) && (
        <div className="space-y-1">
          <p className="text-xs text-muted-foreground">Validating config…</p>
          <StreamingTerminal
            lines={validateFlow.lines}
            status={validateFlow.status}
            error={validateFlow.error}
          />
        </div>
      )}

      {/* Reload flow terminal */}
      {(phase === 'saving' || phase === 'saved' || (reloadFlow.status !== 'idle')) && (
        <div className="space-y-1">
          <p className="text-xs text-muted-foreground">Reloading Caddy…</p>
          <StreamingTerminal
            lines={reloadFlow.lines}
            status={reloadFlow.status}
            error={reloadFlow.error}
          />
        </div>
      )}

      {/* Confirm dialogs */}
      <ConfirmDialog
        open={dialogPending === 'validate'}
        title="Validate Caddyfile"
        commandPreview={VALIDATE_PREVIEW}
        onConfirm={handleValidateConfirm}
        onCancel={() => setDialogPending(null)}
      />
      <ConfirmDialog
        open={dialogPending === 'save'}
        title="Save + Reload Caddy"
        commandPreview={SAVE_PREVIEW}
        onConfirm={handleSaveConfirm}
        onCancel={() => setDialogPending(null)}
      />
    </div>
  )
}
