import { useState, useEffect } from 'react'
import { Plus, X, HelpCircle, Zap, CheckCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { stepCategoriesApi } from '@/api/stepCategories'
import type { StepCreate, StepCategory, StepCommand } from '@/types/step'
import { Button } from '@/components/ui/Button'

interface StepFormProps {
  onSubmit: (data: StepCreate) => void
  onCancel: () => void
  initialData?: Partial<StepCreate>
  submitLabel?: string
  isSubmitting?: boolean
}

const stepTypeOptions = [
  { value: 'decision', label: 'Decision', icon: HelpCircle, description: 'Question with multiple options' },
  { value: 'action', label: 'Action', icon: Zap, description: 'Task to perform' },
  { value: 'solution', label: 'Solution', icon: CheckCircle, description: 'Resolution endpoint' }
] as const

export function StepForm({ onSubmit, onCancel, initialData, submitLabel, isSubmitting }: StepFormProps) {
  // Form state
  const [stepType, setStepType] = useState<'decision' | 'action' | 'solution'>(
    initialData?.step_type || 'action'
  )
  const [title, setTitle] = useState(initialData?.title || '')
  const [instructions, setInstructions] = useState(initialData?.content?.instructions || '')
  const [helpText, setHelpText] = useState(initialData?.content?.help_text || '')
  const [commands, setCommands] = useState<StepCommand[]>(initialData?.content?.commands || [])
  const [categoryId, setCategoryId] = useState(initialData?.category_id || '')
  const [tags, setTags] = useState<string[]>(initialData?.tags || [])
  const [tagInput, setTagInput] = useState('')
  const [visibility, setVisibility] = useState<'private' | 'team' | 'public'>(
    initialData?.visibility || 'private'
  )
  // Categories
  const [categories, setCategories] = useState<StepCategory[]>([])

  // Validation
  const [errors, setErrors] = useState<Record<string, string>>({})

  useEffect(() => {
    const loadCategories = async () => {
      try {
        const data = await stepCategoriesApi.list()
        setCategories(data.filter(c => c.is_active))
      } catch (err) {
        console.error('Failed to load categories:', err)
      }
    }
    loadCategories()
  }, [])

  const addCommand = () => {
    setCommands([...commands, { label: '', command: '', command_type: 'shell' }])
  }

  const removeCommand = (index: number) => {
    setCommands(commands.filter((_, i) => i !== index))
  }

  const updateCommand = (index: number, field: keyof StepCommand, value: string) => {
    const updated = [...commands]
    updated[index] = { ...updated[index], [field]: value }
    setCommands(updated)
  }

  const addTag = () => {
    const trimmed = tagInput.trim()
    if (trimmed && !tags.includes(trimmed)) {
      setTags([...tags, trimmed])
      setTagInput('')
    }
  }

  const removeTag = (tag: string) => {
    setTags(tags.filter(t => t !== tag))
  }

  const handleTagInputKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      addTag()
    }
  }

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {}

    if (!title.trim()) {
      newErrors.title = 'Title is required'
    }

    if (!instructions.trim()) {
      newErrors.instructions = 'Instructions are required'
    }

    // Validate commands
    commands.forEach((cmd, i) => {
      if (cmd.label && !cmd.command) {
        newErrors[`command_${i}_command`] = 'Command is required if label is provided'
      }
      if (cmd.command && !cmd.label) {
        newErrors[`command_${i}_label`] = 'Label is required if command is provided'
      }
    })

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()

    if (!validate()) {
      return
    }

    const data: StepCreate = {
      title: title.trim(),
      step_type: stepType,
      content: {
        instructions: instructions.trim(),
        help_text: helpText.trim() || undefined,
        commands: commands.filter(c => c.label && c.command).length > 0
          ? commands.filter(c => c.label && c.command)
          : undefined
      },
      visibility,
      category_id: categoryId || undefined,
      tags: tags.length > 0 ? tags : undefined
    }

    onSubmit(data)
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Step Type */}
      <div>
        <label className="mb-2 block text-sm font-medium text-foreground">
          Step Type <span className="text-red-400">*</span>
        </label>
        <div className="grid grid-cols-3 gap-2">
          {stepTypeOptions.map(option => {
            const Icon = option.icon
            return (
              <button
                key={option.value}
                type="button"
                onClick={() => setStepType(option.value)}
                className={cn(
                  'rounded-lg border p-3 text-left transition-colors',
                  stepType === option.value
                    ? 'border-border bg-accent ring-2 ring-primary/20'
                    : 'border-border hover:border-border'
                )}
              >
                <div className="mb-1 flex items-center gap-2">
                  <Icon className="h-4 w-4" />
                  <span className="font-medium text-sm text-foreground">{option.label}</span>
                </div>
                <p className="text-xs text-muted-foreground">{option.description}</p>
              </button>
            )
          })}
        </div>
      </div>

      {/* Title */}
      <div>
        <label htmlFor="title" className="mb-2 block text-sm font-medium text-foreground">
          Title <span className="text-red-400">*</span>
        </label>
        <input
          id="title"
          type="text"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder="Enter step title"
          className={cn(
            'w-full rounded-md border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20',
            errors.title ? 'border-red-400/50' : 'border-border'
          )}
        />
        {errors.title && (
          <p className="mt-1 text-xs text-red-400">{errors.title}</p>
        )}
      </div>

      {/* Instructions */}
      <div>
        <label htmlFor="instructions" className="mb-2 block text-sm font-medium text-foreground">
          Instructions <span className="text-red-400">*</span>
          <span className="ml-2 text-xs font-normal text-muted-foreground">(Markdown supported)</span>
        </label>
        <textarea
          id="instructions"
          value={instructions}
          onChange={(e) => setInstructions(e.target.value)}
          placeholder="Describe what to do in this step..."
          rows={6}
          className={cn(
            'w-full rounded-md border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20',
            errors.instructions ? 'border-red-400/50' : 'border-border'
          )}
        />
        {errors.instructions && (
          <p className="mt-1 text-xs text-red-400">{errors.instructions}</p>
        )}
      </div>

      {/* Help Text */}
      <div>
        <label htmlFor="helpText" className="mb-2 block text-sm font-medium text-foreground">
          Help Text <span className="text-xs font-normal text-muted-foreground">(Optional)</span>
        </label>
        <textarea
          id="helpText"
          value={helpText}
          onChange={(e) => setHelpText(e.target.value)}
          placeholder="Additional context or tips..."
          rows={3}
          className="w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
        />
      </div>

      {/* Commands */}
      <div>
        <div className="mb-2 flex items-center justify-between">
          <label className="text-sm font-medium text-foreground">
            Commands <span className="text-xs font-normal text-muted-foreground">(Optional)</span>
          </label>
          <button
            type="button"
            onClick={addCommand}
            className="flex items-center gap-1 rounded-md bg-accent px-2 py-1 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
          >
            <Plus className="h-3 w-3" />
            Add Command
          </button>
        </div>
        {commands.length > 0 && (
          <div className="space-y-3">
            {commands.map((cmd, index) => (
              <div key={index} className="rounded-lg border border-border bg-accent/50 p-3">
                <div className="mb-2 flex items-center justify-between">
                  <span className="text-xs font-medium text-muted-foreground">Command {index + 1}</span>
                  <button
                    type="button"
                    onClick={() => removeCommand(index)}
                    className="rounded p-1 text-muted-foreground hover:bg-red-400/10 hover:text-red-400"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </div>
                <div className="space-y-2">
                  <input
                    type="text"
                    value={cmd.label}
                    onChange={(e) => updateCommand(index, 'label', e.target.value)}
                    placeholder="Command label (e.g., 'Restart service')"
                    className={cn(
                      'w-full rounded-md border bg-card px-3 py-1.5 text-sm text-foreground',
                      errors[`command_${index}_label`] ? 'border-red-400/50' : 'border-border'
                    )}
                  />
                  <input
                    type="text"
                    value={cmd.command}
                    onChange={(e) => updateCommand(index, 'command', e.target.value)}
                    placeholder="Command (e.g., 'systemctl restart nginx')"
                    className={cn(
                      'w-full rounded-md border bg-card px-3 py-1.5 font-mono text-sm text-foreground',
                      errors[`command_${index}_command`] ? 'border-red-400/50' : 'border-border'
                    )}
                  />
                  {(errors[`command_${index}_label`] || errors[`command_${index}_command`]) && (
                    <p className="text-xs text-red-400">
                      {errors[`command_${index}_label`] || errors[`command_${index}_command`]}
                    </p>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Category */}
      <div>
        <label htmlFor="category" className="mb-2 block text-sm font-medium text-foreground">
          Category <span className="text-xs font-normal text-muted-foreground">(Optional)</span>
        </label>
        <select
          id="category"
          value={categoryId}
          onChange={(e) => setCategoryId(e.target.value)}
          className="w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
        >
          <option value="">None</option>
          {categories.map(cat => (
            <option key={cat.id} value={cat.id}>{cat.name}</option>
          ))}
        </select>
      </div>

      {/* Tags */}
      <div>
        <label htmlFor="tagInput" className="mb-2 block text-sm font-medium text-foreground">
          Tags <span className="text-xs font-normal text-muted-foreground">(Optional)</span>
        </label>
        <div className="flex gap-2">
          <input
            id="tagInput"
            type="text"
            value={tagInput}
            onChange={(e) => setTagInput(e.target.value)}
            onKeyDown={handleTagInputKeyDown}
            placeholder="Type tag and press Enter"
            className="flex-1 rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
          />
          <button
            type="button"
            onClick={addTag}
            className="rounded-md bg-accent px-4 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
          >
            Add
          </button>
        </div>
        {tags.length > 0 && (
          <div className="mt-2 flex flex-wrap gap-1.5">
            {tags.map(tag => (
              <span
                key={tag}
                className="flex items-center gap-1 rounded-full bg-accent px-2.5 py-1 text-xs text-muted-foreground"
              >
                {tag}
                <button
                  type="button"
                  onClick={() => removeTag(tag)}
                  className="rounded-full hover:bg-accent"
                  aria-label={`Remove tag ${tag}`}
                >
                  <X className="h-3 w-3" />
                </button>
              </span>
            ))}
          </div>
        )}
      </div>

      {/* Visibility */}
      <div>
        <label htmlFor="visibility" className="mb-2 block text-sm font-medium text-foreground">
          Visibility
        </label>
        <select
          id="visibility"
          value={visibility}
          onChange={(e) => setVisibility(e.target.value as 'private' | 'team' | 'public')}
          className="w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
        >
          <option value="private">Private (only me)</option>
          <option value="team">Team (my team members)</option>
          <option value="public">Public (everyone)</option>
        </select>
      </div>

      {/* Actions */}
      <div className="flex gap-2 pt-4">
        <Button
          type="button"
          variant="secondary"
          onClick={onCancel}
          className="flex-1"
        >
          Cancel
        </Button>
        <Button
          type="submit"
          loading={isSubmitting}
          className="flex-1"
        >
          {submitLabel ?? 'Insert Step'}
        </Button>
      </div>
    </form>
  )
}
