import { useState } from 'react'
import { GripVertical, Plus, X, Pencil, Check, RefreshCw } from 'lucide-react'
import { useAIFlowBuilderStore } from '@/store/aiFlowBuilderStore'
import { cn } from '@/lib/utils'
import type { AIBranch } from '@/types'

export function BranchSelector() {
  const {
    suggestedBranches,
    selectedBranches,
    selectBranches,
    setPhase,
    scaffold,
    isLoading,
    error,
  } = useAIFlowBuilderStore()

  const [editingIndex, setEditingIndex] = useState<number | null>(null)
  const [editName, setEditName] = useState('')
  const [editDesc, setEditDesc] = useState('')
  const [showAddForm, setShowAddForm] = useState(false)
  const [newName, setNewName] = useState('')
  const [newDesc, setNewDesc] = useState('')

  const toggleBranch = (branch: AIBranch) => {
    const isSelected = selectedBranches.some((b) => b.name === branch.name)
    if (isSelected) {
      selectBranches(selectedBranches.filter((b) => b.name !== branch.name))
    } else {
      selectBranches([...selectedBranches, branch])
    }
  }

  const startEditing = (index: number) => {
    const branch = selectedBranches[index]
    setEditingIndex(index)
    setEditName(branch.name)
    setEditDesc(branch.description)
  }

  const saveEdit = () => {
    if (editingIndex === null || !editName.trim()) return
    const updated = [...selectedBranches]
    updated[editingIndex] = {
      ...updated[editingIndex],
      name: editName.trim(),
      description: editDesc.trim(),
    }
    selectBranches(updated)
    setEditingIndex(null)
  }

  const addCustomBranch = () => {
    if (!newName.trim()) return
    const branch: AIBranch = {
      name: newName.trim(),
      description: newDesc.trim(),
      isCustom: true,
    }
    selectBranches([...selectedBranches, branch])
    setNewName('')
    setNewDesc('')
    setShowAddForm(false)
  }

  const moveBranch = (fromIndex: number, direction: 'up' | 'down') => {
    const toIndex = direction === 'up' ? fromIndex - 1 : fromIndex + 1
    if (toIndex < 0 || toIndex >= selectedBranches.length) return
    const updated = [...selectedBranches]
    ;[updated[fromIndex], updated[toIndex]] = [updated[toIndex], updated[fromIndex]]
    selectBranches(updated)
  }

  const canProceed = selectedBranches.length >= 2

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted-foreground">
          AI suggested {suggestedBranches.length} branches. Select, reorder, rename, or add your own.
        </p>
        <button
          type="button"
          onClick={() => scaffold()}
          disabled={isLoading}
          className="flex items-center gap-1.5 rounded-lg border border-border px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50"
          title="Generate new suggestions"
        >
          <RefreshCw className={cn('h-3 w-3', isLoading && 'animate-spin')} />
          Regenerate
        </button>
      </div>

      {/* Branch list */}
      <div className="space-y-2">
        {suggestedBranches.map((branch) => {
          const isSelected = selectedBranches.some((b) => b.name === branch.name)
          const selectedIndex = selectedBranches.findIndex((b) => b.name === branch.name)

          return (
            <div
              key={branch.name}
              className={cn(
                'flex items-start gap-3 rounded-lg border p-3 transition-colors cursor-pointer',
                isSelected
                  ? 'border-primary/30 bg-primary/5'
                  : 'border-border bg-card hover:bg-accent/50'
              )}
              onClick={() => toggleBranch(branch)}
            >
              <div
                className={cn(
                  'mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border',
                  isSelected
                    ? 'border-primary bg-primary text-white'
                    : 'border-border'
                )}
              >
                {isSelected && <Check className="h-3 w-3" />}
              </div>
              <div className="flex-1 min-w-0">
                {editingIndex !== null && selectedIndex === editingIndex ? (
                  <div className="space-y-2" onClick={(e) => e.stopPropagation()}>
                    <input
                      type="text"
                      value={editName}
                      onChange={(e) => setEditName(e.target.value)}
                      className="w-full rounded border border-border bg-card px-2 py-1 text-sm text-foreground focus:border-primary focus:outline-none"
                      autoFocus
                    />
                    <input
                      type="text"
                      value={editDesc}
                      onChange={(e) => setEditDesc(e.target.value)}
                      className="w-full rounded border border-border bg-card px-2 py-1 text-xs text-muted-foreground focus:border-primary focus:outline-none"
                    />
                    <div className="flex gap-1">
                      <button
                        type="button"
                        onClick={saveEdit}
                        className="rounded bg-primary px-2 py-0.5 text-xs text-white"
                      >
                        Save
                      </button>
                      <button
                        type="button"
                        onClick={() => setEditingIndex(null)}
                        className="rounded border border-border px-2 py-0.5 text-xs text-muted-foreground"
                      >
                        Cancel
                      </button>
                    </div>
                  </div>
                ) : (
                  <>
                    <div className="text-sm font-medium text-foreground">{branch.name}</div>
                    <div className="text-xs text-muted-foreground">{branch.description}</div>
                  </>
                )}
              </div>
              {isSelected && editingIndex !== selectedIndex && (
                <div className="flex items-center gap-0.5" onClick={(e) => e.stopPropagation()}>
                  <button
                    type="button"
                    onClick={() => moveBranch(selectedIndex, 'up')}
                    disabled={selectedIndex === 0}
                    className="rounded p-1 text-muted-foreground hover:text-foreground disabled:opacity-30"
                    title="Move up"
                  >
                    <GripVertical className="h-3.5 w-3.5" />
                  </button>
                  <button
                    type="button"
                    onClick={() => startEditing(selectedIndex)}
                    className="rounded p-1 text-muted-foreground hover:text-foreground"
                    title="Edit"
                  >
                    <Pencil className="h-3.5 w-3.5" />
                  </button>
                </div>
              )}
            </div>
          )
        })}

        {/* Custom branches (not in suggested) */}
        {selectedBranches
          .filter((b) => b.isCustom)
          .map((branch, i) => {
            return (
              <div
                key={`custom-${i}`}
                className="flex items-start gap-3 rounded-lg border border-primary/30 bg-primary/5 p-3"
              >
                <div className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border border-primary bg-primary text-white">
                  <Check className="h-3 w-3" />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-foreground">{branch.name}</div>
                  <div className="text-xs text-muted-foreground">{branch.description}</div>
                  <span className="mt-1 inline-block rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-label text-primary">
                    Custom
                  </span>
                </div>
                <button
                  type="button"
                  onClick={() =>
                    selectBranches(selectedBranches.filter((b) => b.name !== branch.name))
                  }
                  className="rounded p-1 text-muted-foreground hover:text-red-400"
                >
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            )
          })}
      </div>

      {/* Add custom branch */}
      {showAddForm ? (
        <div className="space-y-2 rounded-lg border border-dashed border-border p-3">
          <input
            type="text"
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            placeholder="Branch name"
            className="w-full rounded border border-border bg-card px-2 py-1.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none"
            autoFocus
          />
          <input
            type="text"
            value={newDesc}
            onChange={(e) => setNewDesc(e.target.value)}
            placeholder="Brief description"
            className="w-full rounded border border-border bg-card px-2 py-1.5 text-xs text-muted-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:outline-none"
          />
          <div className="flex gap-1">
            <button
              type="button"
              onClick={addCustomBranch}
              disabled={!newName.trim()}
              className="rounded bg-primary px-2.5 py-1 text-xs text-white disabled:opacity-50"
            >
              Add
            </button>
            <button
              type="button"
              onClick={() => setShowAddForm(false)}
              className="rounded border border-border px-2.5 py-1 text-xs text-muted-foreground"
            >
              Cancel
            </button>
          </div>
        </div>
      ) : (
        <button
          type="button"
          onClick={() => setShowAddForm(true)}
          className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
        >
          <Plus className="h-4 w-4" />
          Add custom branch
        </button>
      )}

      {/* Error */}
      {error && (
        <div className="rounded-lg border border-red-400/20 bg-red-400/5 px-3 py-2 text-sm text-red-400">
          {error}
        </div>
      )}

      {/* Footer */}
      <div className="flex items-center justify-between pt-2">
        <span className="text-xs text-muted-foreground">
          {selectedBranches.length} branch{selectedBranches.length !== 1 ? 'es' : ''} selected (min 2)
        </span>
        <button
          type="button"
          onClick={() => setPhase('detailing')}
          disabled={!canProceed}
          className={cn(
            'rounded-lg bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20',
            canProceed ? 'hover:opacity-90' : 'cursor-not-allowed opacity-50'
          )}
        >
          Continue to Detail
        </button>
      </div>
    </div>
  )
}
