/**
 * Registration Form Editor Tab
 * 
 * Field management interface with drag-and-drop reordering
 */

import { useState, useRef, useEffect } from "react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import {
  Plus,
  GripVertical,
  Pencil,
  Copy,
  Trash2,
  MoreVertical,
  EyeOff,
  Lock,
  Type,
  Mail,
  Phone,
  Link,
  Hash,
  AlignLeft,
  ChevronDown,
  ListChecks,
  Circle,
  CheckSquare,
  CheckCircle,
  Calendar,
  CalendarClock,
  Upload,
  Heading,
  FileText,
  Minus,
  X,
} from "lucide-react"
import {
  RegistrationField,
  RegistrationFieldType,
  registrationFieldTypes,
  getFieldTypesByCategory,
  FieldOption,
} from "../../config"

// Icon mapping for field types
const fieldTypeIcons: Record<string, React.ComponentType<{ className?: string }>> = {
  Type,
  Mail,
  Lock,
  Phone,
  Link,
  Hash,
  AlignLeft,
  ChevronDown,
  ListChecks,
  Circle,
  CheckSquare,
  CheckCircle,
  Calendar,
  CalendarClock,
  Upload,
  EyeOff,
  Heading,
  FileText,
  Minus,
}

interface EditorTabProps {
  fields: RegistrationField[]
  onAddField: (type: RegistrationFieldType) => RegistrationField
  onUpdateField: (id: string, updates: Partial<RegistrationField>) => void
  onDeleteField: (id: string) => void
  onDuplicateField: (id: string) => void
  onToggleFieldEnabled: (id: string) => void
  onReorderFields: (fields: RegistrationField[]) => void
}

