import { useRef, useEffect, useCallback, type ReactNode } from 'react'
import { Plus, GripVertical, Trash2, ChevronDown, CheckCircle2, AlertTriangle, Info, Zap, ListOrdered, SeparatorHorizontal } from 'lucide-react'
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import type { DragEndEvent } from '@dnd-kit/core'
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import type { StepContentType } from '@/types'
import { StepEditor } from './StepEditor'
import { useProceduralEditorStore } from '@/store/proceduralEditorStore'
import { cn } from '@/lib/utils'

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

function SortableStepWrapper({
  id,
  disabled,
  children,
}: {
  id: string
  disabled?: boolean
  children: (props: { dragHandleProps: Record<string, unknown> }) => ReactNode
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, disabled })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  }

  return (
    <div ref={setNodeRef} style={style} className={cn(isDragging && 'z-10 opacity-50')}>
      {children({ dragHandleProps: { ...attributes, ...listeners } })}
    </div>
  )
}

interface StepListProps {
  onStepContextMenu?: (e: React.MouseEvent, stepId: string) => void
}

export function StepList({ onStepContextMenu }: StepListProps) {
  const {
    steps,
    intakeForm,
    expandedStepId,
    setExpandedStepId,
    addStep,
    addSectionHeader,
    removeStep,
    updateStep,
    moveStep,
  } = useProceduralEditorStore()

  const procedureSteps = steps.filter((s) => s.type === 'procedure_step')
  const totalMinutes = steps
    .filter(s => s.type === 'procedure_step' && s.estimated_minutes)
    .reduce((sum, s) => sum + (s.estimated_minutes || 0), 0)

  // Auto-scroll to new steps
  const scrollTargetRef = useRef<HTMLDivElement>(null)
  const prevStepCount = useRef(steps.length)

  useEffect(() => {
    if (steps.length > prevStepCount.current) {
      setTimeout(() => {
        scrollTargetRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
      }, 50)
    }
    prevStepCount.current = steps.length
  }, [steps.length])

  // DnD setup
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  )

  const handleDragEnd = useCallback((event: DragEndEvent) => {
    const { active, over } = event
    if (!over || active.id === over.id) return

    const oldIndex = steps.findIndex(s => s.id === active.id)
    const newIndex = steps.findIndex(s => s.id === over.id)
    if (oldIndex === -1 || newIndex === -1) return

    // Don't allow moving past the procedure_end step
    const endIndex = steps.findIndex(s => s.type === 'procedure_end')
    if (newIndex >= endIndex) return

    moveStep(oldIndex, newIndex)
  }, [steps, moveStep])

  // Sortable items: everything except procedure_end
  const sortableItems = steps.filter(s => s.type !== 'procedure_end').map(s => s.id)

  let stepCounter = 0

  return (
    <div>
      <div className="mb-4 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <ListOrdered className="h-5 w-5 text-muted-foreground" />
          <h2 className="text-lg font-semibold text-foreground">Steps</h2>
          <span className="text-sm text-muted-foreground">
            ({procedureSteps.length} step{procedureSteps.length !== 1 ? 's' : ''}
            {totalMinutes > 0 ? ` \u00b7 ~${totalMinutes} min` : ''})
          </span>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => addSectionHeader()}
            className="flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-sm text-muted-foreground hover:bg-elevated hover:text-foreground"
          >
            <SeparatorHorizontal className="h-3.5 w-3.5" />
            Add Section
          </button>
          <button
            onClick={() => addStep()}
            className="flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-sm text-muted-foreground hover:bg-elevated hover:text-foreground"
          >
            <Plus className="h-3.5 w-3.5" />
            Add Step
          </button>
        </div>
      </div>

      <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
        <SortableContext items={sortableItems} strategy={verticalListSortingStrategy}>
          <div className="space-y-2">
            {steps.map((step) => {
              if (step.type === 'procedure_end') {
                // procedure_end: non-draggable, always last
                return (
                  <div
                    key={step.id}
                    className="flex items-center gap-2 rounded-lg border border-dashed border-border bg-elevated/40 px-3 py-2"
                  >
                    <CheckCircle2 className="h-4 w-4 text-emerald-400/50" />
                    <input
                      type="text"
                      value={step.title}
                      onChange={(e) => updateStep(step.id, { title: e.target.value })}
                      className="flex-1 bg-transparent text-sm text-muted-foreground focus:outline-hidden"
                      placeholder="Procedure Complete"
                    />
                    <span className="text-[10px] text-muted-foreground">END</span>
                  </div>
                )
              }

              // Section header rendering
              if (step.type === 'section_header') {
                const isExpanded = expandedStepId === step.id

                if (isExpanded) {
                  return (
                    <SortableStepWrapper key={step.id} id={step.id} disabled>
                      {() => (
                        <div ref={scrollTargetRef} data-step-id={step.id}>
                          <StepEditor
                            step={step}
                            stepNumber={0}
                            onUpdate={(updates) => updateStep(step.id, updates)}
                            onCollapse={() => setExpandedStepId(null)}
                            availableVariables={intakeForm}
                          />
                        </div>
                      )}
                    </SortableStepWrapper>
                  )
                }

                return (
                  <SortableStepWrapper key={step.id} id={step.id}>
                    {({ dragHandleProps }) => (
                      <div className="group flex items-center gap-2 border-b border-border pb-1 pt-3" data-step-id={step.id}>
                        <button
                          type="button"
                          className="shrink-0 cursor-grab touch-none text-muted-foreground active:cursor-grabbing"
                          aria-label={`Drag to reorder section: ${step.title || 'Untitled Section'}`}
                          {...dragHandleProps}
                        >
                          <GripVertical className="h-4 w-4" />
                        </button>
                        <span
                          className="min-w-0 flex-1 cursor-pointer text-xs font-semibold uppercase tracking-wider text-muted-foreground hover:text-muted-foreground"
                          onClick={() => setExpandedStepId(step.id)}
                        >
                          {step.title || 'Untitled Section'}
                        </span>
                        <button
                          onClick={() => removeStep(step.id)}
                          className="shrink-0 rounded p-1 text-muted-foreground opacity-0 hover:bg-red-500/20 hover:text-red-400 group-hover:opacity-100"
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    )}
                  </SortableStepWrapper>
                )
              }

              // Regular procedure step
              stepCounter++
              const stepNumber = stepCounter
              const isExpanded = expandedStepId === step.id
              const contentType = step.content_type || 'action'
              const config = contentTypeConfig[contentType]
              const Icon = config.icon
              const isGhost = !!(step as unknown as Record<string, unknown>)._suggestion

              if (isExpanded) {
                return (
                  <SortableStepWrapper key={step.id} id={step.id} disabled>
                    {() => (
                      <div ref={scrollTargetRef} data-step-id={step.id}>
                        <StepEditor
                          step={step}
                          stepNumber={stepNumber}
                          onUpdate={(updates) => updateStep(step.id, updates)}
                          onCollapse={() => setExpandedStepId(null)}
                          availableVariables={intakeForm}
                        />
                      </div>
                    )}
                  </SortableStepWrapper>
                )
              }

              return (
                <SortableStepWrapper key={step.id} id={step.id}>
                  {({ dragHandleProps }) => (
                    <div
                      className={cn(
                        'group flex flex-col rounded-xl border border-border px-3 py-2.5 transition-colors',
                        'hover:border-white/[0.15] hover:bg-elevated',
                        isGhost && 'border-l-2 border-dashed border-l-primary/40! opacity-60'
                      )}
                      data-step-id={step.id}
                      onContextMenu={(e) => onStepContextMenu?.(e, step.id)}
                    >
                      <div className="flex items-center gap-2">
                        <button
                          type="button"
                          className="shrink-0 cursor-grab touch-none text-muted-foreground active:cursor-grabbing"
                          aria-label={`Drag to reorder step ${stepNumber}: ${step.title || 'Untitled step'}`}
                          {...dragHandleProps}
                        >
                          <GripVertical className="h-4 w-4" />
                        </button>

                        <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-white/[0.10] text-xs font-medium text-muted-foreground">
                          {stepNumber}
                        </span>

                        <span className={cn('shrink-0', config.color)}>
                          <Icon className="h-3.5 w-3.5" />
                        </span>

                        <span
                          className="min-w-0 flex-1 cursor-pointer truncate text-sm text-foreground"
                          onClick={() => setExpandedStepId(step.id)}
                        >
                          {step.title || 'Untitled step'}
                        </span>

                        {step.estimated_minutes && (
                          <span className="shrink-0 text-[10px] text-muted-foreground">
                            ~{step.estimated_minutes}m
                          </span>
                        )}

                        <button
                          onClick={() => setExpandedStepId(step.id)}
                          className="shrink-0 rounded p-1 text-muted-foreground hover:bg-elevated hover:text-foreground"
                        >
                          <ChevronDown className="h-3.5 w-3.5" />
                        </button>

                        <button
                          onClick={() => removeStep(step.id)}
                          className="shrink-0 rounded p-1 text-muted-foreground opacity-0 hover:bg-red-500/20 hover:text-red-400 group-hover:opacity-100"
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </div>

                      {isGhost && (
                        <div className="mt-2 flex gap-2 border-t border-border/50 pt-2">
                          <button
                            onClick={(e) => {
                              e.stopPropagation()
                              // TODO: accept suggestion
                            }}
                            className="flex-1 rounded-md bg-emerald-500/20 px-2 py-1 text-xs text-emerald-400 hover:bg-emerald-500/30 transition-colors"
                          >
                            Accept
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation()
                              // TODO: dismiss suggestion
                            }}
                            className="flex-1 rounded-md bg-rose-500/20 px-2 py-1 text-xs text-rose-400 hover:bg-rose-500/30 transition-colors"
                          >
                            Dismiss
                          </button>
                        </div>
                      )}
                    </div>
                  )}
                </SortableStepWrapper>
              )
            })}
          </div>
        </SortableContext>
      </DndContext>

      {/* Add step button at bottom */}
      <button
        onClick={() => addStep()}
        className="mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-white/20 py-2 text-sm text-muted-foreground transition-colors hover:border-primary/40 hover:bg-elevated/30 hover:text-foreground"
      >
        <Plus className="h-3.5 w-3.5" />
        Add Step
      </button>

      <div ref={scrollTargetRef} />
    </div>
  )
}
