'use client'

import { useState, useCallback, useEffect } from 'react'
import {
  Save,
  ArrowLeft,
  Plus,
  Trash2,
  GripVertical,
  MessageSquare,
  ExternalLink,
  BarChart3,
  ChevronDown,
  ChevronRight,
  Loader2,
} from 'lucide-react'
import { useApiData } from '../lib/useApiData.js'
import { cmsApi } from '../lib/api.js'

interface FormField {
  id: string
  type: string
  label: string
  placeholder?: string
  required: boolean
  options?: string[]
}

interface ConfirmationConfig {
  type: 'message' | 'redirect'
  message: string
  redirectUrl: string
  redirectDelay: number
}

interface AnalyticsConfig {
  enabled: boolean
  measurementId: string
  submitEventName: string
  startEventName: string
  trackAsConversion: boolean
  conversionValue: number
  conversionCurrency: string
  customParameters: Record<string, string>
}

const FIELD_TYPES = [
  { value: 'text', label: 'Text' },
  { value: 'email', label: 'Email' },
  { value: 'tel', label: 'Phone' },
  { value: 'textarea', label: 'Textarea' },
  { value: 'select', label: 'Dropdown' },
  { value: 'checkbox', label: 'Checkbox' },
  { value: 'number', label: 'Number' },
  { value: 'date', label: 'Date' },
  { value: 'url', label: 'URL' },
  { value: 'file', label: 'File Upload' },
  { value: 'hidden', label: 'Hidden' },
] as const

export interface FormEditorProps {
  formId?: string
  onNavigate?: (path: string) => void
}

