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

import TabView from "primevue/tabview";
import TabPanel from "primevue/tabpanel";
import Button from "primevue/button";
import ConfirmDialog from "primevue/confirmdialog";
import Message from "primevue/message";

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

import { computed, 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 contactsTabRef = ref(null);
const addressesTabRef = ref(null);
const bannerError = ref("");

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,
}));

const generalFormErrors = computed(() => ({
  ...errors.value,
  form: bannerError.value,
}));

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;
    await Promise.all([
      contactsTabRef.value?.load?.(),
      addressesTabRef.value?.load?.(),
    ]);
  } catch (e) {
    bannerError.value =
      e?.response?.data?.message ?? "Could not update customer.";
  }
}

async function submitGeneral(payload) {
  bannerError.value = "";
  if (!customer.value?.id) return;
  try {
    const updated = await update(customer.value.id, payload);
    customer.value = { ...customer.value, ...updated };
  } catch {
    /* field errors flow via errors ref */
  }
}
</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"
          >
            Customer details and related records.
          </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>

    <TabView class="customers-show-tabs">
      <TabPanel header="General">
        <div class="rounded-2xl border border-surface-200 dark:border-surface-700 bg-surface-0 dark:bg-surface-950 p-5 shadow-sm mt-4">
          <CustomerForm
            embedded
            :draft="generalDraft"
            :saving="saving"
            :errors="generalFormErrors"
            @submit="submitGeneral"
          />
        </div>
      </TabPanel>
      <TabPanel header="Contacts">
        <ContactsTab
          v-if="customerId"
          ref="contactsTabRef"
          class="mt-4"
          :customer-id="customerId"
        />
      </TabPanel>
      <TabPanel header="Addresses">
        <AddressesTab
          v-if="customerId"
          ref="addressesTabRef"
          class="mt-4"
          :customer-id="customerId"
        />
      </TabPanel>
    </TabView>

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