<script setup>
import { computed, watch, watchEffect } from 'vue'
import { Inertia } from '@inertiajs/inertia'
import { once } from 'lodash'
import { ppn } from '@/utils/helpers'
import { optionStatus } from './config'
import { cartTable } from './config'
import Details from './Components/Details.vue'
import Cart from './Components/Cart.vue'
import { useProductCart } from './Composables/useProductCart'
import { useDialog } from './Composables/useDialog'
import { useForm } from '@/composables/useForm'
import AppInputText from '@/components/AppInputText.vue'
import AppInputNumber from '@/components/AppInputNumber.vue'
import AppDropdown from '@/components/AppDropdown.vue'
import AppAutoComplete from '@/components/AppAutoComplete.vue'
import DashboardLayout from '@/layouts/Dashboard/DashboardLayout.vue'

const props = defineProps({
  number: String,
  ppn: Number,
  suppliers: {
    type: Array,
    default: [],
  },
  products: {
    type: Array,
    default: [],
  },
  productPurchase: Object,
})

const form = useForm({
  status: 'pending',
  price: null,
  qty: null,
  supplier: null,
  product: null,
  ppn: props.ppn,
  checkedPpn: false,
})

const onSubmit = () => {
  form
    .transform((data) => ({
      number: props.number,
      status: data.status,
      ppn: data.checkedPpn,
      supplier_id: data.supplier.id,
      products: productCart,
    }))
    .post(route('purchases.store'), {
      onSuccess: () => {
        form.reset()

        onClearProductCart()
      },
    })
}

watchEffect(() => {
  if (props.productPurchase?.number) {
    form.price = props.productPurchase.price

    form.qty = props.productPurchase.qty
  } else {
    form.price = null
  }
})

watch(
  () => form.product,
  () => {
    if (form.product?.number) {
      Inertia.reload({
        data: {
          productNumber: form.product.number,
          supplierId: form.supplier.id,
        },
        only: ['productPurchase'],
      })
    }
  }
)

const productUnit = computed(() => form.product?.unit)

const productPurchasePrice = computed(() => props.productPurchase?.price)

const productPurchasePpn = computed(() => props.productPurchase?.ppn)

const productPurchaseQty = computed(() => props.productPurchase?.qty)

const dropdownStatus = computed(() => {
  return optionStatus.filter((val) => val.value != 'success')
})

const {
  productCart,
  productErrors,
  onClearProductCart,
  onAddProduct,
  onDeleteProduct,
  totalProductPrice,
} = useProductCart(form)

const { onShowCreateProduct, onShowCreateSupplier } = useDialog()
</script>

