"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  type DragEndEvent,
} from "@dnd-kit/core"
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { GripVertical, Plus, Pencil, Trash2 } from "lucide-react"

const ENTITY_TYPES = [
  { value: "lead", label: "Leads" },
  { value: "customer", label: "Customers" },
  { value: "opportunity", label: "Opportunities" },
  { value: "project", label: "Projects" },
]

const FIELD_TYPES = [
  { value: "text", label: "Text" },
  { value: "number", label: "Number" },
  { value: "date", label: "Date" },
  { value: "select", label: "Select (Single)" },
  { value: "multi_select", label: "Select (Multiple)" },
  { value: "boolean", label: "Boolean (Yes/No)" },
  { value: "url", label: "URL" },
  { value: "email", label: "Email" },
  { value: "phone", label: "Phone" },
]

interface FieldDefinition {
  id: string
  entity_type: string
  field_key: string
  field_label: string
  field_type: string
  options: string[] | null
  placeholder: string | null
  default_value: string | null
  section: string | null
  is_required: boolean
  sort_order: number
  is_active: boolean
}

function SortableField({ field, onEdit, onDelete }: {
  field: FieldDefinition
  onEdit: (f: FieldDefinition) => void
  onDelete: (id: string) => void
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: field.id })
  const style = { transform: CSS.Transform.toString(transform), transition }

  return (
    <div ref={setNodeRef} style={style} className={`flex items-center gap-3 rounded-lg border p-3 ${isDragging ? "opacity-50" : ""}`}>
      <button {...attributes} {...listeners} className="cursor-grab touch-none text-muted-foreground hover:text-foreground">
        <GripVertical className="h-4 w-4" />
      </button>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="font-medium text-sm truncate">{field.field_label}</span>
          <span className="text-xs text-muted-foreground">({field.field_key})</span>
          {field.is_required && <span className="text-xs text-red-500">required</span>}
        </div>
        <p className="text-xs text-muted-foreground">
          {FIELD_TYPES.find(t => t.value === field.field_type)?.label || field.field_type}
          {field.section ? ` — ${field.section}` : ""}
        </p>
      </div>
      <Button variant="ghost" size="icon" onClick={() => onEdit(field)}>
        <Pencil className="h-4 w-4" />
      </Button>
      <Button variant="ghost" size="icon" onClick={() => onDelete(field.id)}>
        <Trash2 className="h-4 w-4 text-red-500" />
      </Button>
    </div>
  )
}

