/**
 * Checkout Field Editor - Editor Tab
 * 
 * Main drag-and-drop field editor interface
 */

import { useState, useEffect } from "react"
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  useDraggable,
  useDroppable,
  DragOverlay,
  DragEndEvent,
  DragStartEvent,
} from "@dnd-kit/core"
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ScrollArea } from "@/components/ui/scroll-area"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
// Accordion import removed - not currently used but may be added for conditional logic UI
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { Textarea } from "@/components/ui/textarea"
import { ProIndicator } from "@/components/pro/pro-indicator"
import { 
  GripVertical,
  Plus,
  Trash2,
  Copy,
  Eye,
  EyeOff,
  Settings,
  ChevronDown,
  ChevronUp,
  Type,
  Hash,
  Mail,
  Phone,
  EyeOff as EyeOffIcon,
  Link,
  AlignLeft,
  ListChecks,
  Circle,
  CheckSquare,
  CheckCircle,
  Upload,
  Calendar,
  Clock,
  CalendarClock,
  CalendarDays,
  CalendarRange,
  CalendarCheck,
  Timer,
  Heading,
  Tag,
  FileText,
  Pencil,
  Zap,
  Globe,
  MapPin,
} from "lucide-react"
import { 
  CheckoutField, 
  CheckoutSection, 
  SectionConfig,
  FieldType,
  FieldOption,
  ConditionalLogic,
  fieldTypeDefinitions,
  fieldCategories,
  widthOptions,
  validationPatterns
} from "../../config"
import { usePro } from "@/contexts/pro-context"
import { ConditionalLogicEditor } from "../conditional-logic-editor"

// Icon mapping
const iconMap: Record<string, React.ComponentType<{ className?: string }>> = {
  Type, Hash, Mail, Phone, EyeOff: EyeOffIcon, Link, AlignLeft,
  ChevronDown, ListChecks, Circle, CheckSquare, CheckCircle, Upload,
  Calendar, Clock, CalendarClock, CalendarDays, CalendarRange, CalendarCheck,
  Timer, Heading, Tag, FileText, Settings, Globe, MapPin
}

interface EditorTabProps {
  fields: CheckoutField[]
  sections: SectionConfig[]
  addField: (type: FieldType, section: CheckoutSection) => CheckoutField
  updateField: (id: string, updates: Partial<CheckoutField>) => void
  deleteField: (id: string) => void
  duplicateField: (id: string) => CheckoutField | null
  toggleFieldEnabled: (id: string) => void
  reorderFields: (section: CheckoutSection, fieldIds: string[]) => void
  moveFieldToSection: (fieldId: string, newSection: CheckoutSection) => void
  updateSection: (id: CheckoutSection, updates: Partial<SectionConfig>) => void
  toggleSectionEnabled: (id: CheckoutSection) => void
  editingFieldFromCL?: CheckoutField | null
  clearEditingFieldFromCL?: () => void
}

interface FieldEditorDialogProps {
  field: CheckoutField | null
  allFields: CheckoutField[]
  isOpen: boolean
  isNewField: boolean
  onClose: () => void
  onCancel: () => void
  onSave: (updates: Partial<CheckoutField>) => void
}

