<script setup>
import BaseAlert from "../../../../components/base/BaseAlert.vue";
import BaseButton from "../../../../components/base/BaseButton.vue";
import BaseCheckbox from "../../../../components/base/BaseCheckbox.vue";
import BaseColumn from "../../../../components/base/BaseColumn.vue";
import BaseConfirmDialog from "../../../../components/base/BaseConfirmDialog.vue";
import BaseDataTable from "../../../../components/base/BaseDataTable.vue";
import BaseInputText from "../../../../components/base/BaseInputText.vue";
import BaseModal from "../../../../components/base/BaseModal.vue";

import { useCustomerContacts } from "../../composables/useCustomers.js";
import { useConfirm } from "primevue/useconfirm";

import { computed, inject, ref, watch } from "vue";

const props = defineProps({
  customerId: { type: [String, Number], required: true },
});

const cid = computed(() => props.customerId);

const confirm = useConfirm();

const {
  contacts,
  loading,
  error,
  load,
  create,
  update,
  remove,
} = useCustomerContacts(cid);

const dialogVisible = ref(false);
const editing = ref(null);
const saving = ref(false);
const validation = ref({});
const draft = ref({
  first_name: "",
  last_name: "",
  email: "",
  phone: "",
  job_function: "",
  is_primary: false,
});

watch(
  () => cid.value,
  () => {
    load();
  },
  { immediate: true },
);

const saveBump = inject("customerDetailSaveBump", null);
watch(
  () => saveBump?.value,
  (n, p) => {
    if (p === undefined) return;
    load();
  },
);

function openCreate() {
  editing.value = null;
  validation.value = {};
  draft.value = {
    first_name: "",
    last_name: "",
    email: "",
    phone: "",
    job_function: "",
    is_primary: false,
  };
  dialogVisible.value = true;
}

function openEdit(row) {
  editing.value = row;
  validation.value = {};
  draft.value = {
    first_name: row.first_name ?? "",
    last_name: row.last_name ?? "",
    email: row.email ?? "",
    phone: row.phone ?? "",
    job_function: row.job_function ?? "",
    is_primary: !!row.is_primary,
  };
  dialogVisible.value = true;
}

function fieldError(field) {
  const e = validation.value?.[field];
  return Array.isArray(e) ? e[0] : e ?? "";
}

async function saveContact() {
  saving.value = true;
  validation.value = {};
  const payload = {
    first_name: draft.value.first_name.trim(),
    last_name: draft.value.last_name.trim(),
    email: draft.value.email?.trim() || null,
    phone: draft.value.phone?.trim() || null,
    job_function: draft.value.job_function?.trim() || null,
    is_primary: !!draft.value.is_primary,
  };
  try {
    if (!editing.value) {
      await create(payload);
    } else {
      await update(editing.value.id, payload);
    }
    dialogVisible.value = false;
    await load();
  } catch (e) {
    validation.value = e?.response?.data?.errors ?? {};
  } finally {
    saving.value = false;
  }
}

function confirmRemove(row) {
  confirm.require({
    message: `Remove contact ${row.full_name}?`,
    header: "Confirm",
    icon: "pi pi-exclamation-triangle",
    rejectProps: { label: "Cancel", severity: "secondary", outlined: true },
    acceptProps: { label: "Delete", severity: "danger" },
    accept: async () => {
      await remove(row.id);
      await load();
    },
  });
}

defineExpose({ load });
</script>

<template>
  <div>
    <BaseConfirmDialog />
    <BaseAlert v-if="error" severity="error" class="mb-2">{{ error }}</BaseAlert>
    <div class="flex justify-end mb-3">
      <BaseButton
        variant="primary"
        icon="plus"
        label="Add contact"
        @click="openCreate"
      />
    </div>
    <BaseDataTable
      :value="contacts"
      data-key="id"
      :loading="loading"
      striped-rows
    >
      <BaseColumn field="full_name" header="Name" />
      <BaseColumn field="email" header="Email" />
      <BaseColumn field="phone" header="Phone" />
      <BaseColumn field="job_function" header="Function" />
      <BaseColumn header="Primary">
        <template #body="{ data }">
          <span>{{ data.is_primary ? "Yes" : "No" }}</span>
        </template>
      </BaseColumn>
      <BaseColumn header="" body-class="text-end w-36">
        <template #body="{ data }">
          <div class="inline-flex gap-1">
            <BaseButton
              type="button"
              variant="secondary"
              icon="pencil"
              text
              rounded
              size="small"
              :icon-only="true"
              aria-label="Edit contact"
              @click="openEdit(data)"
            />
            <BaseButton
              type="button"
              variant="danger"
              icon="trash"
              text
              rounded
              size="small"
              :icon-only="true"
              aria-label="Remove contact"
              @click="confirmRemove(data)"
            />
          </div>
        </template>
      </BaseColumn>
    </BaseDataTable>

    <BaseModal
      v-model:visible="dialogVisible"
      :title="editing ? 'Edit contact' : 'New contact'"
      width="28rem"
      class="w-full max-w-md"
      :dismissable-mask="true"
    >
      <form class="flex flex-col gap-4 mt-2" @submit.prevent="saveContact">
        <BaseInputText
          id="cc-fn"
          v-model.trim="draft.first_name"
          label="First name"
          required
          fluid
          :error="fieldError('first_name')"
        />
        <BaseInputText
          id="cc-ln"
          v-model.trim="draft.last_name"
          label="Last name"
          required
          fluid
          :error="fieldError('last_name')"
        />
        <BaseInputText
          id="cc-em"
          v-model.trim="draft.email"
          type="email"
          label="Email"
          fluid
          :error="fieldError('email')"
        />
        <BaseInputText
          id="cc-ph"
          v-model.trim="draft.phone"
          label="Phone"
          fluid
        />
        <BaseInputText
          id="cc-jf"
          v-model.trim="draft.job_function"
          label="Job function"
          fluid
        />
        <BaseCheckbox
          id="cc-primary"
          v-model="draft.is_primary"
          :binary="true"
          label="Primary contact"
        />
        <div class="flex justify-end gap-2 pt-2">
          <BaseButton
            variant="secondary"
            outlined
            type="button"
            @click="dialogVisible = false"
          >
            Cancel
          </BaseButton>
          <BaseButton variant="primary" type="submit" :loading="saving">
            Save
          </BaseButton>
        </div>
      </form>
    </BaseModal>
  </div>
</template>
