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

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

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

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

  const hasNextNode = !!node.next_node_id

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

  const handleRemoveCommand = (index: number) => {
    const newCommands = [...(node.commands || [])]
    newCommands.splice(index, 1)
    onUpdate({ commands: newCommands })
  }

  const handleUpdateCommand = (index: number, value: string) => {
    const newCommands = [...(node.commands || [])]
    newCommands[index] = value
    onUpdate({ commands: newCommands })
  }

  const handleReorderCommands = (fromIndex: number, toIndex: number) => {
    const newCommands = [...(node.commands || [])]
    const [moved] = newCommands.splice(fromIndex, 1)
    newCommands.splice(toIndex, 0, moved)
    onUpdate({ commands: newCommands })
  }

  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., Restart the Service"
          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="Detailed instructions for this action...

**Example formatting:**
1. First step
2. Second step

**Note:** Important information here"
            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>

      {/* Commands */}
      <div>
        <label className="flex items-center gap-1.5 text-sm font-medium text-foreground">
          Commands
          <InfoTip text="PowerShell or CLI commands to execute" />
        </label>
        <DynamicArrayField
          items={node.commands || []}
          onAdd={handleAddCommand}
          onRemove={handleRemoveCommand}
          onReorder={handleReorderCommands}
          addLabel="Add Command"
          renderItem={(command, index) => (
            <input
              type="text"
              value={command}
              onChange={(e) => handleUpdateCommand(index, e.target.value)}
              placeholder="e.g., Get-Service BrokerAgent"
              className={cn(
                'block w-full rounded-md border border-border px-3 py-2 font-mono text-sm',
                'bg-background text-foreground placeholder:text-muted-foreground',
                'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary'
              )}
            />
          )}
        />
      </div>

      {/* Expected Outcome */}
      <div>
        <label className="block text-sm font-medium text-foreground">
          Expected Outcome
        </label>
        <input
          type="text"
          value={node.expected_outcome || ''}
          onChange={(e) => onUpdate({ expected_outcome: e.target.value })}
          placeholder="e.g., Service should show as Running"
          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>

      {/* Link to existing node */}
      <div>
        <label className="flex items-center gap-1.5 text-sm font-medium text-foreground">
          <Link2 className="h-3.5 w-3.5" />
          Next Step
        </label>
        {hasNextNode ? (
          <div className="mt-1 flex items-center gap-2 rounded-md border border-primary/30 bg-primary/5 px-3 py-2">
            <span className="flex-1 truncate text-sm text-foreground">
              Linked to: {(() => {
                const treeStructure = useTreeEditorStore.getState().treeStructure
                const allNodes = collectAllNodesFlat(treeStructure)
                const target = allNodes.find(n => n.id === node.next_node_id)
                return target ? target.label : node.next_node_id
              })()}
            </span>
            <button
              type="button"
              onClick={() => onUpdate({ next_node_id: undefined })}
              className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
              title="Remove link"
            >
              <X className="h-3.5 w-3.5" />
            </button>
          </div>
        ) : (
          <select
            value=""
            onChange={(e) => {
              if (e.target.value) {
                onUpdate({ next_node_id: e.target.value })
              }
            }}
            className={cn(
              'mt-1 block w-full rounded-md border border-border px-3 py-2 text-sm',
              'bg-card text-foreground',
              'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20'
            )}
          >
            <option value="">Link to existing node...</option>
            {(() => {
              const treeStructure = useTreeEditorStore.getState().treeStructure
              const allNodes = collectAllNodesFlat(treeStructure)
              return allNodes
                .filter(n => n.id !== node.id && n.type !== 'answer')
                .map(n => (
                  <option key={n.id} value={n.id}>
                    {'  '.repeat(n.depth)}{n.type === 'decision' ? '?' : n.type === 'action' ? '>' : '*'} {n.label}
                  </option>
                ))
            })()}
          </select>
        )}
        <p className="mt-1 text-xs text-muted-foreground">
          {hasNextNode
            ? 'This action will navigate to the linked node.'
            : 'Select a node to navigate to after this action, or save to create a new placeholder.'}
        </p>
      </div>
    </div>
  )
}

export default NodeFormAction