// Field Editor Dialog Component
function FieldEditorDialog({ field, allFields, isOpen, isNewField, onClose, onCancel, onSave }: FieldEditorDialogProps) {
  const { isPro } = usePro()
  const [editedField, setEditedField] = useState<Partial<CheckoutField>>({})
  
  // Reset edited state whenever the dialog opens with a different field
  useEffect(() => {
    if (field && isOpen) {
      setEditedField({})
    }
  }, [field?.id, isOpen])

  if (!field) return null

  const currentField = { ...field, ...editedField }
  const fieldDef = fieldTypeDefinitions.find(f => f.type === currentField.type)

  const handleSave = () => {
    onSave(editedField)
    onClose()
  }

  const updateEditedField = <K extends keyof CheckoutField>(key: K, value: CheckoutField[K]) => {
    setEditedField(prev => ({ ...prev, [key]: value }))
  }

  const updateValidation = <K extends keyof CheckoutField['validation']>(
    key: K, 
    value: CheckoutField['validation'][K]
  ) => {
    setEditedField(prev => ({
      ...prev,
      validation: { ...(prev.validation || field.validation), [key]: value }
    }))
  }

  const addOption = () => {
    const options = currentField.options || []
    const newOption: FieldOption = {
      value: `option_${options.length + 1}`,
      label: `Option ${options.length + 1}`
    }
    updateEditedField('options', [...options, newOption])
  }

  const updateOption = (index: number, updates: Partial<FieldOption>) => {
    const options = [...(currentField.options || [])]
    options[index] = { ...options[index], ...updates }
    updateEditedField('options', options)
  }

  const removeOption = (index: number) => {
    const options = (currentField.options || []).filter((_, i) => i !== index)
    updateEditedField('options', options)
  }

  return (
    <Dialog open={isOpen} onOpenChange={(open) => { if (!open) onCancel() }}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Pencil className="h-5 w-5" />
            Edit Field: {currentField.label}
          </DialogTitle>
          <DialogDescription>
            Configure the field properties, validation, and conditional logic.
          </DialogDescription>
        </DialogHeader>

        <ScrollArea className="flex-1 pr-4">
          <Tabs defaultValue="general" className="w-full">
            <TabsList className={`grid w-full ${isPro ? 'grid-cols-5' : 'grid-cols-4'}`}>
              <TabsTrigger value="general">General</TabsTrigger>
              <TabsTrigger value="validation">Validation</TabsTrigger>
              <TabsTrigger value="options" disabled={!fieldDef?.hasOptions}>Options</TabsTrigger>
              <TabsTrigger value="advanced">Advanced</TabsTrigger>
              {isPro && (
                <TabsTrigger value="conditional-logic" className="flex items-center gap-1">
                  <Zap className="h-3 w-3" />
                  Logic
                </TabsTrigger>
              )}
            </TabsList>

            <TabsContent value="general" className="space-y-4 mt-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Label</Label>
                  <Input
                    value={currentField.label}
                    onChange={(e) => updateEditedField('label', e.target.value)}
                  />
                </div>
                <div className="space-y-2">
                  <Label>Field Key</Label>
                  <Input
                    value={currentField.key}
                    onChange={(e) => updateEditedField('key', e.target.value)}
                    disabled={currentField.isCore}
                  />
                </div>
              </div>

              {fieldDef?.hasPlaceholder && (
                <div className="space-y-2">
                  <Label>Placeholder</Label>
                  <Input
                    value={currentField.placeholder || ''}
                    onChange={(e) => updateEditedField('placeholder', e.target.value)}
                  />
                </div>
              )}

              <div className="space-y-2">
                <Label>Description</Label>
                <Textarea
                  value={currentField.description || ''}
                  onChange={(e) => updateEditedField('description', e.target.value)}
                  rows={2}
                />
              </div>

              {fieldDef?.hasDefaultValue && (
                <div className="space-y-2">
                  <Label>Default Value</Label>
                  <Input
                    value={currentField.defaultValue || ''}
                    onChange={(e) => updateEditedField('defaultValue', e.target.value)}
                  />
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Width</Label>
                  <Select
                    value={currentField.width}
                    onValueChange={(v) => updateEditedField('width', v as CheckoutField['width'])}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {widthOptions.map(opt => (
                        <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>CSS Class</Label>
                  <Input
                    value={currentField.cssClass || ''}
                    onChange={(e) => updateEditedField('cssClass', e.target.value)}
                    placeholder="custom-class"
                  />
                </div>
              </div>

              <div className="flex items-center justify-between">
                <Label>Field Enabled</Label>
                <Switch
                  checked={currentField.enabled}
                  onCheckedChange={(v) => updateEditedField('enabled', v)}
                />
              </div>
            </TabsContent>

            <TabsContent value="validation" className="space-y-4 mt-4">
              <div className="flex items-center justify-between">
                <Label>Required Field</Label>
                <Switch
                  checked={currentField.validation?.required || false}
                  onCheckedChange={(v) => updateValidation('required', v)}
                />
              </div>

              {(currentField.type === 'text' || currentField.type === 'textarea') && (
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Min Length</Label>
                    <Input
                      type="number"
                      value={currentField.validation?.minLength || ''}
                      onChange={(e) => updateValidation('minLength', e.target.value ? parseInt(e.target.value) : undefined)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Max Length</Label>
                    <Input
                      type="number"
                      value={currentField.validation?.maxLength || ''}
                      onChange={(e) => updateValidation('maxLength', e.target.value ? parseInt(e.target.value) : undefined)}
                    />
                  </div>
                </div>
              )}

              {currentField.type === 'number' && (
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Min Value</Label>
                    <Input
                      type="number"
                      value={currentField.validation?.min || ''}
                      onChange={(e) => updateValidation('min', e.target.value ? parseFloat(e.target.value) : undefined)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Max Value</Label>
                    <Input
                      type="number"
                      value={currentField.validation?.max || ''}
                      onChange={(e) => updateValidation('max', e.target.value ? parseFloat(e.target.value) : undefined)}
                    />
                  </div>
                </div>
              )}

              <div className="space-y-2">
                <Label>Validation Pattern</Label>
                <Select
                  value={currentField.validation?.pattern || ''}
                  onValueChange={(v) => updateValidation('pattern', v === 'none' ? undefined : v)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select pattern" />
                  </SelectTrigger>
                  <SelectContent>
                    {validationPatterns.map(p => (
                      <SelectItem key={p.value} value={p.value || 'none'}>{p.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label>Validation Error Message</Label>
                <Input
                  value={currentField.validation?.patternMessage || ''}
                  onChange={(e) => updateValidation('patternMessage', e.target.value)}
                  placeholder="Please enter a valid value"
                />
              </div>
            </TabsContent>

            <TabsContent value="options" className="space-y-4 mt-4">
              {fieldDef?.hasOptions && (
                <>
                  <div className="flex items-center justify-between">
                    <Label>Field Options</Label>
                    <Button size="sm" variant="outline" onClick={addOption}>
                      <Plus className="h-4 w-4 mr-1" />
                      Add Option
                    </Button>
                  </div>

                  <div className="space-y-2">
                    {(currentField.options || []).map((option, index) => (
                      <div key={index} className="flex items-center gap-2 p-2 border rounded-lg">
                        <GripVertical className="h-4 w-4 text-muted-foreground cursor-grab" />
                        <Input
                          value={option.label}
                          onChange={(e) => updateOption(index, { label: e.target.value })}
                          placeholder="Label"
                          className="flex-1"
                        />
                        <Input
                          value={option.value}
                          onChange={(e) => updateOption(index, { value: e.target.value })}
                          placeholder="Value"
                          className="w-32"
                        />
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                size="icon"
                                variant={option.isDefault ? "default" : "ghost"}
                                onClick={() => {
                                  const options = (currentField.options || []).map((o, i) => ({
                                    ...o,
                                    isDefault: i === index ? !o.isDefault : false
                                  }))
                                  updateEditedField('options', options)
                                }}
                              >
                                <CheckSquare className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>Set as default</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={() => removeOption(index)}
                        >
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    ))}
                  </div>

                  {(!currentField.options || currentField.options.length === 0) && (
                    <p className="text-sm text-muted-foreground text-center py-4">
                      No options added yet. Click "Add Option" to create options.
                    </p>
                  )}
                </>
              )}
            </TabsContent>

            <TabsContent value="advanced" className="space-y-4 mt-4">
              <div className="space-y-2">
                <Label>Autocomplete</Label>
                <Input
                  value={currentField.autocomplete || ''}
                  onChange={(e) => updateEditedField('autocomplete', e.target.value)}
                  placeholder="e.g., given-name, email, tel"
                />
              </div>

              {currentField.type === 'textarea' && (
                <div className="space-y-2">
                  <Label>Rows</Label>
                  <Input
                    type="number"
                    value={currentField.rows || 4}
                    onChange={(e) => updateEditedField('rows', parseInt(e.target.value) || 4)}
                    min={2}
                    max={20}
                  />
                </div>
              )}

              {currentField.type === 'file' && (
                <>
                  <div className="space-y-2">
                    <Label>Allowed File Types</Label>
                    <Input
                      value={(currentField.allowedFileTypes || []).join(',')}
                      onChange={(e) => updateEditedField('allowedFileTypes', e.target.value.split(',').map(s => s.trim()))}
                      placeholder="jpg,png,pdf"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Max File Size (MB)</Label>
                    <Input
                      type="number"
                      value={currentField.maxFileSize || 5}
                      onChange={(e) => updateEditedField('maxFileSize', parseInt(e.target.value) || 5)}
                    />
                  </div>
                </>
              )}

              {(currentField.type === 'date' || currentField.type === 'datepicker') && (
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Min Date</Label>
                    <Input
                      type="date"
                      value={currentField.minDate || ''}
                      onChange={(e) => updateEditedField('minDate', e.target.value)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Max Date</Label>
                    <Input
                      type="date"
                      value={currentField.maxDate || ''}
                      onChange={(e) => updateEditedField('maxDate', e.target.value)}
                    />
                  </div>
                </div>
              )}

              <div className="space-y-2">
                <Label>Input Mask</Label>
                <Input
                  value={currentField.inputMask || ''}
                  onChange={(e) => updateEditedField('inputMask', e.target.value)}
                  placeholder="e.g., (999) 999-9999"
                />
                <p className="text-xs text-muted-foreground">
                  Use 9 for numbers, a for letters, * for any character
                </p>
              </div>
            </TabsContent>

            {isPro && (
              <TabsContent value="conditional-logic" className="space-y-4 mt-4">
                <ConditionalLogicEditor
                  field={currentField as CheckoutField}
                  allFields={allFields}
                  conditionalLogic={currentField.conditionalLogic}
                  onChange={(cl: ConditionalLogic) => updateEditedField('conditionalLogic', cl)}
                />
              </TabsContent>
            )}
          </Tabs>
        </ScrollArea>

        <DialogFooter className="mt-4">
          <Button variant="outline" onClick={onCancel}>
            {isNewField ? 'Discard' : 'Cancel'}
          </Button>
          <Button onClick={handleSave}>
            {isNewField ? 'Add Field' : 'Save Changes'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

// Field Card Component
interface FieldCardProps {
  field: CheckoutField
  onEdit: () => void
  onDelete: () => void
  onDuplicate: () => void
  onToggleEnabled: () => void
  isDragging?: boolean
  dragHandleProps?: React.HTMLAttributes<HTMLDivElement>
}

function FieldCard({ field, onEdit, onDelete, onDuplicate, onToggleEnabled, isDragging, dragHandleProps }: FieldCardProps) {
  const fieldDef = fieldTypeDefinitions.find(f => f.type === field.type)
  const IconComponent = fieldDef ? iconMap[fieldDef.icon] : Type

  return (
    <div 
      className={`
        flex items-center gap-3 p-3 bg-background border rounded-lg group
        ${!field.enabled ? 'opacity-50' : ''}
        ${isDragging ? 'shadow-lg ring-2 ring-primary z-50' : 'hover:shadow-sm'}
        transition-all
      `}
    >
      <div 
        className="cursor-grab active:cursor-grabbing hover:bg-muted p-1 rounded touch-none"
        {...dragHandleProps}
      >
        <GripVertical className="h-4 w-4 text-muted-foreground" />
      </div>

      <div className="flex items-center gap-2">
        {IconComponent && <IconComponent className="h-4 w-4 text-muted-foreground" />}
      </div>

      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="font-medium truncate">{field.label}</span>
          {field.validation.required && (
            <Badge variant="destructive" className="text-xs">Required</Badge>
          )}
          {field.isCore && (
            <Badge variant="secondary" className="text-xs">Core</Badge>
          )}
          {field.conditionalLogic?.enabled && field.conditionalLogic.rules.length > 0 && (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger>
                  <Badge variant="outline" className="text-xs gap-1 px-1.5">
                    <Zap className="h-3 w-3 text-amber-500" />
                  </Badge>
                </TooltipTrigger>
                <TooltipContent>
                  Conditional logic active ({field.conditionalLogic.rules.length} rule{field.conditionalLogic.rules.length !== 1 ? 's' : ''})
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          )}
        </div>
        <div className="flex items-center gap-2 text-xs text-muted-foreground">
          <span>{fieldDef?.label || field.type}</span>
          <span>•</span>
          <span className="font-mono">{field.key}</span>
          <span>•</span>
          <span>{field.width === 'full' ? '100%' : field.width === 'half' ? '50%' : '33%'}</span>
        </div>
      </div>

      <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button 
                size="icon" 
                variant="ghost" 
                onClick={onToggleEnabled}
              >
                {field.enabled ? (
                  <Eye className="h-4 w-4" />
                ) : (
                  <EyeOff className="h-4 w-4" />
                )}
              </Button>
            </TooltipTrigger>
            <TooltipContent>
              {field.enabled 
                  ? 'Disable' 
                  : 'Enable'
              }
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>

        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button size="icon" variant="ghost" onClick={onEdit}>
                <Pencil className="h-4 w-4" />
              </Button>
            </TooltipTrigger>
            <TooltipContent>Edit</TooltipContent>
          </Tooltip>
        </TooltipProvider>

        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button size="icon" variant="ghost" onClick={onDuplicate}>
                <Copy className="h-4 w-4" />
              </Button>
            </TooltipTrigger>
            <TooltipContent>Duplicate</TooltipContent>
          </Tooltip>
        </TooltipProvider>

        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button 
                size="icon" 
                variant="ghost" 
                onClick={onDelete}
                disabled={field.isCore}
              >
                <Trash2 className="h-4 w-4 text-destructive" />
              </Button>
            </TooltipTrigger>
            <TooltipContent>{field.isCore ? 'Core fields cannot be deleted' : 'Delete'}</TooltipContent>
          </Tooltip>
        </TooltipProvider>
      </div>
    </div>
  )
}

// Sortable Field Card Wrapper
interface SortableFieldCardProps {
  field: CheckoutField
  onEdit: () => void
  onDelete: () => void
  onDuplicate: () => void
  onToggleEnabled: () => void
}

function SortableFieldCard({ field, onEdit, onDelete, onDuplicate, onToggleEnabled }: SortableFieldCardProps) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: field.id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  }

  return (
    <div ref={setNodeRef} style={style} {...attributes}>
      <FieldCard
        field={field}
        onEdit={onEdit}
        onDelete={onDelete}
        onDuplicate={onDuplicate}
        onToggleEnabled={onToggleEnabled}
        isDragging={isDragging}
        dragHandleProps={listeners}
      />
    </div>
  )
}

// Draggable Quick Add Field Type
function DraggableFieldType({ type, label, icon }: { type: FieldType; label: string; icon: string }) {
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
    id: `quick-add-${type}`,
    data: { type, isQuickAdd: true },
  })
  const Icon = iconMap[icon] || Type

  return (
    <div ref={setNodeRef} {...listeners} {...attributes}>
      <Button
        variant="outline"
        size="sm"
        className={`cursor-grab active:cursor-grabbing select-none ${isDragging ? 'opacity-50' : ''}`}
      >
        <Icon className="h-4 w-4 mr-1" />
        {label}
      </Button>
    </div>
  )
}

// Section Card Component
interface SectionCardProps {
  section: SectionConfig
  fields: CheckoutField[]
  onToggleEnabled: () => void
  onUpdateSection: (updates: Partial<SectionConfig>) => void
  onEditField: (field: CheckoutField) => void
  onDeleteField: (id: string) => void
  onDuplicateField: (id: string) => void
  onToggleFieldEnabled: (id: string) => void
  onAddField: (type: FieldType) => void
  onReorderFields: (fieldIds: string[]) => void
  isDropTarget?: boolean
}

function SectionCard({
  section,
  fields,
  onToggleEnabled,
  onUpdateSection: _onUpdateSection,
  onEditField,
  onDeleteField,
  onDuplicateField,
  onToggleFieldEnabled,
  onAddField,
  onReorderFields,
  isDropTarget = false,
}: SectionCardProps) {
  const { setNodeRef: setDropRef, isOver } = useDroppable({
    id: `section-drop-${section.id}`,
    data: { sectionId: section.id },
  })
  const [isExpanded, setIsExpanded] = useState(true)
  const [showAddField, setShowAddField] = useState(false)

  const sortedFields = [...fields].sort((a, b) => a.priority - b.priority)
  const fieldIds = sortedFields.map(f => f.id)

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

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event
    
    if (over && active.id !== over.id) {
      const oldIndex = fieldIds.indexOf(active.id as string)
      const newIndex = fieldIds.indexOf(over.id as string)
      const newOrder = arrayMove(fieldIds, oldIndex, newIndex)
      onReorderFields(newOrder)
    }
  }

  return (
    <Card
      ref={setDropRef}
      className={`transition-all duration-200 ${
        !section.enabled ? 'opacity-60' : ''
      } ${
        isDropTarget && isOver
          ? 'ring-2 ring-primary ring-offset-2 bg-primary/5'
          : isDropTarget
          ? 'ring-1 ring-dashed ring-muted-foreground/30'
          : ''
      }`}
    >
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Button
              size="icon"
              variant="ghost"
              onClick={() => setIsExpanded(!isExpanded)}
            >
              {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
            </Button>
            <div>
              <CardTitle className="text-base">
                {section.title}
              </CardTitle>
              <CardDescription>
                {sortedFields.length} field{sortedFields.length !== 1 ? 's' : ''} • 
                {sortedFields.filter(f => f.enabled).length} enabled
              </CardDescription>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button size="icon" variant="ghost" onClick={onToggleEnabled}>
                    {section.enabled ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
                  </Button>
                </TooltipTrigger>
                <TooltipContent>{section.enabled ? 'Disable section' : 'Enable section'}</TooltipContent>
              </Tooltip>
            </TooltipProvider>
            <Button size="sm" variant="outline" onClick={() => setShowAddField(true)}>
              <Plus className="h-4 w-4 mr-1" />
              Add Field
            </Button>
          </div>
        </div>
      </CardHeader>

      {isExpanded && (
        <CardContent className="space-y-2">
          {sortedFields.length > 0 ? (
            <DndContext
              sensors={sensors}
              collisionDetection={closestCenter}
              onDragEnd={handleDragEnd}
            >
              <SortableContext items={fieldIds} strategy={verticalListSortingStrategy}>
                {sortedFields.map(field => (
                  <SortableFieldCard
                    key={field.id}
                    field={field}
                    onEdit={() => onEditField(field)}
                    onDelete={() => onDeleteField(field.id)}
                    onDuplicate={() => onDuplicateField(field.id)}
                    onToggleEnabled={() => onToggleFieldEnabled(field.id)}
                  />
                ))}
              </SortableContext>
            </DndContext>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              <p>No fields in this section.</p>
              <Button 
                variant="link" 
                className="mt-2"
                onClick={() => setShowAddField(true)}
              >
                Add your first field
              </Button>
            </div>
          )}
        </CardContent>
      )}

      {/* Add Field Dialog */}
      <Dialog open={showAddField} onOpenChange={setShowAddField}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Add Field to {section.title}</DialogTitle>
            <DialogDescription>
              Choose a field type to add to this section.
            </DialogDescription>
          </DialogHeader>

          <AddFieldDialogContent 
            onAddField={(type) => {
              onAddField(type)
              setShowAddField(false)
            }}
          />
        </DialogContent>
      </Dialog>
    </Card>
  )
}

// Separate component for Add Field Dialog content
function AddFieldDialogContent({ onAddField }: { onAddField: (type: FieldType) => void }) {
  const { isPro } = usePro()

  return (
    <div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto">
      {fieldCategories
        .filter(category => isPro || category.id === 'basic')
        .map(category => (
        <div key={category.id} className="col-span-2">
          <h4 className="text-sm font-medium text-muted-foreground mb-2 mt-4 first:mt-0 flex items-center gap-2">
            {category.label}
          </h4>
          <div className="grid grid-cols-2 gap-2">
            {fieldTypeDefinitions
              .filter(f => f.category === category.id)
              .filter(f => isPro || !f.isPro)
              .map(fieldType => {
                const Icon = iconMap[fieldType.icon] || Type
                return (
                  <Button
                    key={fieldType.type}
                    variant="outline"
                    className="justify-start h-auto py-3"
                    onClick={() => onAddField(fieldType.type)}
                  >
                    <Icon className="h-4 w-4 mr-2" />
                    <span className="flex min-w-0 items-center gap-1.5">
                      <span className="truncate">{fieldType.label}</span>
                      {fieldType.isPro && <ProIndicator size="sm" />}
                    </span>
                  </Button>
                )
              })}
          </div>
        </div>
      ))}
    </div>
  )
}

export function EditorTab({
  fields,
  sections,
  addField,
  updateField,
  deleteField,
  duplicateField,
  toggleFieldEnabled,
  reorderFields,
  moveFieldToSection: _moveFieldToSection,
  updateSection,
  toggleSectionEnabled,
  editingFieldFromCL,
  clearEditingFieldFromCL
}: EditorTabProps) {
  const [editingField, setEditingField] = useState<CheckoutField | null>(null)
  const [isNewField, setIsNewField] = useState(false)

  // Handle field editing triggered from the Conditional Logic tab after render.
  useEffect(() => {
    if (editingFieldFromCL && !editingField) {
      setEditingField(editingFieldFromCL)
      setIsNewField(false)
      clearEditingFieldFromCL?.()
    }
  }, [editingFieldFromCL, editingField, clearEditingFieldFromCL])

  const getFieldsForSection = (sectionId: CheckoutSection) => {
    return fields.filter(f => f.section === sectionId)
  }

  const handleAddField = (section: CheckoutSection) => (type: FieldType) => {
    const newField = addField(type, section)
    setEditingField(newField)
    setIsNewField(true)
  }
  
  const [isDraggingQuickAdd, setIsDraggingQuickAdd] = useState(false)
  const [draggingFieldType, setDraggingFieldType] = useState<FieldType | null>(null)

  const handleDialogClose = () => {
    setEditingField(null)
    setIsNewField(false)
  }

  const handleDialogCancel = () => {
    // If this was a new field that hasn't been saved, delete it
    if (isNewField && editingField) {
      deleteField(editingField.id)
    }
    setEditingField(null)
    setIsNewField(false)
  }

  // Get only free field types for quick add
  const quickAddFields = fieldTypeDefinitions.filter(f => !f.isPro).slice(0, 8)

  // Top-level DnD sensors for Quick Add drag
  const quickAddSensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 5,
      },
    })
  )

  const handleQuickAddDragStart = (event: DragStartEvent) => {
    const { active } = event
    if (active.data.current?.isQuickAdd) {
      setIsDraggingQuickAdd(true)
      setDraggingFieldType(active.data.current.type as FieldType)
    }
  }

  const handleQuickAddDragEnd = (event: DragEndEvent) => {
    const { active, over } = event
    setIsDraggingQuickAdd(false)
    setDraggingFieldType(null)

    if (!over || !active.data.current?.isQuickAdd) return

    // Check if dropped over a section
    const sectionId = over.data.current?.sectionId as CheckoutSection | undefined
    if (!sectionId) return

    const fieldType = active.data.current.type as FieldType
    const newField = addField(fieldType, sectionId)
    setEditingField(newField)
    setIsNewField(true)
  }

  // Get the label for the currently dragged type (for overlay)
  const draggingFieldDef = draggingFieldType
    ? fieldTypeDefinitions.find(f => f.type === draggingFieldType)
    : null
  const DraggingIcon = draggingFieldDef ? (iconMap[draggingFieldDef.icon] || Type) : Type

  return (
    <DndContext
      sensors={quickAddSensors}
      onDragStart={handleQuickAddDragStart}
      onDragEnd={handleQuickAddDragEnd}
    >
      <div className="space-y-6">
        {/* Field Type Toolbox */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Plus className="h-5 w-5" />
              Quick Add Fields
            </CardTitle>
            <CardDescription>
              Drag a field type and drop it into any section below.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-2">
              {quickAddFields.map(fieldType => (
                <DraggableFieldType
                  key={fieldType.type}
                  type={fieldType.type}
                  label={fieldType.label}
                  icon={fieldType.icon}
                />
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Section Cards - 2 Column Layout */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          {sections.map(section => (
            <SectionCard
              key={section.id}
              section={section}
              fields={getFieldsForSection(section.id)}
              onToggleEnabled={() => toggleSectionEnabled(section.id)}
              onUpdateSection={(updates) => updateSection(section.id, updates)}
              onEditField={setEditingField}
              onDeleteField={deleteField}
              onDuplicateField={duplicateField}
              onToggleFieldEnabled={toggleFieldEnabled}
              onAddField={handleAddField(section.id)}
              onReorderFields={(fieldIds) => reorderFields(section.id, fieldIds)}
              isDropTarget={isDraggingQuickAdd}
            />
          ))}
        </div>

        {/* Field Editor Dialog */}
        <FieldEditorDialog
          field={editingField}
          allFields={fields}
          isOpen={!!editingField}
          isNewField={isNewField}
          onClose={handleDialogClose}
          onCancel={handleDialogCancel}
          onSave={(updates) => {
            if (editingField) {
              updateField(editingField.id, updates)
            }
          }}
        />
      </div>

      {/* Drag Overlay for Quick Add */}
      <DragOverlay dropAnimation={null}>
        {isDraggingQuickAdd && draggingFieldDef ? (
          <Button
            variant="outline"
            size="sm"
            className="shadow-lg ring-2 ring-primary pointer-events-none"
          >
            <DraggingIcon className="h-4 w-4 mr-1" />
            {draggingFieldDef.label}
          </Button>
        ) : null}
      </DragOverlay>
    </DndContext>
  )
}
