<template>
  <div>
    <h1 class="text-h4 mb-4">Import Transactions</h1>
    <v-card>
      <v-card-text>
        <v-file-input v-model="file" label="Select file to import" accept=".ofx,.qfx,.csv,.qif" prepend-icon="mdi-upload" />
        <v-select v-model="selectedAccount" label="Target Account" :items="accounts" item-title="name" item-value="id" />
        <v-btn color="primary" :disabled="!file || !selectedAccount" @click="uploadFile" :loading="uploading">Import</v-btn>
      </v-card-text>
    </v-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useAccountsStore } from '@/stores/accounts'
import api from '@/services/api'

const accountsStore = useAccountsStore()
const accounts = ref(accountsStore.accounts)
const file = ref<File | null>(null)
const selectedAccount = ref('')
const uploading = ref(false)

onMounted(async () => {
  await accountsStore.fetchAccounts()
  accounts.value = accountsStore.accounts
})

async function uploadFile() {
  if (!file.value || !selectedAccount.value) return
  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file.value)
    await api.post(`/imports/upload?accountId=${selectedAccount.value}`, formData, { headers: { 'Content-Type': 'multipart/form-data' } })
    file.value = null
  } finally {
    uploading.value = false
  }
}
</script>
