<template>
  <div class="vm-json-editor" :class="{ 'is-fill': fill }">
    <textarea
      class="vm-json-editor__input vm-scroll"
      :class="{ 'is-error': Boolean(error) }"
      :value="inner"
      :disabled="disabled"
      :placeholder="placeholder ?? crudLabel('jsonPlaceholder')"
      :rows="fill ? undefined : rows"
      @input="onInput"
      @blur="validate"
    />
    <p v-if="error" class="vm-json-editor__error">{{ error }}</p>
  </div>
</template>

<script setup lang="ts">
import { crudLabel } from '../style'
import { ref, watch } from 'vue'
import { parseJsonInput, prettyJson, textOfJson } from '../../lib/json'

defineOptions({ name: 'vm-json-editor' })

const props = withDefaults(
  defineProps<{
    modelValue?: unknown
    placeholder?: string
    rows?: number
    disabled?: boolean
    /** blur 时自动格式化 */
    formatOnBlur?: boolean
    /** 在 flex 布局中铺满剩余高度 */
    fill?: boolean
  }>(),
  {
    placeholder: undefined,
    rows: 8,
    formatOnBlur: true,
    fill: false,
  },
)

const emit = defineEmits<{
  'update:modelValue': [v: unknown]
  change: [v: unknown]
  error: [msg: string]
}>()

const inner = ref('')
const error = ref('')
/** 流式写入时跳过 modelValue 回写覆盖 */
const streaming = ref(false)

function syncFromModel() {
  if (streaming.value) return
  inner.value = prettyJson(props.modelValue, '')
  error.value = ''
}

watch(
  () => props.modelValue,
  () => syncFromModel(),
  { immediate: true },
)

function onInput(e: Event) {
  inner.value = (e.target as HTMLTextAreaElement).value
  error.value = ''
}

function validate() {
  if (streaming.value) return
  const parsed = parseJsonInput(inner.value)
  if (!parsed.ok) {
    error.value = parsed.error
    emit('error', parsed.error)
    return
  }
  if (props.formatOnBlur) {
    inner.value = prettyJson(parsed.value, '')
  }
  error.value = ''
  emit('update:modelValue', parsed.value)
  emit('change', parsed.value)
}

defineExpose({
  validate,
  getText: () => inner.value,
  setText: (v: unknown) => {
    inner.value = typeof v === 'string' ? v : textOfJson(v)
    error.value = ''
  },
  beginStream: () => {
    streaming.value = true
    error.value = ''
  },
  endStream: () => {
    streaming.value = false
  },
})
</script>

<style lang="scss" scoped>
.vm-json-editor {
  display: grid;
  gap: 6px;
  min-width: 0;

  &.is-fill {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }
}

.vm-json-editor__input {
  width: 100%;
  min-height: 72px;
  padding: 8px var(--vm-control-padding-x, 12px);
  border: 1px solid var(--input, var(--border));
  border-radius: var(--vm-control-radius);
  background: var(--muted);
  color: var(--foreground);
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  outline: none;
  transition: border-color 0.15s ease;

  .is-fill & {
    flex: 1 1 auto;
    min-height: 0;
    height: 100%;
    resize: none;
  }

  &:focus,
  &:focus-visible {
    border-color: var(--focus-border, var(--brand));
    box-shadow: none;
  }

  &.is-error {
    border-color: var(--danger, var(--destructive));
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.vm-json-editor__error {
  margin: 0;
  font-size: 12px;
  color: var(--danger);
}
</style>