export function FormEditor({ formId, onNavigate }: FormEditorProps) {
  const isNew = !formId
  const { data: existingForm, loading } = useApiData<any>(
    formId ? `/collections/forms/${formId}` : null,
  )

  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [status, setStatus] = useState('active')
  const [fields, setFields] = useState<FormField[]>([])
  const [saving, setSaving] = useState(false)
  const [expandedSection, setExpandedSection] = useState<string | null>('fields')

  const [confirmation, setConfirmation] = useState<ConfirmationConfig>({
    type: 'message',
    message: 'Thank you! Your submission has been received.',
    redirectUrl: '',
    redirectDelay: 0,
  })

  const [analytics, setAnalytics] = useState<AnalyticsConfig>({
    enabled: false,
    measurementId: '',
    submitEventName: 'form_submit',
    startEventName: 'form_start',
    trackAsConversion: false,
    conversionValue: 0,
    conversionCurrency: 'USD',
    customParameters: {},
  })

  useEffect(() => {
    if (existingForm) {
      const d = existingForm.data ?? existingForm
      setName(d.name ?? '')
      setDescription(d.description ?? '')
      setStatus(d.status ?? 'active')
      if (Array.isArray(d.fields)) setFields(d.fields)
      if (d.confirmation) {
        setConfirmation((prev) => ({ ...prev, ...d.confirmation }))
      }
      if (d.analytics) {
        setAnalytics((prev) => ({ ...prev, ...d.analytics }))
      }
    }
  }, [existingForm])

  const addField = useCallback((type: string) => {
    setFields((prev) => [
      ...prev,
      {
        id: crypto.randomUUID(),
        type,
        label: `New ${type} field`,
        required: false,
      },
    ])
  }, [])

  const removeField = useCallback((id: string) => {
    setFields((prev) => prev.filter((f) => f.id !== id))
  }, [])

  const updateField = useCallback((id: string, updates: Partial<FormField>) => {
    setFields((prev) => prev.map((f) => (f.id === id ? { ...f, ...updates } : f)))
  }, [])

  const moveField = useCallback((from: number, to: number) => {
    setFields((prev) => {
      const next = [...prev]
      const [moved] = next.splice(from, 1)
      next.splice(to, 0, moved!)
      return next
    })
  }, [])

  const handleSave = async () => {
    setSaving(true)
    try {
      const payload = {
        name,
        description,
        status,
        fields,
        confirmation,
        analytics: analytics.enabled ? analytics : { enabled: false },
      }

      if (isNew) {
        await cmsApi('/collections/forms', {
          method: 'POST',
          body: JSON.stringify(payload),
        })
      } else {
        await cmsApi(`/collections/forms/${formId}`, {
          method: 'PUT',
          body: JSON.stringify(payload),
        })
      }
      onNavigate?.('/forms')
    } finally {
      setSaving(false)
    }
  }

  const toggleSection = (section: string) => {
    setExpandedSection(expandedSection === section ? null : section)
  }

  if (loading) {
    return (
      <div className="flex h-64 items-center justify-center p-4">
        <Loader2 className="text-primary h-6 w-6 animate-spin" />
      </div>
    )
  }

  return (
    <div className="max-w-4xl p-3 pr-6 sm:p-4 sm:pr-8">
      {/* Header */}
      <div className="mb-6 flex items-center gap-3">
        <button
          onClick={() => onNavigate?.('/forms')}
          className="hover:bg-muted rounded-lg p-2 transition-colors"
        >
          <ArrowLeft className="text-muted-foreground h-5 w-5" />
        </button>
        <div className="flex-1">
          <h1 className="text-foreground text-xl font-medium">
            {isNew ? 'New Form' : 'Edit Form'}
          </h1>
        </div>
        <button
          onClick={handleSave}
          disabled={saving || !name.trim()}
          className="bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm transition-colors disabled:opacity-50"
        >
          {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
          {saving ? 'Saving...' : 'Save'}
        </button>
      </div>

      {/* Basic info */}
      <div className="border-border bg-card mb-4 rounded-lg border p-4">
        <div className="grid gap-4">
          <div>
            <label className="text-foreground mb-1 block text-sm font-medium">Form Name</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g. Contact Form"
              className="border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
            />
          </div>
          <div>
            <label className="text-foreground mb-1 block text-sm font-medium">Description</label>
            <input
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Brief description of this form"
              className="border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
            />
          </div>
          <div>
            <label className="text-foreground mb-1 block text-sm font-medium">Status</label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              className="border-border focus-visible:ring-ring/50 rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
            >
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
        </div>
      </div>

      {/* Fields section */}
      <div className="border-border bg-card mb-4 rounded-lg border">
        <button
          onClick={() => toggleSection('fields')}
          className="hover:bg-muted flex w-full items-center justify-between p-4 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSection === 'fields' ? (
              <ChevronDown className="h-4 w-4" />
            ) : (
              <ChevronRight className="h-4 w-4" />
            )}
            <span className="text-foreground font-medium">Form Fields</span>
            <span className="text-muted-foreground text-sm">({fields.length})</span>
          </div>
        </button>
        {expandedSection === 'fields' && (
          <div className="border-border border-t p-4">
            <div className="mb-4 flex flex-wrap gap-2">
              {FIELD_TYPES.map((ft) => (
                <button
                  key={ft.value}
                  onClick={() => addField(ft.value)}
                  className="border-border hover:bg-muted flex items-center gap-1 rounded-lg border px-3 py-1.5 text-xs transition-colors"
                >
                  <Plus className="h-3 w-3" /> {ft.label}
                </button>
              ))}
            </div>

            {fields.length === 0 ? (
              <p className="text-muted-foreground py-6 text-center text-sm">
                Click a field type above to add it to your form.
              </p>
            ) : (
              <div className="flex flex-col gap-2">
                {fields.map((field, index) => (
                  <div
                    key={field.id}
                    draggable
                    onDragStart={(e) => e.dataTransfer.setData('text/plain', String(index))}
                    onDragOver={(e) => e.preventDefault()}
                    onDrop={(e) => {
                      const from = Number(e.dataTransfer.getData('text/plain'))
                      moveField(from, index)
                    }}
                    className="border-border bg-muted hover:bg-card flex items-center gap-3 rounded-lg border p-3 transition-colors"
                  >
                    <GripVertical className="text-muted-foreground h-4 w-4 shrink-0 cursor-grab" />
                    <input
                      type="text"
                      value={field.label}
                      onChange={(e) => updateField(field.id, { label: e.target.value })}
                      className="border-border focus-visible:ring-ring/50 flex-1 rounded border px-2 py-1 text-sm focus:ring-1 focus:outline-none"
                    />
                    <span className="bg-muted text-muted-foreground shrink-0 rounded px-2 py-0.5 text-xs">
                      {field.type}
                    </span>
                    <label className="text-muted-foreground flex shrink-0 items-center gap-1 text-xs">
                      <input
                        type="checkbox"
                        checked={field.required}
                        onChange={(e) => updateField(field.id, { required: e.target.checked })}
                        className="rounded"
                      />
                      Required
                    </label>
                    <button
                      onClick={() => removeField(field.id)}
                      className="text-destructive hover:bg-destructive/10 shrink-0 rounded p-1 transition-colors"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Confirmation section */}
      <div className="border-border bg-card mb-4 rounded-lg border">
        <button
          onClick={() => toggleSection('confirmation')}
          className="hover:bg-muted flex w-full items-center justify-between p-4 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSection === 'confirmation' ? (
              <ChevronDown className="h-4 w-4" />
            ) : (
              <ChevronRight className="h-4 w-4" />
            )}
            <MessageSquare className="text-success h-4 w-4" />
            <span className="text-foreground font-medium">Confirmation</span>
            <span className="bg-muted text-muted-foreground rounded px-2 py-0.5 text-xs">
              {confirmation.type === 'message' ? 'Show Message' : 'Redirect'}
            </span>
          </div>
        </button>
        {expandedSection === 'confirmation' && (
          <div className="border-border border-t p-4">
            <div className="mb-4">
              <label className="text-foreground mb-2 block text-sm font-medium">
                After submission
              </label>
              <div className="flex gap-3">
                <label
                  className="hover:bg-muted flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 transition-colors"
                  style={{
                    borderColor: confirmation.type === 'message' ? '#2563eb' : '#d1d5db',
                    backgroundColor: confirmation.type === 'message' ? '#eff6ff' : 'transparent',
                  }}
                >
                  <input
                    type="radio"
                    name="confirmationType"
                    value="message"
                    checked={confirmation.type === 'message'}
                    onChange={() => setConfirmation((c) => ({ ...c, type: 'message' }))}
                    className="text-primary"
                  />
                  <MessageSquare className="h-4 w-4" />
                  <span className="text-sm">Show Message</span>
                </label>
                <label
                  className="hover:bg-muted flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 transition-colors"
                  style={{
                    borderColor: confirmation.type === 'redirect' ? '#2563eb' : '#d1d5db',
                    backgroundColor: confirmation.type === 'redirect' ? '#eff6ff' : 'transparent',
                  }}
                >
                  <input
                    type="radio"
                    name="confirmationType"
                    value="redirect"
                    checked={confirmation.type === 'redirect'}
                    onChange={() => setConfirmation((c) => ({ ...c, type: 'redirect' }))}
                    className="text-primary"
                  />
                  <ExternalLink className="h-4 w-4" />
                  <span className="text-sm">Redirect to Page</span>
                </label>
              </div>
            </div>

            {confirmation.type === 'message' ? (
              <div>
                <label className="text-foreground mb-1 block text-sm font-medium">
                  Success Message
                </label>
                <textarea
                  value={confirmation.message}
                  onChange={(e) => setConfirmation((c) => ({ ...c, message: e.target.value }))}
                  rows={3}
                  className="border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                  placeholder="Thank you! Your submission has been received."
                />
              </div>
            ) : (
              <div className="grid gap-3">
                <div>
                  <label className="text-foreground mb-1 block text-sm font-medium">
                    Redirect URL
                  </label>
                  <input
                    type="url"
                    value={confirmation.redirectUrl}
                    onChange={(e) =>
                      setConfirmation((c) => ({ ...c, redirectUrl: e.target.value }))
                    }
                    placeholder="https://example.com/thank-you"
                    className="border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="text-foreground mb-1 block text-sm font-medium">
                    Redirect Delay (ms)
                  </label>
                  <input
                    type="number"
                    value={confirmation.redirectDelay}
                    onChange={(e) =>
                      setConfirmation((c) => ({ ...c, redirectDelay: Number(e.target.value) }))
                    }
                    min={0}
                    step={500}
                    className="border-border focus-visible:ring-ring/50 w-32 rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                  />
                  <p className="text-muted-foreground mt-1 text-xs">0 = instant redirect</p>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Analytics section */}
      <div className="border-border bg-card mb-4 rounded-lg border">
        <button
          onClick={() => toggleSection('analytics')}
          className="hover:bg-muted flex w-full items-center justify-between p-4 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSection === 'analytics' ? (
              <ChevronDown className="h-4 w-4" />
            ) : (
              <ChevronRight className="h-4 w-4" />
            )}
            <BarChart3 className="text-brand h-4 w-4" />
            <span className="text-foreground font-medium">GA4 Analytics</span>
            <span
              className={`rounded px-2 py-0.5 text-xs ${analytics.enabled ? 'bg-success/10 text-success' : 'bg-muted text-muted-foreground'}`}
            >
              {analytics.enabled ? 'Enabled' : 'Disabled'}
            </span>
          </div>
        </button>
        {expandedSection === 'analytics' && (
          <div className="border-border border-t p-4">
            <div className="mb-4 flex items-center gap-3">
              <label className="relative inline-flex cursor-pointer items-center">
                <input
                  type="checkbox"
                  checked={analytics.enabled}
                  onChange={(e) => setAnalytics((a) => ({ ...a, enabled: e.target.checked }))}
                  className="peer sr-only"
                />
                <div className="bg-muted peer peer-checked:bg-primary peer-focus:ring-ring/50 after:border-border after:bg-card h-5 w-9 rounded-full peer-focus:ring-2 peer-focus:outline-none after:absolute after:top-[2px] after:left-[2px] after:h-4 after:w-4 after:rounded-full after:border after:transition-all after:content-[''] peer-checked:after:translate-x-full peer-checked:after:border-white" />
              </label>
              <span className="text-foreground text-sm font-medium">
                Push events to Google Analytics 4
              </span>
            </div>

            {analytics.enabled && (
              <div className="grid gap-4 pl-12">
                <div>
                  <label className="text-foreground mb-1 block text-sm font-medium">
                    GA4 Measurement ID
                    <span className="text-muted-foreground font-normal"> (optional)</span>
                  </label>
                  <input
                    type="text"
                    value={analytics.measurementId}
                    onChange={(e) => setAnalytics((a) => ({ ...a, measurementId: e.target.value }))}
                    placeholder="G-XXXXXXXXXX"
                    className="border-border focus-visible:ring-ring/50 w-64 rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                  />
                  <p className="text-muted-foreground mt-1 text-xs">
                    Leave blank to use your site's default GA4 tag
                  </p>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-foreground mb-1 block text-sm font-medium">
                      Submit Event Name
                    </label>
                    <input
                      type="text"
                      value={analytics.submitEventName}
                      onChange={(e) =>
                        setAnalytics((a) => ({ ...a, submitEventName: e.target.value }))
                      }
                      className="border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                    />
                  </div>
                  <div>
                    <label className="text-foreground mb-1 block text-sm font-medium">
                      Start Event Name
                    </label>
                    <input
                      type="text"
                      value={analytics.startEventName}
                      onChange={(e) =>
                        setAnalytics((a) => ({ ...a, startEventName: e.target.value }))
                      }
                      className="border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                    />
                  </div>
                </div>

                <div className="border-border border-t pt-4">
                  <div className="mb-3 flex items-center gap-3">
                    <input
                      type="checkbox"
                      id="trackConversion"
                      checked={analytics.trackAsConversion}
                      onChange={(e) =>
                        setAnalytics((a) => ({ ...a, trackAsConversion: e.target.checked }))
                      }
                      className="rounded"
                    />
                    <label
                      htmlFor="trackConversion"
                      className="text-foreground text-sm font-medium"
                    >
                      Track as conversion event
                    </label>
                  </div>

                  {analytics.trackAsConversion && (
                    <div className="ml-6 grid grid-cols-2 gap-4">
                      <div>
                        <label className="text-foreground mb-1 block text-sm font-medium">
                          Conversion Value
                        </label>
                        <input
                          type="number"
                          value={analytics.conversionValue}
                          onChange={(e) =>
                            setAnalytics((a) => ({ ...a, conversionValue: Number(e.target.value) }))
                          }
                          min={0}
                          step={0.01}
                          className="border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                        />
                      </div>
                      <div>
                        <label className="text-foreground mb-1 block text-sm font-medium">
                          Currency
                        </label>
                        <select
                          value={analytics.conversionCurrency}
                          onChange={(e) =>
                            setAnalytics((a) => ({ ...a, conversionCurrency: e.target.value }))
                          }
                          className="border-border focus-visible:ring-ring/50 w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                        >
                          <option value="USD">USD</option>
                          <option value="EUR">EUR</option>
                          <option value="GBP">GBP</option>
                          <option value="CAD">CAD</option>
                          <option value="AUD">AUD</option>
                        </select>
                      </div>
                    </div>
                  )}
                </div>

                <div className="border-info/30 bg-info/10 rounded-lg border p-3">
                  <p className="text-foreground text-xs">
                    <strong>Note:</strong> Your site must have the GA4 snippet or GTM container
                    installed. Actuate pushes events via{' '}
                    <code className="bg-info/10 rounded px-1">gtag()</code> /
                    <code className="bg-info/10 rounded px-1">dataLayer</code> — it does not load
                    the GA4 script.
                  </p>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