export function EditorTab({
  fields,
  onAddField,
  onUpdateField,
  onDeleteField,
  onDuplicateField,
  onToggleFieldEnabled,
  onReorderFields,
}: EditorTabProps) {
  const [editingField, setEditingField] = useState<RegistrationField | null>(null)
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
  const [draggedField, setDraggedField] = useState<string | null>(null)

  // Handle drag start
  const handleDragStart = (e: React.DragEvent, fieldId: string) => {
    setDraggedField(fieldId)
    e.dataTransfer.effectAllowed = 'move'
  }

  // Handle drag over
  const handleDragOver = (e: React.DragEvent, fieldId: string) => {
    e.preventDefault()
    if (!draggedField || draggedField === fieldId) return

    const newFields = [...fields]
    const draggedIndex = newFields.findIndex(f => f.id === draggedField)
    const targetIndex = newFields.findIndex(f => f.id === fieldId)

    if (draggedIndex !== -1 && targetIndex !== -1) {
      const [draggedItem] = newFields.splice(draggedIndex, 1)
      newFields.splice(targetIndex, 0, draggedItem)
      onReorderFields(newFields)
    }
  }

  // Handle drag end
  const handleDragEnd = () => {
    setDraggedField(null)
  }

  // Get icon component for field type
  const getFieldIcon = (iconName: string) => {
    const Icon = fieldTypeIcons[iconName]
    return Icon ? <Icon className="h-4 w-4" /> : <Type className="h-4 w-4" />
  }

  // Get field type definition
  const getFieldTypeDef = (type: RegistrationFieldType) => {
    return registrationFieldTypes.find(ft => ft.type === type)
  }

  return (
    <div className="space-y-4">
      {/* Add Field Button */}
      <div className="flex justify-between items-center">
        <div>
          <h3 className="text-lg font-medium">Registration Fields</h3>
          <p className="text-sm text-muted-foreground">
            Drag and drop to reorder. Click to edit field properties.
          </p>
        </div>
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              Add Field
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle>Add New Field</DialogTitle>
              <DialogDescription>
                Select the type of field you want to add to the registration form.
              </DialogDescription>
            </DialogHeader>
            <ScrollArea className="max-h-[400px] pr-4">
              <div className="space-y-4">
                {/* Basic Fields */}
                <div>
                  <h4 className="text-sm font-medium mb-2">Basic Fields</h4>
                  <div className="grid grid-cols-2 gap-2">
                    {getFieldTypesByCategory('basic').map((fieldType) => (
                      <Button
                        key={fieldType.type}
                        variant="outline"
                        className="justify-start h-auto py-3"
                        onClick={() => {
                          const newField = onAddField(fieldType.type)
                          setIsAddDialogOpen(false)
                          setEditingField(newField)
                        }}
                      >
                        {getFieldIcon(fieldType.icon)}
                        <div className="ml-2 text-left">
                          <div className="font-medium">{fieldType.label}</div>
                          <div className="text-xs text-muted-foreground">{fieldType.description}</div>
                        </div>
                      </Button>
                    ))}
                  </div>
                </div>

                <Separator />

                {/* Selection Fields */}
                <div>
                  <h4 className="text-sm font-medium mb-2">Selection Fields</h4>
                  <div className="grid grid-cols-2 gap-2">
                    {getFieldTypesByCategory('selection').map((fieldType) => (
                      <Button
                        key={fieldType.type}
                        variant="outline"
                        className="justify-start h-auto py-3"
                        onClick={() => {
                          const newField = onAddField(fieldType.type)
                          setIsAddDialogOpen(false)
                          setEditingField(newField)
                        }}
                      >
                        {getFieldIcon(fieldType.icon)}
                        <div className="ml-2 text-left">
                          <div className="font-medium">{fieldType.label}</div>
                          <div className="text-xs text-muted-foreground">{fieldType.description}</div>
                        </div>
                      </Button>
                    ))}
                  </div>
                </div>

                <Separator />

                {/* DateTime Fields */}
                <div>
                  <h4 className="text-sm font-medium mb-2">Date & Time Fields</h4>
                  <div className="grid grid-cols-2 gap-2">
                    {getFieldTypesByCategory('datetime').map((fieldType) => (
                      <Button
                        key={fieldType.type}
                        variant="outline"
                        className="justify-start h-auto py-3"
                        onClick={() => {
                          const newField = onAddField(fieldType.type)
                          setIsAddDialogOpen(false)
                          setEditingField(newField)
                        }}
                      >
                        {getFieldIcon(fieldType.icon)}
                        <div className="ml-2 text-left">
                          <div className="font-medium">{fieldType.label}</div>
                          <div className="text-xs text-muted-foreground">{fieldType.description}</div>
                        </div>
                      </Button>
                    ))}
                  </div>
                </div>

                <Separator />

                {/* Content Fields */}
                <div>
                  <h4 className="text-sm font-medium mb-2">Content & Layout</h4>
                  <div className="grid grid-cols-2 gap-2">
                    {getFieldTypesByCategory('content').map((fieldType) => (
                      <Button
                        key={fieldType.type}
                        variant="outline"
                        className="justify-start h-auto py-3"
                        onClick={() => {
                          const newField = onAddField(fieldType.type)
                          setIsAddDialogOpen(false)
                          setEditingField(newField)
                        }}
                      >
                        {getFieldIcon(fieldType.icon)}
                        <div className="ml-2 text-left">
                          <div className="font-medium">{fieldType.label}</div>
                          <div className="text-xs text-muted-foreground">{fieldType.description}</div>
                        </div>
                      </Button>
                    ))}
                  </div>
                </div>

                <Separator />

                {/* Special Fields */}
                <div>
                  <h4 className="text-sm font-medium mb-2">Special Fields</h4>
                  <div className="grid grid-cols-2 gap-2">
                    {getFieldTypesByCategory('special').map((fieldType) => (
                      <Button
                        key={fieldType.type}
                        variant="outline"
                        className="justify-start h-auto py-3"
                        onClick={() => {
                          const newField = onAddField(fieldType.type)
                          setIsAddDialogOpen(false)
                          setEditingField(newField)
                        }}
                      >
                        {getFieldIcon(fieldType.icon)}
                        <div className="ml-2 text-left">
                          <div className="font-medium">{fieldType.label}</div>
                          <div className="text-xs text-muted-foreground">{fieldType.description}</div>
                        </div>
                      </Button>
                    ))}
                  </div>
                </div>
              </div>
            </ScrollArea>
          </DialogContent>
        </Dialog>
      </div>

      {/* Fields List */}
      <Card>
        <CardContent className="p-0">
          <div className="divide-y">
            {fields.map((field) => {
              const fieldTypeDef = getFieldTypeDef(field.type)
              return (
                <div
                  key={field.id}
                  draggable={!field.isCore}
                  onDragStart={(e) => handleDragStart(e, field.id)}
                  onDragOver={(e) => handleDragOver(e, field.id)}
                  onDragEnd={handleDragEnd}
                  className={`flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors ${
                    draggedField === field.id ? 'opacity-50' : ''
                  } ${!field.enabled ? 'opacity-60' : ''}`}
                >
                  {/* Drag Handle */}
                  <div className={`cursor-grab ${field.isCore ? 'invisible' : ''}`}>
                    <GripVertical className="h-4 w-4 text-muted-foreground" />
                  </div>

                  {/* Field Icon */}
                  <div className="flex-shrink-0">
                    {fieldTypeDef && getFieldIcon(fieldTypeDef.icon)}
                  </div>

                  {/* Field Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="font-medium truncate">{field.label}</span>
                      {field.isCore && (
                        <Badge variant="secondary" className="text-xs">Core</Badge>
                      )}
                      {field.validation.required && (
                        <Badge variant="outline" className="text-xs text-red-600 border-red-200">Required</Badge>
                      )}
                    </div>
                    <div className="text-xs text-muted-foreground flex items-center gap-2">
                      <span>{fieldTypeDef?.label}</span>
                      <span>•</span>
                      <span className="font-mono">{field.key}</span>
                      <span>•</span>
                      <span>{field.width}</span>
                    </div>
                  </div>

                  {/* Context Badges */}
                  <div className="flex gap-1">
                    {field.showOn.includes('wordpress') && (
                      <Badge variant="outline" className="text-xs">WP</Badge>
                    )}
                    {field.showOn.includes('woocommerce') && (
                      <Badge variant="outline" className="text-xs">WC</Badge>
                    )}
                  </div>

                  {/* Enable/Disable Toggle */}
                  <Switch
                    checked={field.enabled}
                    onCheckedChange={() => onToggleFieldEnabled(field.id)}
                    disabled={field.isCore && ['user_login', 'user_email'].includes(field.key)}
                  />

                  {/* Actions Menu */}
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon">
                        <MoreVertical className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuLabel>Actions</DropdownMenuLabel>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem onClick={() => setEditingField(field)}>
                        <Pencil className="mr-2 h-4 w-4" />
                        Edit
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => onDuplicateField(field.id)}>
                        <Copy className="mr-2 h-4 w-4" />
                        Duplicate
                      </DropdownMenuItem>
                      {!field.isCore && (
                        <>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            className="text-red-600"
                            onClick={() => onDeleteField(field.id)}
                          >
                            <Trash2 className="mr-2 h-4 w-4" />
                            Delete
                          </DropdownMenuItem>
                        </>
                      )}
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              )
            })}
          </div>
        </CardContent>
      </Card>

      {/* Edit Field Dialog */}
      {editingField && (
        <FieldEditDialog
          field={editingField}
          onSave={(updates) => {
            onUpdateField(editingField.id, updates)
            setEditingField(null)
          }}
          onClose={() => setEditingField(null)}
        />
      )}
    </div>
  )
}