export function CustomFieldsManager() {
  const [entityType, setEntityType] = useState("lead")
  const [fields, setFields] = useState<FieldDefinition[]>([])
  const [loading, setLoading] = useState(true)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingField, setEditingField] = useState<FieldDefinition | null>(null)
  const [form, setForm] = useState({
    fieldKey: "", fieldLabel: "", fieldType: "text", options: "",
    placeholder: "", defaultValue: "", section: "", isRequired: false,
  })

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

  async function loadFields() {
    setLoading(true)
    try {
      const res = await fetch(`/api/custom-fields?entityType=${entityType}`)
      if (res.ok) setFields(await res.json())
    } catch { /* ignore */ }
    setLoading(false)
  }

  useEffect(() => { loadFields() }, [entityType])

  function resetForm() {
    setForm({ fieldKey: "", fieldLabel: "", fieldType: "text", options: "", placeholder: "", defaultValue: "", section: "", isRequired: false })
    setEditingField(null)
  }

  function openEdit(field: FieldDefinition) {
    setEditingField(field)
    setForm({
      fieldKey: field.field_key,
      fieldLabel: field.field_label,
      fieldType: field.field_type,
      options: field.options?.join("\n") || "",
      placeholder: field.placeholder || "",
      defaultValue: field.default_value || "",
      section: field.section || "",
      isRequired: field.is_required,
    })
    setDialogOpen(true)
  }

  async function handleSave() {
    const options = form.options ? form.options.split("\n").map(s => s.trim()).filter(Boolean) : null
    const payload = { ...form, options, entityType }

    const res = editingField
      ? await fetch("/api/custom-fields", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: editingField.id, ...payload }) })
      : await fetch("/api/custom-fields", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) })

    if (res.ok) {
      setDialogOpen(false)
      resetForm()
      loadFields()
    }
  }

  async function handleDelete(id: string) {
    if (!confirm("Delete this custom field?")) return
    const res = await fetch(`/api/custom-fields?id=${id}`, { method: "DELETE" })
    if (res.ok) loadFields()
  }

  async function handleDragEnd(event: DragEndEvent) {
    const { active, over } = event
    if (!over || active.id === over.id) return
    const oldIndex = fields.findIndex(f => f.id === active.id)
    const newIndex = fields.findIndex(f => f.id === over.id)
    const reordered = arrayMove(fields, oldIndex, newIndex)
    setFields(reordered)
    await Promise.all(reordered.map((f, i) =>
      fetch("/api/custom-fields", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: f.id, sortOrder: i }) })
    ))
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Select value={entityType} onValueChange={setEntityType}>
          <SelectTrigger className="w-[200px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {ENTITY_TYPES.map(et => (
              <SelectItem key={et.value} value={et.value}>{et.label}</SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Dialog open={dialogOpen} onOpenChange={(open) => { setDialogOpen(open); if (!open) resetForm() }}>
          <DialogTrigger asChild>
            <Button size="sm"><Plus className="mr-1 h-4 w-4" />Add Field</Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg">
            <DialogHeader>
              <DialogTitle>{editingField ? "Edit Field" : "New Custom Field"}</DialogTitle>
            </DialogHeader>
            <div className="space-y-3">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium mb-1 block">Field Key</label>
                  <Input value={form.fieldKey} onChange={e => setForm(p => ({ ...p, fieldKey: e.target.value }))} placeholder="e.g. service_type" disabled={!!editingField} />
                </div>
                <div>
                  <label className="text-xs font-medium mb-1 block">Field Label</label>
                  <Input value={form.fieldLabel} onChange={e => setForm(p => ({ ...p, fieldLabel: e.target.value }))} placeholder="e.g. Service Type" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium mb-1 block">Field Type</label>
                  <Select value={form.fieldType} onValueChange={v => setForm(p => ({ ...p, fieldType: v }))}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {FIELD_TYPES.map(ft => (
                        <SelectItem key={ft.value} value={ft.value}>{ft.label}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <label className="text-xs font-medium mb-1 block">Section (optional)</label>
                  <Input value={form.section} onChange={e => setForm(p => ({ ...p, section: e.target.value }))} placeholder="e.g. Details, Technical" />
                </div>
              </div>
              {(form.fieldType === "select" || form.fieldType === "multi_select") && (
                <div>
                  <label className="text-xs font-medium mb-1 block">Options (one per line)</label>
                  <textarea
                    className="w-full min-h-[80px] rounded-md border bg-background px-3 py-2 text-sm"
                    value={form.options}
                    onChange={e => setForm(p => ({ ...p, options: e.target.value }))}
                    placeholder="Option 1&#10;Option 2&#10;Option 3"
                  />
                </div>
              )}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium mb-1 block">Placeholder</label>
                  <Input value={form.placeholder} onChange={e => setForm(p => ({ ...p, placeholder: e.target.value }))} />
                </div>
                <div>
                  <label className="text-xs font-medium mb-1 block">Default Value</label>
                  <Input value={form.defaultValue} onChange={e => setForm(p => ({ ...p, defaultValue: e.target.value }))} />
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Switch checked={form.isRequired} onCheckedChange={v => setForm(p => ({ ...p, isRequired: v }))} />
                <label className="text-sm">Required</label>
              </div>
              <Button onClick={handleSave} className="w-full">{editingField ? "Update" : "Create"}</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {loading ? (
        <p className="text-sm text-muted-foreground">Loading...</p>
      ) : fields.length === 0 ? (
        <Card>
          <CardContent className="py-8 text-center">
            <p className="text-sm text-muted-foreground">No custom fields defined for {ENTITY_TYPES.find(e => e.value === entityType)?.label}.</p>
            <p className="text-xs text-muted-foreground mt-1">Click "Add Field" to create one.</p>
          </CardContent>
        </Card>
      ) : (
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
          <SortableContext items={fields.map(f => f.id)} strategy={verticalListSortingStrategy}>
            <div className="space-y-2">
              {fields.map(field => (
                <SortableField key={field.id} field={field} onEdit={openEdit} onDelete={handleDelete} />
              ))}
            </div>
          </SortableContext>
        </DndContext>
      )}
    </div>
  )
}
