import { useState } from 'react'
import { DynamicArrayField } from './DynamicArrayField'
import { useTreeEditorStore } from '@/store/treeEditorStore'
import { MarkdownContent } from '@/components/ui/MarkdownContent'
import { InfoTip } from '@/components/common/InfoTip'
import type { TreeStructure } from '@/types'
import { cn } from '@/lib/utils'

interface NodeFormResolutionProps {
  node: TreeStructure
  onUpdate: (updates: Partial<TreeStructure>) => void
}

export function NodeFormResolution({ node, onUpdate }: NodeFormResolutionProps) {
  const { validationErrors } = useTreeEditorStore()
  const [showPreview, setShowPreview] = useState(false)

  const titleError = validationErrors.find(
    e => e.nodeId === node.id && e.field === 'title'
  )

  const handleAddStep = () => {
    onUpdate({
      resolution_steps: [...(node.resolution_steps || []), '']
    })
  }

  const handleRemoveStep = (index: number) => {
    const newSteps = [...(node.resolution_steps || [])]
    newSteps.splice(index, 1)
    onUpdate({ resolution_steps: newSteps })
  }

  const handleUpdateStep = (index: number, value: string) => {
    const newSteps = [...(node.resolution_steps || [])]
    newSteps[index] = value
    onUpdate({ resolution_steps: newSteps })
  }

  const handleReorderSteps = (fromIndex: number, toIndex: number) => {
    const newSteps = [...(node.resolution_steps || [])]
    const [moved] = newSteps.splice(fromIndex, 1)
    newSteps.splice(toIndex, 0, moved)
    onUpdate({ resolution_steps: newSteps })
  }

  return (
    <div className="space-y-4">
      {/* Title */}
      <div>
        <label className="block text-sm font-medium text-foreground">
          Title <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          value={node.title || ''}
          onChange={(e) => onUpdate({ title: e.target.value })}
          placeholder="e.g., VDA Successfully Registered"
          className={cn(
            'mt-1 block w-full rounded-md border px-3 py-2 text-sm',
            'bg-card text-foreground placeholder:text-muted-foreground',
            'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20',
            titleError ? 'border-red-400' : 'border-border'
          )}
        />
        {titleError && (
          <p className="mt-1 text-xs text-red-400">{titleError.message}</p>
        )}
      </div>

      {/* Description */}
      <div>
        <div className="flex items-center justify-between">
          <label className="flex items-center gap-1.5 text-sm font-medium text-foreground">
            Description
            <InfoTip text="Supports markdown: **bold**, *italic*, - lists, 1. numbered lists, `code`" />
          </label>
          {node.description && (
            <button
              type="button"
              onClick={() => setShowPreview(!showPreview)}
              className="text-xs text-muted-foreground hover:text-foreground hover:underline"
            >
              {showPreview ? 'Edit' : 'Preview'}
            </button>
          )}
        </div>
        {showPreview && node.description ? (
          <div className="mt-1 rounded-md border border-border bg-accent/50 p-3 text-sm">
            <MarkdownContent content={node.description} />
          </div>
        ) : (
          <textarea
            value={node.description || ''}
            onChange={(e) => onUpdate({ description: e.target.value })}
            placeholder="Summary of the resolution and any follow-up recommendations...

**Ticket Notes:**
Document what was done and the outcome.

**Close ticket as:** Resolved"
            rows={5}
            className={cn(
              'mt-1 block w-full rounded-md border border-border px-3 py-2 text-sm',
              'bg-background text-foreground placeholder:text-muted-foreground',
              'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary'
            )}
          />
        )}
      </div>

      {/* Resolution Steps */}
      <div>
        <label className="flex items-center gap-1.5 text-sm font-medium text-foreground">
          Resolution Steps
          <InfoTip text="Step-by-step instructions for resolving the issue" />
        </label>
        <DynamicArrayField
          items={node.resolution_steps || []}
          onAdd={handleAddStep}
          onRemove={handleRemoveStep}
          onReorder={handleReorderSteps}
          addLabel="Add Step"
          renderItem={(step, index) => (
            <div className="flex items-start gap-2">
              <span className="mt-2 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-emerald-400/10 text-xs font-medium text-emerald-400">
                {index + 1}
              </span>
              <input
                type="text"
                value={step}
                onChange={(e) => handleUpdateStep(index, e.target.value)}
                placeholder={`Step ${index + 1}`}
                className={cn(
                  'block w-full rounded-md border border-border px-3 py-2 text-sm',
                  'bg-background text-foreground placeholder:text-muted-foreground',
                  'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary'
                )}
              />
            </div>
          )}
        />
      </div>

      {/* Note about terminal node */}
      <p className="text-xs text-emerald-400/70">
        Solution nodes are terminal — the session completes when users reach this node.
      </p>
    </div>
  )
}

export default NodeFormResolution
