<script setup>
import BaseButton from "../../../components/base/BaseButton.vue";
import BaseColumn from "../../../components/base/BaseColumn.vue";
import BaseDataTable from "../../../components/base/BaseDataTable.vue";
import BaseIndex from "../../../components/base/BaseIndex.vue";
import BaseInputText from "../../../components/base/BaseInputText.vue";
import BaseModal from "../../../components/base/BaseModal.vue";
import { useBaseToast } from "../../../composables/useBaseToast.js";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";

import { useOffersApi } from "../composables/useOffersApi.js";

const router = useRouter();
const toast = useBaseToast();

const { listOffers, renameTemplate } = useOffersApi();

const loading = ref(false);
const rows = ref([]);
const dlg = ref(false);
const draftName = ref("");
const renaming = ref(null);
const busyRename = ref(false);

async function load() {
  loading.value = true;
  try {
    const res = await listOffers({
      templates_only: true,
      per_page: 100,
      sort_by: "updated_at",
      sort_dir: "desc",
    });
    rows.value = Array.isArray(res?.data) ? res.data : [];
  } catch {
    rows.value = [];
    toast.add({ severity: "error", summary: "Could not load templates", life: 3200 });
  } finally {
    loading.value = false;
  }
}

function openRename(row) {
  renaming.value = row;
  draftName.value = row.template_name || row.subject || "";
  dlg.value = true;
}

async function saveRename() {
  if (!renaming.value) {
    dlg.value = false;

    return;
  }
  const name = draftName.value.trim();
  if (!name) {
    toast.add({ severity: "warn", summary: "Name required", life: 2200 });

    return;
  }
  busyRename.value = true;
  try {
    await renameTemplate(renaming.value.id, name);
    dlg.value = false;
    renaming.value = null;
    toast.add({ severity: "success", summary: "Template renamed", life: 2200 });
    await load();
  } catch {
    toast.add({ severity: "error", summary: "Rename failed", life: 3400 });
  } finally {
    busyRename.value = false;
  }
}

function edit(row) {
  router.push(`/offers/${row.id}`);
}

onMounted(load);
</script>

<template>
  <BaseIndex title="Offer templates" subtitle="Marked as template library drafts you can reuse for new proposals.">
    <div class="mb-4 flex gap-2">
      <BaseButton
        type="button"
        label="Refresh"
        icon="refresh"
        variant="secondary"
        outlined
        @click="load"
      />
      <BaseButton
        type="button"
        label="New draft template"
        icon="external-link"
        variant="secondary"
        text
        @click="router.push('/offers')"
      />
    </div>

    <BaseDataTable
      :value="rows"
      :loading="loading"
      striped-rows
      responsive-layout="stack"
      breakpoint="960px"
    >
      <BaseColumn field="template_name" header="Template name">
        <template #body="{ data }">
          <span>{{ data.template_name || "—" }}</span>
          <span v-if="data.subject && data.subject !== data.template_name" class="opacity-65 text-xs block">
            Subject: {{ data.subject }}
          </span>
        </template>
      </BaseColumn>
      <BaseColumn field="offer_number" header="#" />
      <BaseColumn field="status" header="Status" />
      <BaseColumn header="">
        <template #body="{ data }">
          <div class="flex flex-wrap gap-1 justify-end">
            <BaseButton
              variant="secondary"
              icon="pencil"
              text
              rounded
              :icon-only="true"
              aria-label="Open"
              title="Edit"
              @click="edit(data)"
            />
            <BaseButton
              variant="secondary"
              icon="tag"
              text
              rounded
              :icon-only="true"
              aria-label="Rename"
              @click="openRename(data)"
            />
          </div>
        </template>
      </BaseColumn>
    </BaseDataTable>

    <BaseModal v-model:visible="dlg" title="Rename template" width="28rem" class="max-w-md">
      <div class="flex flex-col gap-3 text-sm pt-2">
        <BaseInputText
          v-model="draftName"
          label="Library name"
          fluid
          @keyup.enter="saveRename"
        />
        <BaseButton
          type="button"
          variant="primary"
          icon="check"
          label="Save"
          :loading="busyRename"
          @click="saveRename"
        />
      </div>
    </BaseModal>
  </BaseIndex>
</template>
