<script setup>
import {onMounted, ref} from 'vue';
import InvoiceProcessorOverviewBox from "@/views/dashboards/superUserDashboard/collectedOrderInvoices/InvoiceProcessorOverviewBox.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";

const errors = ref([]);

const addErrorMessage = (message, httpStatusCode = null) => {
  // Check if message is an object and has a response property
  if (typeof message === 'object' && message.hasOwnProperty('data')) {
    // Extract the error message from the response
    if (message.data && message.data.data && message.data.data.message) {
      message = message.data.data.message;
    } else if (message.statusText) {
      message = message.statusText;
    } else {
      message = 'Der opstod en fejl under indlæsning af data.';
    }
  }
  errors.value.push({
    type: 'error',
    message: message,
    httpStatusCode: httpStatusCode,
  });
};

const removeErrorMessage = (index) => {
  errors.value.splice(index, 1);
};
const clearErrorMessages = () => {
  errors.value = [];
};
const hasErrorMessages = () => {
  return errors.value.length > 0;
};

// Define the dynamic data properties
const loading = ref(false);
const total = ref(0);
const paid = ref(0);
const unpaid = ref(0);
const overdue = ref(0);
const booked = ref(0);
const draft = ref(0);
const sent = ref(0);
const error = ref(0);

const refresh = () => {
  loading.value = true;
  SessionUser.request(
      '/collected-invoices/economic/overview',
      'GET',
      {}
  ).then((response) => {
    if (response.status === 200) {
      const result = response.data.data;
      console.log(result, 'result');
      total.value = result.total;
      paid.value = result.paid;
      unpaid.value = result.unpaid;
      overdue.value = result.overdue;
      booked.value = result.booked;
      draft.value = result.draft;
      sent.value = result.sent;
      error.value = result.error;
    } else {
      addErrorMessage(response, response.status);
    }
  }).catch((error) => {
    console.log(error);
    if (error.response) {
      addErrorMessage(error.response, error.response.status);
    } else {
      addErrorMessage('Der opstod en fejl under indlæsning af data.');
    }
  }).finally(() => {
    loading.value = false;
  });
};

const options = ref({
  module: {
    name: 'Economic',
    icon: 'fas fa-file-invoice-dollar',
    color: 'has-text-grey',
  },
  actions: [
    {
      label: 'Opdater status for faktura kladder',
      icon: 'fas fa-sync-alt',
      action: () => {
        SessionUser.objects.collectedOrderInvoices.functions.economic.runCheckDrafts().then((response) => {
          console.log('Check drafts response', response);
          refresh();
        }).catch((error) => {
          addErrorMessage(error);
        });
      },
      disabled: false,
    },
    {
      label: 'Check fejl',
      icon: 'fas fa-sync-alt',
      action: () => {
        SessionUser.objects.collectedOrderInvoices.functions.economic.runCheckErrors().then((response) => {
          console.log('Check errors response', response);
          refresh();
        }).catch((error) => {
          addErrorMessage(error);
        });
      },
      disabled: false,
    },
  ],
});

const counts = ref({
  total: {
    label: 'Total',
    value: total,
    icon: 'fas fa-file-invoice-dollar',
    color: 'has-text-grey',
  },
  /**
  paid: {
    label: 'Betalt',
    value: paid,
    icon: 'fas fa-check-circle',
    color: 'has-text-grey-darker',
  },
  unpaid: {
    label: 'Ikke betalt',
    value: unpaid,
    icon: 'fas fa-times-circle',
    color: 'has-text-danger',
  },
  overdue: {
    label: 'Forsinket',
    value: overdue,
    icon: 'fas fa-clock',
    color: 'has-text-warning',
  },
  */
  booked: {
    label: 'Bogført',
    value: booked,
    icon: 'fas fa-book',
    color: 'has-text-success',
  },
  unbooked: {
    label: 'Faktura kladde',
    value: draft,
    icon: 'fas fa-file-invoice',
    color: 'has-text-warning',
  },
  /**
  sent: {
    label: 'Sendt',
    value: sent,
    icon: 'fas fa-paper-plane',
    color: 'has-text-grey-dark',
  },
  */
  error: {
    label: 'Fejl',
    value: error,
    icon: 'fas fa-exclamation-triangle',
    color: 'has-text-danger',
  },
});

// Fetch data on mounted
refresh();
</script>

<template>
  <div class="columns is-multiline is-mobile">
    <!-- Display the available actions -->
    <div class="column is-full">
      <div class="card">
        <div class="card-header">
          <div class="card-header-icon">
            <span class="icon">
              <i class="fas fa-cogs"></i>
            </span>
          </div>
          <p class="card-header-title">
            Handlinger
          </p>
        </div>
        <!-- Display the available action buttons -->
        <div class="card-content">
          <div class="buttons">
            <template
              v-for="(action, index) in options.actions"
              :key="index"
            >
              <button
                class="button is-dark is-outlined"
                @click="action.action()"
                :disabled="action.disabled"
              >
                <span class="icon">
                  <i :class="action.icon"></i>
                </span>
                <span>{{ action.label }}</span>
              </button>
            </template>
          </div>
        </div>
      </div>
    </div>
    <!-- Display error messages if any -->
    <template v-if="hasErrorMessages()">
      <div class="column is-full">
        <div v-for="(error, index) in errors" :key="index" class="notification is-danger">
          <!-- Display the error code if available -->
          <strong v-if="error.httpStatusCode">Error {{ error.httpStatusCode }}:</strong>
          <!-- Display the error message -->
          {{ error.message }}
          <button class="delete" @click="removeErrorMessage(index)"></button>
        </div>
      </div>
    </template>
    <!-- Display the overview boxes -->
    <template v-for="count in counts" :key="count">
      <div class="column is-3-desktop">
        <InvoiceProcessorOverviewBox
          v-bind:options="options"
          v-bind:count="count"
          v-bind:loading="loading"
          @refresh="refresh"
        />
      </div>
    </template>
  </div>
  <!-- Other content can be added here -->
</template>

<style scoped>

</style>