<template>
  <div>
    <v-container v-if="loading" class="text-center py-8">
      <v-progress-circular color="primary" indeterminate />
      <p class="text-body-1 text-grey mt-4">Cargando pedido...</p>
    </v-container>

    <v-alert v-else-if="error" class="my-4" type="error">
      {{ error }}
    </v-alert>

    <v-card v-else-if="purchase" class="rounded-lg">
      <v-card-item>
        <template #prepend>
          <v-icon color="primary" size="36">mdi-receipt-text-outline</v-icon>
        </template>
        <v-card-title class="font-weight-bold text-h6">
          {{ purchase.type === 'catalog' ? 'Resumen del pedido' : 'Resumen de la compra' }}
        </v-card-title>
      </v-card-item>
      <v-divider />
      <v-card-text>
        <OrderAccessInfo :code="purchase.code" />
        <v-divider class="my-3" />
        <v-list>
          <v-list-item>
            <template #prepend>
              <v-icon>mdi-calendar</v-icon>
            </template>
            <v-list-item-title>Fecha</v-list-item-title>
            <v-list-item-subtitle>{{ purchase.date }}</v-list-item-subtitle>
          </v-list-item>
          <OrderCustomer :customer="purchase.customer" />
          <OrderPayment
            v-if="purchase.type === 'sale'"
            :payment-method="purchase.payment_method"
          />
        </v-list>
        <v-divider class="my-3" />
        <OrderLines :lines="purchase.lines" />
        <v-divider class="my-3" />
        <OrderTotal :total="calculateTotal(purchase.lines)" />
        <ProvenanceSection
          v-if="purchase.product_provenance?.length"
          :provenance="purchase.product_provenance"
        />
      </v-card-text>
    </v-card>
  </div>
</template>

<script setup>
  import OrderAccessInfo from '@/components/order/OrderAccessInfo.vue'
  import OrderCustomer from '@/components/order/OrderCustomer.vue'
  import OrderLines from '@/components/order/OrderLines.vue'
  import OrderPayment from '@/components/order/OrderPayment.vue'
  import OrderTotal from '@/components/order/OrderTotal.vue'
  import ProvenanceSection from '@/components/provenance/ProvenanceSection.vue'

  defineProps({
    purchase: {
      type: Object,
      default: null,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    error: {
      type: String,
      default: '',
    },
  })

  function calculateTotal (lines = []) {
    return lines.reduce((total, line) => {
      return total + Number(line.unit_price || 0) * Number(line.quantity || 0)
    }, 0)
  }
</script>