<template>
  <DashboardLayout title="Tambah Pembelian">
    <DynamicDialog />

    <div class="grid">
      <div class="col-12 md:col-8">
        <div class="grid">
          <div class="col-12">
            <Card>
              <template #title> Transaksi </template>
              <template #content>
                <div class="grid">
                  <div class="col-12 md:col-6">
                    <AppDropdown
                      label="Status"
                      placeholder="status"
                      :options="dropdownStatus"
                      :error="form.errors.status"
                      v-model="form.status"
                    />
                  </div>

                  <div class="col-12 md:col-6">
                    <AppAutoComplete
                      empty
                      label="Supplier"
                      placeholder="supplier"
                      field="name"
                      refresh-data="suppliers"
                      v-model="form.supplier"
                      :error="form.errors.suppliers_id"
                      :suggestions="suppliers"
                    >
                      <template #item="slotProps">
                        <template v-if="slotProps.item">
                          <div class="flex flex-column">
                            <span>{{ slotProps.item.name }}</span>
                            <span>{{ slotProps.item.phone }}</span>
                          </div>
                        </template>
                      </template>

                      <template #empty>
                        <span
                          class="cursor-pointer"
                          style="color: var(--primary-color)"
                          @click="onShowCreateSupplier"
                        >
                          Tambah Supplier
                        </span>
                      </template>
                    </AppAutoComplete>
                  </div>
                </div>
              </template>
            </Card>
          </div>

          <div class="col-12">
            <Card>
              <template #title>Produk</template>
              <template #content>
                <div class="grid">
                  <div class="col-12 md:col-6">
                    <AppAutoComplete
                      :disabled="!form.supplier?.id"
                      empty
                      label="Produk"
                      placeholder="produk"
                      field="name"
                      refresh-data="products"
                      v-model="form.product"
                      :error="form.errors.product"
                      :suggestions="products"
                    >
                      <template #item="slotProps">
                        <template v-if="slotProps.item">
                          <div class="flex flex-column">
                            <span>{{ slotProps.item.number }}</span>
                            <span>{{ slotProps.item.name }}</span>
                          </div>
                        </template>
                      </template>

                      <template #empty>
                        <span
                          class="cursor-pointer"
                          style="color: var(--primary-color)"
                          @click="onShowCreateProduct"
                        >
                          Tambah Produk
                        </span>
                      </template>
                    </AppAutoComplete>
                  </div>

                  <div class="col-12 md:col-6">
                    <AppInputText
                      disabled
                      label="Satuan"
                      placeholder="satuan"
                      v-model="productUnit"
                    />
                  </div>

                  <Divider type="dashed" />

                  <div class="col-12">
                    <h3 class="text-lg">Riwayat Produk Sebelumnya</h3>
                  </div>

                  <div class="col-12 md:col-6">
                    <AppInputNumber
                      disabled
                      class="mb-0"
                      label="Harga "
                      placeholder="harga"
                      v-model="productPurchasePrice"
                    />

                    <span v-if="productPurchasePpn" class="text-xs">
                      Harga sudah termasuk PPN {{ ppn }} %
                    </span>
                  </div>

                  <div class="col-12 md:col-6">
                    <AppInputText
                      disabled
                      label="Kuantitas"
                      placeholder="kuantitas"
                      type="number"
                      v-model="productPurchaseQty"
                    />
                  </div>

                  <Divider type="dashed" />

                  <div class="col-12 md:col-6">
                    <AppInputNumber
                      :disabled="!form.product?.id"
                      label="Harga Terbaru"
                      placeholder="harga terbaru"
                      v-model="form.price"
                    />
                  </div>

                  <div class="col-12 md:col-6">
                    <AppInputText
                      :disabled="!form.product?.id"
                      label="Kuantitas"
                      placeholder="kuantitas"
                      type="number"
                      v-model="form.qty"
                    />
                  </div>
                </div>
              </template>
              <template #footer>
                <div class="flex flex-column md:flex-row justify-content-end">
                  <Button
                    label="Tambah Produk"
                    icon="pi pi-check"
                    class="p-button-outlined"
                    :class="{ 'p-button-danger': productErrors.length }"
                    :disabled="
                      !form.price ||
                      !Number(form.qty) ||
                      !form.product?.number ||
                      productErrors.length
                    "
                    @click="onAddProduct"
                  />
                </div>
              </template>
            </Card>
          </div>

          <div class="col-12">
            <Cart
              title="Keranjang Produk"
              :product-cart="productCart"
              :header-table="cartTable"
              :btn-edit-show="false"
              v-model:checked-ppn="form.checkedPpn"
              @delete="onDeleteProduct"
            />
          </div>
        </div>
      </div>

      <div class="col-12 md:col-4">
        <Details
          title="Detail Pembelian"
          message="Pastikan semua produk sudah benar"
          :number="number"
          :status="form.status"
          :person="form.supplier"
          :product="form.product"
          :price="totalProductPrice()"
          :disabled="
            form.processing ||
            !form.status ||
            !form.supplier?.id ||
            productCart.length === 0
          "
          @submit="onSubmit"
        />
      </div>
    </div>
  </DashboardLayout>
</template>
