import { useState, useRef, useEffect } from 'react'
import { Variable } from 'lucide-react'
import type { IntakeFormField } from '@/types'
import { cn } from '@/lib/utils'

interface InlineVariablePromptProps {
  variableName: string
  fieldMeta?: IntakeFormField
  onSubmit: (variableName: string, value: string) => void
  disabled?: boolean
}

export function InlineVariablePrompt({
  variableName,
  fieldMeta,
  onSubmit,
  disabled,
}: InlineVariablePromptProps) {
  const [value, setValue] = useState('')
  const [isEditing, setIsEditing] = useState(false)
  const inputRef = useRef<HTMLInputElement | HTMLSelectElement>(null)

  const label = fieldMeta?.label || variableName
  const placeholder = fieldMeta?.placeholder || `Enter ${label}...`
  const helpText = fieldMeta?.help_text
  const fieldType = fieldMeta?.field_type || 'text'
  const options = fieldMeta?.options || []
  const isRequired = fieldMeta?.required ?? false

  useEffect(() => {
    if (isEditing && inputRef.current) {
      inputRef.current.focus()
    }
  }, [isEditing])

  const handleSubmit = () => {
    const trimmed = value.trim()
    if (trimmed) {
      onSubmit(variableName, trimmed)
      setIsEditing(false)
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      handleSubmit()
    }
    if (e.key === 'Escape') {
      setIsEditing(false)
      setValue('')
    }
  }

  if (!isEditing) {
    return (
      <button
        onClick={() => setIsEditing(true)}
        disabled={disabled}
        className={cn(
          'inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm font-medium transition-all',
          'border-blue-500/40 bg-blue-500/5 text-blue-400',
          'hover:border-blue-400/60 hover:bg-blue-500/10 hover:shadow-[0_0_12px_rgba(96,165,250,0.15)]',
          'disabled:opacity-50 disabled:cursor-not-allowed',
          isRequired && 'ring-1 ring-blue-500/20'
        )}
      >
        <Variable className="h-3.5 w-3.5" />
        {label}
      </button>
    )
  }

  // Select field type
  if (fieldType === 'select' && options.length > 0) {
    return (
      <span className="inline-flex items-center gap-1.5">
        <select
          ref={inputRef as React.RefObject<HTMLSelectElement>}
          value={value}
          onChange={(e) => {
            setValue(e.target.value)
            if (e.target.value) {
              onSubmit(variableName, e.target.value)
              setIsEditing(false)
            }
          }}
          onBlur={() => {
            if (!value) setIsEditing(false)
          }}
          className="rounded-md border border-blue-500/40 bg-blue-500/5 px-2.5 py-1 text-sm text-foreground shadow-[0_0_12px_rgba(96,165,250,0.15)] focus:border-blue-400 focus:outline-hidden focus:ring-1 focus:ring-blue-400/30"
        >
          <option value="">{placeholder}</option>
          {options.map((opt) => (
            <option key={opt} value={opt}>{opt}</option>
          ))}
        </select>
      </span>
    )
  }

  // Text/other input types
  const inputType = fieldType === 'email' ? 'email'
    : fieldType === 'number' ? 'number'
    : fieldType === 'url' ? 'url'
    : fieldType === 'ip_address' ? 'text'
    : 'text'

  return (
    <span className="inline-flex items-center gap-1.5">
      <span className="relative inline-flex items-center">
        <input
          ref={inputRef as React.RefObject<HTMLInputElement>}
          type={inputType}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onBlur={handleSubmit}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          className="w-48 rounded-md border border-blue-500/40 bg-blue-500/5 px-2.5 py-1 text-sm text-foreground shadow-[0_0_12px_rgba(96,165,250,0.15)] placeholder:text-muted-foreground focus:border-blue-400 focus:outline-hidden focus:ring-1 focus:ring-blue-400/30"
        />
        {helpText && (
          <span className="absolute -bottom-5 left-0 text-[0.625rem] text-muted-foreground whitespace-nowrap">
            {helpText}
          </span>
        )}
      </span>
    </span>
  )
}
