'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="h-6 w-6 animate-spin text-blue-600" />
      </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="rounded-lg p-2 transition-colors hover:bg-gray-100"
        >
          <ArrowLeft className="h-5 w-5 text-gray-600" />
        </button>
        <div className="flex-1">
          <h1 className="text-xl font-semibold text-gray-900">
            {isNew ? 'New Form' : 'Edit Form'}
          </h1>
        </div>
        <button
          onClick={handleSave}
          disabled={saving || !name.trim()}
          className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700 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="mb-4 rounded-lg border border-gray-200 bg-white p-4">
        <div className="grid gap-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700">Form Name</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g. Contact Form"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700">Description</label>
            <input
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Brief description of this form"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700">Status</label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              className="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
            >
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
        </div>
      </div>

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

            {fields.length === 0 ? (
              <p className="py-6 text-center text-sm text-gray-500">
                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="flex items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 p-3 transition-colors hover:bg-white"
                  >
                    <GripVertical className="h-4 w-4 shrink-0 cursor-grab text-gray-400" />
                    <input
                      type="text"
                      value={field.label}
                      onChange={(e) => updateField(field.id, { label: e.target.value })}
                      className="flex-1 rounded border border-gray-300 px-2 py-1 text-sm focus:ring-1 focus:ring-blue-500 focus:outline-none"
                    />
                    <span className="shrink-0 rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-500">
                      {field.type}
                    </span>
                    <label className="flex shrink-0 items-center gap-1 text-xs text-gray-600">
                      <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="shrink-0 rounded p-1 text-red-500 transition-colors hover:bg-red-50"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Confirmation section */}
      <div className="mb-4 rounded-lg border border-gray-200 bg-white">
        <button
          onClick={() => toggleSection('confirmation')}
          className="flex w-full items-center justify-between p-4 transition-colors hover:bg-gray-50"
        >
          <div className="flex items-center gap-2">
            {expandedSection === 'confirmation' ? (
              <ChevronDown className="h-4 w-4" />
            ) : (
              <ChevronRight className="h-4 w-4" />
            )}
            <MessageSquare className="h-4 w-4 text-green-600" />
            <span className="font-medium text-gray-900">Confirmation</span>
            <span className="rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-500">
              {confirmation.type === 'message' ? 'Show Message' : 'Redirect'}
            </span>
          </div>
        </button>
        {expandedSection === 'confirmation' && (
          <div className="border-t border-gray-200 p-4">
            <div className="mb-4">
              <label className="mb-2 block text-sm font-medium text-gray-700">
                After submission
              </label>
              <div className="flex gap-3">
                <label
                  className="flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 transition-colors hover:bg-gray-50"
                  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-blue-600"
                  />
                  <MessageSquare className="h-4 w-4" />
                  <span className="text-sm">Show Message</span>
                </label>
                <label
                  className="flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 transition-colors hover:bg-gray-50"
                  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-blue-600"
                  />
                  <ExternalLink className="h-4 w-4" />
                  <span className="text-sm">Redirect to Page</span>
                </label>
              </div>
            </div>

            {confirmation.type === 'message' ? (
              <div>
                <label className="mb-1 block text-sm font-medium text-gray-700">
                  Success Message
                </label>
                <textarea
                  value={confirmation.message}
                  onChange={(e) => setConfirmation((c) => ({ ...c, message: e.target.value }))}
                  rows={3}
                  className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  placeholder="Thank you! Your submission has been received."
                />
              </div>
            ) : (
              <div className="grid gap-3">
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">
                    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="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">
                    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="w-32 rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  />
                  <p className="mt-1 text-xs text-gray-500">0 = instant redirect</p>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Analytics section */}
      <div className="mb-4 rounded-lg border border-gray-200 bg-white">
        <button
          onClick={() => toggleSection('analytics')}
          className="flex w-full items-center justify-between p-4 transition-colors hover:bg-gray-50"
        >
          <div className="flex items-center gap-2">
            {expandedSection === 'analytics' ? (
              <ChevronDown className="h-4 w-4" />
            ) : (
              <ChevronRight className="h-4 w-4" />
            )}
            <BarChart3 className="h-4 w-4 text-purple-600" />
            <span className="font-medium text-gray-900">GA4 Analytics</span>
            <span
              className={`rounded px-2 py-0.5 text-xs ${analytics.enabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}
            >
              {analytics.enabled ? 'Enabled' : 'Disabled'}
            </span>
          </div>
        </button>
        {expandedSection === 'analytics' && (
          <div className="border-t border-gray-200 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="peer h-5 w-9 rounded-full bg-gray-200 peer-checked:bg-blue-600 peer-focus:ring-2 peer-focus:ring-blue-300 peer-focus:outline-none after:absolute after:top-[2px] after:left-[2px] after:h-4 after:w-4 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:after:translate-x-full peer-checked:after:border-white" />
              </label>
              <span className="text-sm font-medium text-gray-700">
                Push events to Google Analytics 4
              </span>
            </div>

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

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

                <div className="border-t border-gray-200 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-sm font-medium text-gray-700">
                      Track as conversion event
                    </label>
                  </div>

                  {analytics.trackAsConversion && (
                    <div className="ml-6 grid grid-cols-2 gap-4">
                      <div>
                        <label className="mb-1 block text-sm font-medium text-gray-700">
                          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="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                        />
                      </div>
                      <div>
                        <label className="mb-1 block text-sm font-medium text-gray-700">
                          Currency
                        </label>
                        <select
                          value={analytics.conversionCurrency}
                          onChange={(e) =>
                            setAnalytics((a) => ({ ...a, conversionCurrency: e.target.value }))
                          }
                          className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 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="rounded-lg border border-blue-200 bg-blue-50 p-3">
                  <p className="text-xs text-blue-800">
                    <strong>Note:</strong> Your site must have the GA4 snippet or GTM container
                    installed. Actuate pushes events via{' '}
                    <code className="rounded bg-blue-100 px-1">gtag()</code> /
                    <code className="rounded bg-blue-100 px-1">dataLayer</code> — it does not load
                    the GA4 script.
                  </p>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
