<script setup>
import BaseIndex from "../../../components/base/BaseIndex.vue";
import Button from "primevue/button";
import Column from "primevue/column";
import DataTable from "primevue/datatable";
import Dialog from "primevue/dialog";
import InputText from "primevue/inputtext";

import { useToast } from "primevue/usetoast";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";

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

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

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">
      <Button type="button" label="Refresh" icon="pi pi-refresh" outlined @click="load" />
      <Button
        type="button"
        label="New draft template"
        icon="pi pi-external-link"
        text
        @click="router.push('/offers')"
      />
    </div>

    <DataTable :value="rows" :loading="loading" striped-rows responsive-layout="stack" breakpoint="960px">
      <Column 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>
      </Column>
      <Column field="offer_number" header="#" />
      <Column field="status" header="Status" />
      <Column header="">
        <template #body="{ data }">
          <div class="flex flex-wrap gap-1 justify-end">
            <Button icon="pi pi-pencil" text rounded aria-label="Open" title="Edit" @click="edit(data)" />
            <Button
              icon="pi pi-tag"
              text
              rounded
              severity="secondary"
              aria-label="Rename"
              @click="openRename(data)"
            />
          </div>
        </template>
      </Column>
    </DataTable>

    <Dialog v-model:visible="dlg" header="Rename template" modal class="max-w-md">
      <div class="flex flex-col gap-3 text-sm pt-2">
        <label class="flex flex-col gap-1">
          <span>Library name</span>
          <InputText v-model="draftName" @keyup.enter="saveRename" />
        </label>
        <Button type="button" severity="primary" icon="pi pi-check" label="Save" :loading="busyRename" @click="saveRename" />
      </div>
    </Dialog>
  </BaseIndex>
</template>
