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

import Button from "primevue/button";
import Column from "primevue/column";
import ConfirmDialog from "primevue/confirmdialog";
import DataTable from "primevue/datatable";
import Dialog from "primevue/dialog";
import Checkbox from "primevue/checkbox";
import InputText from "primevue/inputtext";

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

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

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

    <Dialog
      v-model:visible="dialogVisible"
      modal
      :header="editing ? 'Edit contact' : 'New contact'"
      class="w-full max-w-md"
      :dismissable-mask="true"
    >
      <form class="flex flex-col gap-3 mt-2" @submit.prevent="saveContact">
        <div class="flex flex-col gap-1">
          <label class="label-small">First name</label>
          <InputText v-model.trim="draft.first_name" fluid required />
          <p v-if="fieldError('first_name')" class="text-xs text-red-600 m-0">
            {{ fieldError("first_name") }}
          </p>
        </div>
        <div class="flex flex-col gap-1">
          <label class="label-small">Last name</label>
          <InputText v-model.trim="draft.last_name" fluid required />
          <p v-if="fieldError('last_name')" class="text-xs text-red-600 m-0">
            {{ fieldError("last_name") }}
          </p>
        </div>
        <div class="flex flex-col gap-1">
          <label class="label-small">Email</label>
          <InputText v-model.trim="draft.email" type="email" fluid />
          <p v-if="fieldError('email')" class="text-xs text-red-600 m-0">
            {{ fieldError("email") }}
          </p>
        </div>
        <div class="flex flex-col gap-1">
          <label class="label-small">Phone</label>
          <InputText v-model.trim="draft.phone" fluid />
        </div>
        <div class="flex flex-col gap-1">
          <label class="label-small">Job function</label>
          <InputText v-model.trim="draft.job_function" fluid />
        </div>
        <div class="flex items-center gap-2 pt-2">
          <Checkbox v-model="draft.is_primary" binary input-id="cc-primary" />
          <label for="cc-primary" class="label-small cursor-pointer">
            Primary contact
          </label>
        </div>
        <div class="flex justify-end gap-2 pt-2">
          <Button
            type="button"
            label="Cancel"
            severity="secondary"
            outlined
            @click="dialogVisible = false"
          />
          <BaseButton variant="primary" type="submit" :loading="saving">
            Save
          </BaseButton>
        </div>
      </form>
    </Dialog>
  </div>
</template>
