import { useTranslation } from 'react-i18next'
import { Button, EmptyState } from '@/ui'
import { PlusIcon } from '@phosphor-icons/react'
import { PropertyEditor } from './PropertyEditor'
import { newPropertyDef, type PropertyDef } from './types'

type Props = {
  properties: PropertyDef[]
  onChange: (next: PropertyDef[]) => void
}

export const SchemaBuilder = ({ properties, onChange }: Props) => {
  const { t } = useTranslation()

  const updateAt = (index: number, next: PropertyDef) => {
    const copy = properties.slice()
    copy[index] = next
    onChange(copy)
  }

  const removeAt = (index: number) => {
    onChange(properties.filter((_, i) => i !== index))
  }

  const moveBy = (index: number, delta: number) => {
    const target = index + delta
    if (target < 0 || target >= properties.length) return
    const copy = properties.slice()
    const [item] = copy.splice(index, 1)
    copy.splice(target, 0, item)
    onChange(copy)
  }

  const add = () => onChange([...properties, newPropertyDef()])

  return (
    <div className="space-y-3">
      {properties.length === 0 && (
        <EmptyState title={t('schema.empty')} />
      )}
      {properties.map((p, i) => (
        <PropertyEditor
          key={p.id}
          prop={p}
          index={i}
          total={properties.length}
          onChange={(next) => updateAt(i, next)}
          onRemove={() => removeAt(i)}
          onMoveUp={() => moveBy(i, -1)}
          onMoveDown={() => moveBy(i, 1)}
        />
      ))}
      <Button
        type="button"
        variant="secondary"
        leftIcon={<PlusIcon weight="bold" size={16} />}
        onClick={add}
      >
        {t('schema.addProperty')}
      </Button>
    </div>
  )
}
