<script setup>
import { ref, nextTick } from 'vue'
import { useMerchApi } from '@/api/merch.js'

const { updateMerch } = useMerchApi()

const props = defineProps({
  modelValue: {
    type: String,
    required: true,
  },
  placeholder: {
    type: String,
    default: 'Enter link here...',
  },
  merchUuid: {
    type: String,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  origin: {
    type: String,
    required: true,
  },
})

const emit = defineEmits(['update:modelValue', 'cancel-edit'])

const tempValue = ref('')
const inputRef = ref(null)
const loading = ref(false)

tempValue.value = props.modelValue

nextTick(() => {
  inputRef.value?.focus?.()
})

const save = async () => {
  const newValue = tempValue.value.trim()

  if (newValue === '') {
    emit('cancel-edit')
    return
  }

  if (newValue === props.modelValue.trim()) {
    emit('cancel-edit')
    return
  }

  loading.value = true

  try {
    await updateMerch({
      merch_uuid: props.merchUuid,
      name: props.name,
      origin: props.origin,
      link: newValue,
    })

    emit('update:modelValue', newValue)
  } catch (error) {
    console.error('Update link error:', error)
  } finally {
    loading.value = false
  }
}

const showModal = ref(false)
const clearLink = async () => {
  showModal.value = true
}

const confirmClearLink = async () => {
  loading.value = true

  try {
    await updateMerch({
      merch_uuid: props.merchUuid,
      name: props.name,
      origin: props.origin,
      link: '',
    })

    emit('update:modelValue', '')
  } catch (error) {
    console.error('Update link error:', error)
  } finally {
    loading.value = false
  }
  showModal.value = false
  cancel()
}

const cancel = () => {
  emit('cancel-edit')
}
</script>

<template>
  <div class="editing-area">
    <n-input
      v-model:value="tempValue"
      type="textarea"
      size="large"
      ref="inputRef"
      @keyup.enter="save"
      @keyup.esc="cancel"
      :placeholder="placeholder"
      :loading="loading"
    />
    <n-button size="small" type="primary" :loading="loading" @click="save">Save</n-button>
    <n-button size="small" @click="cancel">Cancel</n-button>
  </div>
  <div class="center-button-container">
    <n-button type="error" class="center-button" @click="clearLink">Clear link</n-button>
  </div>

  <n-modal v-model:show="showModal" preset="dialog" title="Confirmation">
    <template #default>
      <p>Confirm clear link</p>
    </template>
    <template #action>
      <n-button @click="confirmClearLink" type="error">Clear</n-button>
      <n-button @click="showModal = false">Cancel</n-button>
    </template>
  </n-modal>
</template>

<style scoped>
.editing-area {
  display: flex;
  gap: 6px;
  align-items: center;
  width: 100%;
  flex-wrap: wrap;
}

.editing-area :deep(.n-input) {
  flex: 1;
  min-width: 200px;
}
</style>
