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

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">
    <div class="flex flex-wrap items-start gap-4 justify-between">
      <div class="flex items-start gap-3 min-w-0">
        <BaseButton
          type="button"
          variant="secondary"
          icon="arrow-left"
          text
          rounded
          :icon-only="true"
          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">
            Secties voor deze klant staan in het zijmenu (subsidebar) naast de
            hoofdnavigatie.
          </p>
        </div>
      </div>
      <BaseButton variant="secondary" outlined icon="pencil" @click="openHeaderEdit">
        Edit
      </BaseButton>
    </div>

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

    <router-view />

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