import React, { useEffect, useState } from 'react'
import type { WObject } from '@/lib/wysiwyg/schema'

export type PropsPanelProps = {
  object: WObject
  onChange?: (next: WObject) => void
}

function num(v: string, fallback: number) {
  const n = Number(v)
  return Number.isFinite(n) ? n : fallback
}

function isImage(o: WObject): o is Extract<WObject, { type: 'image' }> {
  return o.type === 'image'
}

function isText(o: WObject): o is Extract<WObject, { type: 'text' }> {
  return o.type === 'text'
}

function isButton(o: WObject): o is Extract<WObject, { type: 'button' }> {
  return o.type === 'button'
}

function isInput(o: WObject): o is Extract<WObject, { type: 'input' }> {
  return o.type === 'input'
}

function isSelect(o: WObject): o is Extract<WObject, { type: 'select' }> {
  return o.type === 'select'
}

function isRadio(o: WObject): o is Extract<WObject, { type: 'radio' }> {
  return o.type === 'radio'
}

function isCheckbox(o: WObject): o is Extract<WObject, { type: 'checkbox' }> {
  return o.type === 'checkbox'
}

function isTextarea(o: WObject): o is Extract<WObject, { type: 'textarea' }> {
  return o.type === 'textarea'
}

export function PropsPanel({ object, onChange }: PropsPanelProps) {
  const [model, setModel] = useState<WObject>(object)

  useEffect(() => {
    setModel(object)
  }, [object])

  const emit = (next: WObject) => {
    setModel(next)
    onChange?.(next)
  }

  const update = (patch: Partial<Pick<WObject, 'x' | 'y' | 'width' | 'height' | 'rotate'>>): void => {
    const next: WObject = { ...model, ...patch }
    emit(next)
  }
  const updateImageProps = (patch: Partial<{ src: string; alt?: string }>): void => {
    if (!isImage(model)) return
    const next: WObject = { ...model, props: { ...model.props, ...patch } }
    emit(next)
  }
  const updateTextProps = (patch: Partial<{ text: string }>): void => {
    if (!isText(model)) return
    const next: WObject = { ...model, props: { ...model.props, ...patch } }
    emit(next)
  }
  const updateButtonProps = (patch: Partial<{ label: string }>): void => {
    if (!isButton(model)) return
    const next: WObject = { ...model, props: { ...model.props, ...patch } }
    emit(next)
  }

  const updateInputProps = (patch: Partial<{ name: string; label: string; placeholder: string; required: boolean; help: string }>): void => {
    if (!isInput(model)) return
    const next: WObject = { ...model, props: { ...model.props, ...patch } }
    emit(next)
  }

  const updateSelectProps = (patch: Partial<{ name: string; label: string; options: string[]; defaultValue: string; help: string }>): void => {
    if (!isSelect(model)) return
    const next: WObject = { ...model, props: { ...model.props, ...patch } }
    emit(next)
  }

  const updateRadioProps = (patch: Partial<{ name: string; legend: string; options: string[]; defaultValue: string; required: boolean; help: string }>): void => {
    if (!isRadio(model)) return
    const next: WObject = { ...model, props: { ...model.props, ...patch } }
    emit(next)
  }

  const updateCheckboxProps = (patch: Partial<{ name: string; legend: string; options: string[]; defaultValues: string[]; required: boolean; help: string }>): void => {
    if (!isCheckbox(model)) return
    const next: WObject = { ...model, props: { ...model.props, ...patch } }
    emit(next)
  }

  const updateTextareaProps = (patch: Partial<{ name: string; label: string; placeholder: string; rows: number; required: boolean; help: string }>): void => {
    if (!isTextarea(model)) return
    const next: WObject = { ...model, props: { ...model.props, ...patch } }
    emit(next)
  }

  return (
    <div aria-label="Properties Panel">
      <div>
        <label>
          X
          <input aria-label="X" type="number" value={model.x} onChange={(e) => update({ x: num(e.target.value, model.x) })} />
        </label>
        <label>
          Y
          <input aria-label="Y" type="number" value={model.y} onChange={(e) => update({ y: num(e.target.value, model.y) })} />
        </label>
        <label>
          Width
          <input aria-label="Width" type="number" value={model.width} onChange={(e) => update({ width: num(e.target.value, model.width) })} />
        </label>
        <label>
          Height
          <input aria-label="Height" type="number" value={model.height} onChange={(e) => update({ height: num(e.target.value, model.height) })} />
        </label>
        <label>
          Rotate
          <input aria-label="Rotate" type="number" value={model.rotate} onChange={(e) => update({ rotate: num(e.target.value, model.rotate) })} />
        </label>
      </div>

      {isText(model) && (
        <div>
          <label>
            Text
            <input aria-label="Text" type="text" value={model.props.text} onChange={(e) => updateTextProps({ text: e.target.value })} />
          </label>
        </div>
      )}

      {isTextarea(model) && (
        <div>
          <label>
            Name
            <input aria-label="Name" type="text" value={model.props.name} onChange={(e) => updateTextareaProps({ name: e.target.value })} />
          </label>
          <label>
            Label
            <input aria-label="Label" type="text" value={model.props.label} onChange={(e) => updateTextareaProps({ label: e.target.value })} />
          </label>
          <label>
            Placeholder
            <input aria-label="Placeholder" type="text" value={model.props.placeholder || ''} onChange={(e) => updateTextareaProps({ placeholder: e.target.value })} />
          </label>
          <label>
            Rows
            <input aria-label="Rows" type="number" value={model.props.rows ?? 3} onChange={(e) => updateTextareaProps({ rows: Number(e.target.value) || model.props.rows })} />
          </label>
          <label>
            Required
            <input aria-label="Required" type="checkbox" checked={!!model.props.required} onChange={(e) => updateTextareaProps({ required: e.target.checked })} />
          </label>
          <label>
            Help
            <input aria-label="Help" type="text" value={model.props.help || ''} onChange={(e) => updateTextareaProps({ help: e.target.value })} />
          </label>
        </div>
      )}

      {isRadio(model) && (
        <div>
          <label>
            Name
            <input aria-label="Name" type="text" value={model.props.name} onChange={(e) => updateRadioProps({ name: e.target.value })} />
          </label>
          <label>
            Legend
            <input aria-label="Legend" type="text" value={model.props.legend} onChange={(e) => updateRadioProps({ legend: e.target.value })} />
          </label>
          <label>
            Options
            <input aria-label="Options" type="text" value={(model.props.options || []).join(',')} onChange={(e) => updateRadioProps({ options: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })} />
          </label>
          <label>
            Default
            <input aria-label="Default" type="text" value={model.props.defaultValue || ''} onChange={(e) => updateRadioProps({ defaultValue: e.target.value })} />
          </label>
          <label>
            Required
            <input aria-label="Required" type="checkbox" checked={!!model.props.required} onChange={(e) => updateRadioProps({ required: e.target.checked })} />
          </label>
          <label>
            Help
            <input aria-label="Help" type="text" value={model.props.help || ''} onChange={(e) => updateRadioProps({ help: e.target.value })} />
          </label>
        </div>
      )}

      {isCheckbox(model) && (
        <div>
          <label>
            Name
            <input aria-label="Name" type="text" value={model.props.name} onChange={(e) => updateCheckboxProps({ name: e.target.value })} />
          </label>
          <label>
            Legend
            <input aria-label="Legend" type="text" value={model.props.legend} onChange={(e) => updateCheckboxProps({ legend: e.target.value })} />
          </label>
          <label>
            Options
            <input aria-label="Options" type="text" value={(model.props.options || []).join(',')} onChange={(e) => updateCheckboxProps({ options: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })} />
          </label>
          <label>
            Defaults
            <input aria-label="Defaults" type="text" value={(model.props.defaultValues || []).join(',')} onChange={(e) => updateCheckboxProps({ defaultValues: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })} />
          </label>
          <label>
            Required
            <input aria-label="Required" type="checkbox" checked={!!model.props.required} onChange={(e) => updateCheckboxProps({ required: e.target.checked })} />
          </label>
          <label>
            Help
            <input aria-label="Help" type="text" value={model.props.help || ''} onChange={(e) => updateCheckboxProps({ help: e.target.value })} />
          </label>
        </div>
      )}

      {isSelect(model) && (
        <div>
          <label>
            Name
            <input aria-label="Name" type="text" value={model.props.name} onChange={(e) => updateSelectProps({ name: e.target.value })} />
          </label>
          <label>
            Label
            <input aria-label="Label" type="text" value={model.props.label} onChange={(e) => updateSelectProps({ label: e.target.value })} />
          </label>
          <label>
            Options
            <input aria-label="Options" type="text" value={(model.props.options || []).join(',')} onChange={(e) => updateSelectProps({ options: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })} />
          </label>
          <label>
            Default
            <input aria-label="Default" type="text" value={model.props.defaultValue || ''} onChange={(e) => updateSelectProps({ defaultValue: e.target.value })} />
          </label>
          <label>
            Help
            <input aria-label="Help" type="text" value={model.props.help || ''} onChange={(e) => updateSelectProps({ help: e.target.value })} />
          </label>
        </div>
      )}

      {isButton(model) && (
        <div>
          <label>
            Label
            <input aria-label="Label" type="text" value={model.props.label} onChange={(e) => updateButtonProps({ label: e.target.value })} />
          </label>
        </div>
      )}

      {isImage(model) && (
        <div>
          <label>
            Src
            <input aria-label="Src" type="text" value={model.props.src} onChange={(e) => updateImageProps({ src: e.target.value })} />
          </label>
          <label>
            Alt
            <input aria-label="Alt" type="text" value={model.props.alt || ''} onChange={(e) => updateImageProps({ alt: e.target.value })} />
          </label>
        </div>
      )}

      {isInput(model) && (
        <div>
          <label>
            Name
            <input aria-label="Name" type="text" value={model.props.name} onChange={(e) => updateInputProps({ name: e.target.value })} />
          </label>
          <label>
            Label
            <input aria-label="Label" type="text" value={model.props.label} onChange={(e) => updateInputProps({ label: e.target.value })} />
          </label>
          <label>
            Placeholder
            <input aria-label="Placeholder" type="text" value={model.props.placeholder || ''} onChange={(e) => updateInputProps({ placeholder: e.target.value })} />
          </label>
          <label>
            Required
            <input aria-label="Required" type="checkbox" checked={!!model.props.required} onChange={(e) => updateInputProps({ required: e.target.checked })} />
          </label>
          <label>
            Help
            <input aria-label="Help" type="text" value={model.props.help || ''} onChange={(e) => updateInputProps({ help: e.target.value })} />
          </label>
        </div>
      )}
    </div>
  )
}
