<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'
import AppForm from '@/components/common/form/AppForm.vue'
import FormControl from '@/components/common/form/FormControl.vue'
import FormGroup from '@/components/common/form/FormGroup.vue'
import ModalWrapper from '@/components/common/ModalWrapper.vue'
import { TransactionApiClient, type TransactionVendor } from '@/api/transaction'
import AppButton from './common/AppButton.vue'
import { useRoute } from 'vue-router'
import { getSelectedProfile } from '@/api/profile'

const route = useRoute()
const props = defineProps<{
  vendor?: TransactionVendor
}>()
const emit = defineEmits<{ saved: [TransactionVendor] }>()
const modal = useTemplateRef('modal')

// Form data:
const name = ref('')
const description = ref('')

function show(): Promise<string | undefined> {
  if (!modal.value) return Promise.resolve(undefined)
  name.value = props.vendor?.name ?? ''
  description.value = props.vendor?.description ?? ''
  return modal.value.show()
}

function canSave() {
  const inputValid = name.value.trim().length > 0
  if (!inputValid) return false
  if (props.vendor) {
    const newDesc = description.value.trim().length === 0 ? null : description.value.trim()
    return props.vendor.name.trim() !== name.value.trim() || props.vendor.description !== newDesc
  }
  return true
}

async function doSave() {
  const api = new TransactionApiClient(getSelectedProfile(route))
  const payload = {
    name: name.value.trim(),
    description: description.value.trim().length === 0 ? null : description.value.trim(),
  }
  try {
    let savedVendor = null
    if (props.vendor) {
      savedVendor = await api.updateVendor(props.vendor.id, payload)
    } else {
      savedVendor = await api.createVendor(payload)
    }
    emit('saved', savedVendor)
    modal.value?.close('saved')
  } catch (err) {
    console.error(err)
    modal.value?.close()
  }
}

defineExpose({ show })
</script>
<template>
  <ModalWrapper ref="modal">
    <template v-slot:default>
      <h2>{{ vendor ? 'Edit' : 'Add' }} Vendor</h2>
      <AppForm>
        <FormGroup>
          <FormControl label="Name">
            <input
              type="text"
              v-model="name"
            />
          </FormControl>
          <FormControl
            label="Description"
            style="min-width: 300px"
          >
            <textarea v-model="description"></textarea>
          </FormControl>
        </FormGroup>
      </AppForm>
    </template>
    <template v-slot:buttons>
      <AppButton
        :disabled="!canSave()"
        @click="doSave()"
        >Save</AppButton
      >
      <AppButton
        button-style="secondary"
        @click="modal?.close()"
        >Cancel</AppButton
      >
    </template>
  </ModalWrapper>
</template>