// Field Edit Dialog Component
interface FieldEditDialogProps {
  field: RegistrationField
  onSave: (updates: Partial<RegistrationField>) => void
  onClose: () => void
}

function FieldEditDialog({ field, onSave, onClose }: FieldEditDialogProps) {
  const [editedField, setEditedField] = useState<RegistrationField>({ ...field })
  const fieldTypeDef = registrationFieldTypes.find(ft => ft.type === field.type)
  const optionsEndRef = useRef<HTMLDivElement>(null)
  const prevOptionsCountRef = useRef((field.options || []).length)

  // Auto-scroll when a new option is added
  useEffect(() => {
    const currentCount = (editedField.options || []).length
    if (currentCount > prevOptionsCountRef.current) {
      optionsEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
    }
    prevOptionsCountRef.current = currentCount
  }, [editedField.options?.length])

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

  const updateOption = (index: number, updates: Partial<FieldOption>) => {
    const newOptions = [...(editedField.options || [])]
    newOptions[index] = { ...newOptions[index], ...updates }
    setEditedField({ ...editedField, options: newOptions })
  }

  const addOption = () => {
    const newOptions = [...(editedField.options || [])]
    newOptions.push({ value: `option_${newOptions.length + 1}`, label: `Option ${newOptions.length + 1}` })
    setEditedField({ ...editedField, options: newOptions })
  }

  const removeOption = (index: number) => {
    const newOptions = [...(editedField.options || [])]
    newOptions.splice(index, 1)
    setEditedField({ ...editedField, options: newOptions })
  }

  return (
    <Dialog open={true} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>Edit Field</DialogTitle>
          <DialogDescription>
            Configure the properties for this {fieldTypeDef?.label} field.
          </DialogDescription>
        </DialogHeader>

        <ScrollArea className="max-h-[60vh] pr-4">
          <div className="space-y-4">
            {/* Basic Properties */}
            <div className="grid gap-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="label">Label</Label>
                  <Input
                    id="label"
                    value={editedField.label}
                    onChange={(e) => setEditedField({ ...editedField, label: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="key">Field Key</Label>
                  <Input
                    id="key"
                    value={editedField.key}
                    onChange={(e) => setEditedField({ ...editedField, key: e.target.value })}
                    disabled={editedField.isCore}
                  />
                </div>
              </div>

              {fieldTypeDef?.hasPlaceholder && (
                <div className="space-y-2">
                  <Label htmlFor="placeholder">Placeholder</Label>
                  <Input
                    id="placeholder"
                    value={editedField.placeholder || ''}
                    onChange={(e) => setEditedField({ ...editedField, placeholder: e.target.value })}
                  />
                </div>
              )}

              <div className="space-y-2">
                <Label htmlFor="description">Description</Label>
                <Input
                  id="description"
                  value={editedField.description || ''}
                  onChange={(e) => setEditedField({ ...editedField, description: e.target.value })}
                />
              </div>

              {fieldTypeDef?.hasDefaultValue && (
                <div className="space-y-2">
                  <Label htmlFor="defaultValue">Default Value</Label>
                  <Input
                    id="defaultValue"
                    value={editedField.defaultValue || ''}
                    onChange={(e) => setEditedField({ ...editedField, defaultValue: e.target.value })}
                  />
                </div>
              )}
            </div>

            <Separator />

            {/* Layout */}
            <div className="space-y-4">
              <h4 className="text-sm font-medium">Layout</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="width">Width</Label>
                  <Select
                    value={editedField.width}
                    onValueChange={(value: 'full' | 'half' | 'third') => 
                      setEditedField({ ...editedField, width: value })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="full">Full Width</SelectItem>
                      <SelectItem value="half">Half Width</SelectItem>
                      <SelectItem value="third">Third Width</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="cssClass">CSS Class</Label>
                  <Input
                    id="cssClass"
                    value={editedField.cssClass || ''}
                    onChange={(e) => setEditedField({ ...editedField, cssClass: e.target.value })}
                  />
                </div>
              </div>
            </div>

            <Separator />

            {/* Validation */}
            {fieldTypeDef?.hasValidation && (
              <>
                <div className="space-y-4">
                  <h4 className="text-sm font-medium">Validation</h4>
                  <div className="flex items-center justify-between">
                    <Label htmlFor="required">Required Field</Label>
                    <Switch
                      id="required"
                      checked={editedField.validation.required}
                      onCheckedChange={(checked) => 
                        setEditedField({ 
                          ...editedField, 
                          validation: { ...editedField.validation, required: checked } 
                        })
                      }
                    />
                  </div>
                  {['text', 'textarea', 'password'].includes(editedField.type) && (
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="minLength">Min Length</Label>
                        <Input
                          id="minLength"
                          type="number"
                          value={editedField.validation.minLength || ''}
                          onChange={(e) => 
                            setEditedField({ 
                              ...editedField, 
                              validation: { 
                                ...editedField.validation, 
                                minLength: e.target.value ? parseInt(e.target.value) : undefined 
                              } 
                            })
                          }
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="maxLength">Max Length</Label>
                        <Input
                          id="maxLength"
                          type="number"
                          value={editedField.validation.maxLength || ''}
                          onChange={(e) => 
                            setEditedField({ 
                              ...editedField, 
                              validation: { 
                                ...editedField.validation, 
                                maxLength: e.target.value ? parseInt(e.target.value) : undefined 
                              } 
                            })
                          }
                        />
                      </div>
                    </div>
                  )}
                </div>
                <Separator />
              </>
            )}

            {/* Show On */}
            <div className="space-y-4">
              <h4 className="text-sm font-medium">Display Context</h4>
              <div className="flex items-center justify-between">
                <Label htmlFor="showOnWordPress">Show on WordPress Registration</Label>
                <Switch
                  id="showOnWordPress"
                  checked={editedField.showOn.includes('wordpress')}
                  onCheckedChange={(checked) => {
                    const showOn = checked 
                      ? [...editedField.showOn, 'wordpress'] 
                      : editedField.showOn.filter(c => c !== 'wordpress')
                    setEditedField({ ...editedField, showOn: showOn as ('wordpress' | 'woocommerce')[] })
                  }}
                />
              </div>
              <div className="flex items-center justify-between">
                <Label htmlFor="showOnWooCommerce">Show on WooCommerce Registration</Label>
                <Switch
                  id="showOnWooCommerce"
                  checked={editedField.showOn.includes('woocommerce')}
                  onCheckedChange={(checked) => {
                    const showOn = checked 
                      ? [...editedField.showOn, 'woocommerce'] 
                      : editedField.showOn.filter(c => c !== 'woocommerce')
                    setEditedField({ ...editedField, showOn: showOn as ('wordpress' | 'woocommerce')[] })
                  }}
                />
              </div>
            </div>

            {/* Options (for select, radio, checkbox_group) */}
            {fieldTypeDef?.hasOptions && (
              <>
                <Separator />
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <h4 className="text-sm font-medium">Options</h4>
                    <Button type="button" variant="outline" size="sm" onClick={addOption}>
                      <Plus className="mr-1 h-3 w-3" />
                      Add Option
                    </Button>
                  </div>
                  <div className="space-y-2">
                    {(editedField.options || []).map((option, index) => (
                      <div key={index} className="flex items-center gap-2">
                        <Input
                          placeholder="Value"
                          value={option.value}
                          onChange={(e) => updateOption(index, { value: e.target.value })}
                          className="flex-1"
                        />
                        <Input
                          placeholder="Label"
                          value={option.label}
                          onChange={(e) => updateOption(index, { label: e.target.value })}
                          className="flex-1"
                        />
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          onClick={() => removeOption(index)}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    ))}
                    <div ref={optionsEndRef} />
                  </div>
                </div>
              </>
            )}
          </div>
        </ScrollArea>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button onClick={handleSave}>
            Save Changes
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
