<script setup>
import BaseButton from "../../../components/base/BaseButton.vue";
import CustomerForm from "./partials/CustomerForm.vue";

import Button from "primevue/button";
import ConfirmDialog from "primevue/confirmdialog";
import Message from "primevue/message";

import { useCustomer, useCustomerForm } from "../composables/useCustomers.js";

import { computed, provide, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

const customerId = computed(() => route.params.id);

const { customer, loading, error, load } = useCustomer(customerId);
const { saving, errors, update } = useCustomerForm();

const editDialogVisible = ref(false);
const dialogDraft = ref({});
const bannerError = ref("");

const saveBump = ref(0);

provide("customerDetailSaveBump", saveBump);

function bumpRelatedLists() {
  saveBump.value += 1;
}

provide("customerDetailContext", {
  customer,
  loading,
  error,
  load,
  saving,
  errors,
  update,
  bannerError,
  bumpRelatedLists,
});

watch(
  customerId,
  () => {
    load();
  },
  { immediate: true },
);

const generalDraft = computed(() => ({
  name: customer.value?.name ?? "",
  email: customer.value?.email ?? "",
  phone: customer.value?.phone ?? "",
  website: customer.value?.website ?? "",
  notes: customer.value?.notes ?? "",
  is_active: customer.value?.is_active !== false,
}));

function openHeaderEdit() {
  dialogDraft.value = { ...generalDraft.value };
  editDialogVisible.value = true;
}

async function submitHeaderEdit(payload) {
  bannerError.value = "";
  if (!customer.value?.id) return;
  try {
    const updated = await update(customer.value.id, payload);
    customer.value = { ...customer.value, ...updated };
    editDialogVisible.value = false;
    bumpRelatedLists();
  } catch (e) {
    bannerError.value =
      e?.response?.data?.message ?? "Could not update customer.";
  }
}
</script>

<template>
  <div class="flex flex-col gap-4">
    <ConfirmDialog />

    <div class="flex flex-wrap items-start gap-4 justify-between">
      <div class="flex items-start gap-3 min-w-0">
        <Button
          type="button"
          icon="pi pi-arrow-left"
          rounded
          text
          severity="secondary"
          aria-label="Back to customers"
          @click="router.push({ name: 'customers' })"
        />
        <div class="min-w-0">
          <h1
            class="text-2xl font-semibold tracking-tight text-surface-950 dark:text-surface-0 m-0 truncate"
          >
            {{ loading ? "…" : customer?.name ?? "Customer" }}
          </h1>
          <p class="text-sm text-surface-600 dark:text-surface-400 mt-1 mb-0">
            Gebruik het menu links voor Algemeen, Contacten en Adressen.
          </p>
        </div>
      </div>
      <BaseButton variant="secondary" outlined icon="pencil" @click="openHeaderEdit">
        Edit
      </BaseButton>
    </div>

    <Message v-if="error" severity="error" class="rounded-2xl">{{ error }}</Message>
    <Message v-if="bannerError" severity="error" class="rounded-2xl">{{
      bannerError
    }}</Message>

    <router-view />

    <CustomerForm
      v-model:visible="editDialogVisible"
      :draft="dialogDraft"
      :saving="saving"
      :errors="errors"
      title="Edit customer"
      @submit="submitHeaderEdit"
      @cancel="editDialogVisible = false"
    />
  </div>
</template>
