import { useState } from 'react'
import { AlertTriangle, CheckCircle2, Info, Zap, Copy, Check, ExternalLink } from 'lucide-react'
import type { RuntimeStep, StepContentType, CommandBlock } from '@/types'
import { resolveVariables } from '@/lib/variableResolver'
import { cn } from '@/lib/utils'

const contentTypeConfig: Record<StepContentType, { icon: typeof Zap; color: string; bg: string; label: string }> = {
  action: { icon: Zap, color: 'text-blue-400', bg: 'bg-blue-400/10', label: 'Action' },
  informational: { icon: Info, color: 'text-muted-foreground', bg: 'bg-accent', label: 'Info' },
  verification: { icon: CheckCircle2, color: 'text-emerald-400', bg: 'bg-emerald-400/10', label: 'Verification' },
  warning: { icon: AlertTriangle, color: 'text-yellow-400', bg: 'bg-yellow-400/10', label: 'Warning' },
}

interface StepDetailProps {
  step: RuntimeStep
  stepNumber: number
  totalSteps: number
  variables: Record<string, string>
  notes: string
  onNotesChange: (notes: string) => void
  verificationValue: string
  onVerificationChange: (value: string) => void
  isCompleted: boolean
  onMarkComplete: () => void
  isLast: boolean
}

