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

const route = useRoute()
const props = defineProps<{ draftId: number }>()
const modal = useTemplateRef('modal')
const savedTxn: Ref<RecurringTransactionResponse | undefined> = ref()

// Form Data:
const dayOfMonth: Ref<number> = ref(1)

async function show(): Promise<RecurringTransactionResponse | undefined> {
  if (!modal.value) return undefined
  savedTxn.value = undefined
  const result = await modal.value.show()
  if (result === 'saved') {
    return savedTxn.value
  }
  return undefined
}

async function addRecurringTransaction() {
  const payload: RecurringTransactionPayload = {
    draftId: props.draftId,
    scheduleExpr: `0 0 0 ${dayOfMonth.value} * *`,
  }
  const api = new TransactionApiClient(getSelectedProfile(route))
  try {
    savedTxn.value = await api.createRecurringTransaction(payload)
    modal.value?.close('saved')
  } catch (err) {
    console.error(err)
    savedTxn.value = undefined
  }
}

defineExpose({ show })
</script>
<template>
  <ModalWrapper ref="modal">
    <template v-slot:default>
      <h2>Add Recurring Transaction</h2>
      <p>
        Use this template to add a <em>recurring transaction</em>. According to the interval you
        specify below, Finnow will create a new draft using this template each time, which you can
        then review and submit.
      </p>
      <p>
        Each time a new draft is created from this template for recurring transactions, the new
        draft's timestamp will be set to the current date and time.
      </p>
      <AppForm>
        <h3>Monthly Schedule</h3>
        <FormGroup>
          <FormControl
            label="Day of Month"
            hint="Specify on which day of the month this transaction occurs."
          >
            <input
              type="number"
              step="1"
              min="1"
              max="31"
              v-model="dayOfMonth"
            />
          </FormControl>
        </FormGroup>
      </AppForm>
    </template>
    <template v-slot:buttons>
      <AppButton @click="addRecurringTransaction()">Add</AppButton>
      <AppButton
        button-style="secondary"
        @click="modal?.close()"
        >Cancel</AppButton
      >
    </template>
  </ModalWrapper>
</template>
