import { api, ensureCsrf } from "../../../services/api.js";
import { getFilterScalar } from "../../../composables/useDataTableFilters.js";
import { ref } from "vue";

export function useInvoiceList() {
  const rows = ref([]);
  const totalRecords = ref(0);
  const totalAllRecords = ref(0);
  const loading = ref(false);
  const error = ref("");

  const pagination = ref({ page: 1, limit: 15 });
  const sort = ref([{ field: "invoice_date", order: -1 }]);

  const tableUiState = ref({
    globalSearch: "",
    filters: {},
  });

  let loadTimer = null;
  let fetchSeq = 0;

  function scheduleLoad() {
    if (loadTimer) clearTimeout(loadTimer);
    loadTimer = setTimeout(() => {
      loadTimer = null;
      load();
    }, 400);
  }

  function scalarFromFilters(key) {
    const raw = tableUiState.value?.filters?.[key];
    const v = getFilterScalar(raw);
    if (v == null) return "";
    if (Array.isArray(v)) return v.map(String).join(" ").trim();
    return String(v).trim();
  }

  function sortFieldApi(field) {
    const allowed = new Set([
      "invoice_date",
      "expiration_date",
      "document_number",
      "updated_at",
      "total_inc_vat",
      "status",
    ]);
    return allowed.has(field) ? field : "invoice_date";
  }

  async function load() {
    const seq = ++fetchSeq;
    loading.value = true;
    error.value = "";
    try {
      await ensureCsrf();
      const g = String(tableUiState.value?.globalSearch ?? "").trim();

      const typeRaw = scalarFromFilters("type");
      const statusRaw = scalarFromFilters("status");

      const s0 = sort.value?.[0];
      const sf = sortFieldApi(s0?.field ?? "invoice_date");
      const asc = Number(s0?.order) === 1;

      const { data } = await api.get("/api/invoices", {
        params: {
          page: pagination.value.page,
          per_page: pagination.value.limit,
          search: g || undefined,
          type: typeRaw || undefined,
          status: statusRaw || undefined,
          sort_by: sf,
          sort_dir: asc ? "asc" : "desc",
        },
      });
      if (seq !== fetchSeq) return;

      rows.value = data.data ?? [];
      totalRecords.value = data.meta?.total ?? 0;
      totalAllRecords.value = data.meta?.total ?? 0;
    } catch (e) {
      if (seq !== fetchSeq) return;
      error.value =
        e?.response?.data?.message ?? "Could not load invoices.";
      rows.value = [];
      totalRecords.value = 0;
    } finally {
      if (seq === fetchSeq) loading.value = false;
    }
  }

  function onTableState(state) {
    const nextGs = String(state?.globalSearch ?? "");
    const nextFilters =
      state?.filters && typeof state.filters === "object"
        ? state.filters
        : {};
    tableUiState.value = {
      globalSearch: nextGs,
      filters: nextFilters,
    };
    pagination.value.page = 1;
    scheduleLoad();
  }

  return {
    rows,
    totalRecords,
    totalAllRecords,
    loading,
    error,
    pagination,
    sort,
    load,
    onTableState,
  };
}

export async function fetchInvoiceMeta() {
  await ensureCsrf();
  const { data } = await api.get("/api/invoices/meta");
  return data.data ?? {};
}

export async function fetchInvoice(id) {
  await ensureCsrf();
  const { data } = await api.get(`/api/invoices/${id}`);
  return data.data ?? data;
}

export async function saveInvoiceDraft(payload, id = null) {
  await ensureCsrf();
  if (id) {
    const { data } = await api.patch(`/api/invoices/${id}`, payload);
    return data?.data ?? data;
  }
  const { data } = await api.post("/api/invoices", payload);
  return data?.data ?? data;
}

export async function sendInvoice(id, body = {}) {
  await ensureCsrf();
  const { data } = await api.post(`/api/invoices/${id}/send`, body);
  return data?.data ?? data;
}

export async function bookInvoice(id) {
  await ensureCsrf();
  const { data } = await api.post(`/api/invoices/${id}/book`);
  return data?.data ?? data;
}

export async function sendInvoiceCopy(id, body = {}) {
  await ensureCsrf();
  const { data } = await api.post(`/api/invoices/${id}/send-copy`, body);
  return data?.data ?? data;
}

export async function deleteInvoice(id) {
  await ensureCsrf();
  await api.delete(`/api/invoices/${id}`);
}

export async function fetchInvoicePdfBlob(id) {
  await ensureCsrf();
  const res = await api.get(`/api/invoices/${id}/pdf`, {
    responseType: "blob",
  });
  return res.data;
}