export function StepDetail({
  step,
  stepNumber,
  totalSteps,
  variables,
  notes,
  onNotesChange,
  verificationValue,
  onVerificationChange,
  isCompleted,
  onMarkComplete,
  isLast,
}: StepDetailProps) {
  const [copiedIndex, setCopiedIndex] = useState<number | null>(null)
  const isCustom = 'isCustom' in step && step.isCustom
  const contentType = step.content_type || 'action'
  const config = contentTypeConfig[contentType]
  const Icon = config.icon

  // Derive verification from either flat fields or nested object
  const verificationPrompt = !isCustom && 'verification_prompt' in step
    ? step.verification_prompt || step.verification?.prompt
    : undefined
  const verificationType = !isCustom && 'verification_type' in step
    ? step.verification_type || step.verification?.type
    : undefined

  const resolve = (text: string | undefined) => {
    if (!text) return ''
    return resolveVariables(text, variables)
  }

  // Normalize commands to array of CommandBlock
  const commandBlocks: CommandBlock[] = (() => {
    if (!step.commands) return []
    if (typeof step.commands === 'string') {
      return [{ code: step.commands }]
    }
    if (Array.isArray(step.commands)) {
      return step.commands
    }
    return []
  })()

  const handleCopyCommand = (code: string, index: number) => {
    navigator.clipboard.writeText(resolve(code))
    setCopiedIndex(index)
    setTimeout(() => setCopiedIndex(null), 2000)
  }

  const canComplete = () => {
    if (isCompleted) return false
    if (verificationType === 'checkbox' && !verificationValue) return false
    if (verificationType === 'text_input' && !verificationValue.trim()) return false
    return true
  }

  return (
    <div className="space-y-4">
      {/* Step header */}
      <div className="flex items-start gap-3">
        <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-accent text-sm font-semibold text-foreground">
          {stepNumber}
        </span>
        <div className="min-w-0 flex-1">
          <h2 className="text-lg font-semibold text-foreground">{step.title}</h2>
          <div className="mt-1 flex items-center gap-2">
            {isCustom ? (
              <span className="inline-flex items-center gap-1 rounded-full bg-amber-400/15 px-2 py-0.5 text-xs text-amber-400">
                ✦ Custom Step
              </span>
            ) : (
              <span className={cn('inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs', config.bg, config.color)}>
                <Icon className="h-3 w-3" />
                {config.label}
              </span>
            )}
            <span className="text-xs text-muted-foreground">
              Step {stepNumber} of {totalSteps}
            </span>
            {'estimated_minutes' in step && step.estimated_minutes && (
              <span className="text-xs text-muted-foreground">~{step.estimated_minutes} min</span>
            )}
          </div>
        </div>
      </div>

      {/* Warning banner */}
      {'warning_text' in step && step.warning_text && (
        <div className="flex items-start gap-2 rounded-lg border border-yellow-400/20 bg-yellow-400/5 px-3 py-2.5">
          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-yellow-400" />
          <p className="text-sm text-yellow-200">{resolve(step.warning_text)}</p>
        </div>
      )}

      {/* Description */}
      {step.description && (
        <div className="prose prose-invert prose-sm max-w-none text-muted-foreground">
          <p className="whitespace-pre-wrap">{resolve(step.description)}</p>
        </div>
      )}

      {/* Commands block(s) */}
      {commandBlocks.length > 0 && (
        <div className="space-y-3">
          {commandBlocks.map((cmd, i) => (
            <div key={i} className="rounded-lg border border-border bg-card">
              <div className="flex items-center justify-between border-b border-border px-3 py-1.5">
                <span className="text-xs font-medium text-muted-foreground">
                  {cmd.label || (cmd.language ? cmd.language : 'Command')}
                </span>
                <button
                  onClick={() => handleCopyCommand(cmd.code, i)}
                  className="flex items-center gap-1 rounded px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
                >
                  {copiedIndex === i ? <Check className="h-3 w-3 text-emerald-400" /> : <Copy className="h-3 w-3" />}
                  {copiedIndex === i ? 'Copied' : 'Copy'}
                </button>
              </div>
              <pre className="overflow-x-auto p-3 font-mono text-sm text-emerald-300">
                {resolve(cmd.code)}
              </pre>
            </div>
          ))}
        </div>
      )}

      {/* Expected outcome */}
      {'expected_outcome' in step && step.expected_outcome && (
        <div className="rounded-lg border border-border bg-white/[0.02] p-3">
          <h4 className="mb-1 text-xs font-medium text-muted-foreground">Expected Outcome</h4>
          <p className="text-sm text-muted-foreground">{resolve(step.expected_outcome)}</p>
        </div>
      )}

      {/* Verification */}
      {verificationPrompt && (
        <div className="rounded-lg border border-border bg-white/[0.02] p-3">
          <h4 className="mb-2 text-xs font-medium text-muted-foreground">Verification</h4>
          {verificationType === 'checkbox' ? (
            <label className="flex items-center gap-2 text-sm text-muted-foreground">
              <input
                type="checkbox"
                checked={!!verificationValue}
                onChange={(e) => onVerificationChange(e.target.checked ? 'confirmed' : '')}
                disabled={isCompleted}
                className="rounded border-border"
              />
              {resolve(verificationPrompt)}
            </label>
          ) : (
            <div>
              <p className="mb-2 text-sm text-muted-foreground">{resolve(verificationPrompt)}</p>
              <input
                type="text"
                value={verificationValue}
                onChange={(e) => onVerificationChange(e.target.value)}
                disabled={isCompleted}
                placeholder="Enter observed value..."
                className="w-full rounded border border-border bg-card px-3 py-1.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20 disabled:opacity-50"
              />
            </div>
          )}
        </div>
      )}

      {/* Notes */}
      {(!('notes_enabled' in step) || step.notes_enabled !== false) && (
        <div>
          <label className="mb-1 block text-xs font-medium text-muted-foreground">Notes</label>
          <textarea
            value={notes}
            onChange={(e) => onNotesChange(e.target.value)}
            placeholder="Add notes for this step..."
            rows={2}
            className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
          />
        </div>
      )}

      {/* Reference link */}
      {'reference_url' in step && step.reference_url && (
        <a
          href={resolve(step.reference_url)}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
        >
          <ExternalLink className="h-3.5 w-3.5" />
          Reference Documentation
        </a>
      )}

      {/* Complete button */}
      <div className="pt-2">
        <button
          onClick={onMarkComplete}
          disabled={!canComplete()}
          className={cn(
            'flex w-full items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-medium transition-colors',
            isCompleted
              ? 'bg-emerald-400/10 text-emerald-400'
              : 'bg-gradient-brand text-white shadow-lg shadow-primary/20 hover:opacity-90 disabled:opacity-40 disabled:hover:opacity-100'
          )}
        >
          {isCompleted ? (
            <>
              <CheckCircle2 className="h-4 w-4" />
              Completed
            </>
          ) : isLast ? (
            'Complete Procedure'
          ) : (
            'Mark Complete & Next'
          )}
        </button>
      </div>
    </div>
  )
}
