<script setup>
import { ref, watch } from 'vue';
import DialogModal from './DialogModal.vue';
import InputLabel from './InputLabel.vue';
import SectionTitle from './SectionTitle.vue';
import TextInput from './TextInput.vue';
import InputError from './InputError.vue';
import PrimaryButton from './PrimaryButton.vue';
import axios from 'axios';

/*
  TRR (bank account) create/update
  Fields aligned to migration/model: iban, bank_name, bic_swift, account_number, routing_number, currency, country_code, holder_name, notes
  Routes: person.trr.create / person.trr.update
*/

const props = defineProps({
  show: { type: Boolean, default: false },
  person: { type: Object, required: true },
  currencies: { type: Array, default: () => ['EUR'] },
  edit: { type: Boolean, default: false },
  id: { type: Number, default: 0 },
});

const processing = ref(false);
const errors = ref({});
const emit = defineEmits(['close']);

const close = () => { emit('close'); setTimeout(() => { errors.value = {}; }, 300); };

const initialCurrency = () => (props.currencies && props.currencies.length ? props.currencies[0] : 'EUR');

const form = ref({
  iban: '',
  bank_name: '',
  bic_swift: '',
  account_number: '',
  routing_number: '',
  currency: initialCurrency(),
  country_code: '',
  holder_name: '',
  notes: ''
});

const resetForm = () => {
  form.value = { iban: '', bank_name: '', bic_swift: '', account_number: '', routing_number: '', currency: initialCurrency(), country_code: '', holder_name: '', notes: '' };
};

const create = async () => {
  processing.value = true; errors.value = {};
  try {
  const { data } = await axios.post(route('person.trr.create', props.person), form.value);
  if (!Array.isArray(props.person.trrs)) props.person.trrs = (props.person.bank_accounts || props.person.accounts || props.person.bankAccounts || []);
    (props.person.trrs).push(data.trr);
    processing.value = false; close(); resetForm();
  } catch (e) {
    errors.value = e?.response?.data?.errors || {}; processing.value = false;
  }
};

const update = async () => {
  processing.value = true; errors.value = {};
  try {
    const { data } = await axios.put(route('person.trr.update', { person: props.person, trr_id: props.id }), form.value);
  let list = props.person.trrs || props.person.bank_accounts || props.person.accounts || props.person.bankAccounts || [];
    const idx = list.findIndex(a => a.id === data.trr.id);
    if (idx !== -1) list[idx] = data.trr;
    processing.value = false; close(); resetForm();
  } catch (e) {
    errors.value = e?.response?.data?.errors || {}; processing.value = false;
  }
};

watch(
  () => props.id,
  (id) => {
    if (props.edit && id) {
      const list = props.person.trrs || props.person.bank_accounts || props.person.accounts || props.person.bankAccounts || [];
      const current = list.find(a => a.id === id);
      if (current) {
        form.value = {
          iban: current.iban || current.account_number || current.number || '',
          bank_name: current.bank_name || '',
          bic_swift: current.bic_swift || '',
          account_number: current.account_number || '',
          routing_number: current.routing_number || '',
          currency: current.currency || initialCurrency(),
          country_code: current.country_code || '',
          holder_name: current.holder_name || '',
          notes: current.notes || ''
        };
        return;
      }
    }
    resetForm();
  },
  { immediate: true }
);

const submit = () => (props.edit ? update() : create());
</script>

<template>
  <DialogModal :show="show" @close="close">
    <template #title>
      <span v-if="edit">Spremeni TRR</span>
      <span v-else>Dodaj TRR</span>
    </template>
    <template #content>
      <form @submit.prevent="submit">
        <SectionTitle class="border-b mb-4">
          <template #title>TRR</template>
        </SectionTitle>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="trr_iban" value="IBAN" />
          <TextInput id="trr_iban" v-model="form.iban" type="text" class="mt-1 block w-full" autocomplete="off" />
          <InputError v-if="errors.iban" v-for="err in errors.iban" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="trr_bank_name" value="Banka" />
          <TextInput id="trr_bank_name" v-model="form.bank_name" type="text" class="mt-1 block w-full" autocomplete="organization" />
          <InputError v-if="errors.bank_name" v-for="err in errors.bank_name" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="trr_bic" value="BIC / SWIFT" />
          <TextInput id="trr_bic" v-model="form.bic_swift" type="text" class="mt-1 block w-full" autocomplete="off" />
          <InputError v-if="errors.bic_swift" v-for="err in errors.bic_swift" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="trr_accnum" value="Številka računa" />
          <TextInput id="trr_accnum" v-model="form.account_number" type="text" class="mt-1 block w-full" autocomplete="off" />
          <InputError v-if="errors.account_number" v-for="err in errors.account_number" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="trr_route" value="Usmerjevalna številka (routing)" />
          <TextInput id="trr_route" v-model="form.routing_number" type="text" class="mt-1 block w-full" autocomplete="off" />
          <InputError v-if="errors.routing_number" v-for="err in errors.routing_number" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4" v-if="currencies && currencies.length">
          <InputLabel for="trr_currency" value="Valuta" />
          <select id="trr_currency" v-model="form.currency" class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
            <option v-for="c in currencies" :key="c">{{ c }}</option>
          </select>
          <InputError v-if="errors.currency" v-for="err in errors.currency" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="trr_cc" value="Koda države (2-znaki, npr. SI)" />
          <TextInput id="trr_cc" v-model="form.country_code" type="text" class="mt-1 block w-full" autocomplete="country" />
          <InputError v-if="errors.country_code" v-for="err in errors.country_code" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="trr_holder" value="Imetnik računa" />
          <TextInput id="trr_holder" v-model="form.holder_name" type="text" class="mt-1 block w-full" autocomplete="name" />
          <InputError v-if="errors.holder_name" v-for="err in errors.holder_name" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="trr_notes" value="Opombe" />
          <TextInput id="trr_notes" v-model="form.notes" type="text" class="mt-1 block w-full" autocomplete="off" />
          <InputError v-if="errors.notes" v-for="err in errors.notes" :key="err" :message="err" />
        </div>

        <div class="flex justify-end mt-4">
          <PrimaryButton :class="{ 'opacity-25': processing }" :disabled="processing">Shrani</PrimaryButton>
        </div>
      </form>
    </template>
  </DialogModal>
</template>
