import { defineStore } from "pinia";
import { ref, computed } from "vue";
import api from "@reports/services/api";

export const useInvoicesStore = defineStore("invoices", () => {
  // State
  const invoices = ref([]);
  const isLoading = ref(false);
  const error = ref(null);
  const accountingPeriod = ref({ an: null, luna: null });
  // Total sold din TOATE facturile filtrate (nu doar pagina curentă)
  const totalSoldAll = ref(0);
  const filters = ref({
    company: null,
    type: "CLIENTI", // CLIENTI or FURNIZORI
    dateFrom: null,
    dateTo: null,
    searchTerm: "",
  });
  const pagination = ref({
    page: 1,
    rows: 50,
    totalRecords: 0,
  });

  // Getters
  const invoiceList = computed(() => invoices.value);
  const hasInvoices = computed(() => invoices.value.length > 0);
  const totalInvoices = computed(() => pagination.value.totalRecords);

  const paidInvoices = computed(() =>
    invoices.value.filter((invoice) => invoice.css_class === "invoice-paid"),
  );

  const overdueInvoices = computed(() =>
    invoices.value.filter((invoice) => invoice.css_class === "invoice-overdue"),
  );

  const totalAmountPaid = computed(() =>
    paidInvoices.value.reduce((sum, invoice) => sum + (invoice.suma || 0), 0),
  );

  const totalAmountOverdue = computed(() =>
    overdueInvoices.value.reduce(
      (sum, invoice) => sum + (invoice.suma || 0),
      0,
    ),
  );

  // Actions
  const loadInvoices = async (companyCode, options = {}) => {
    if (!companyCode) {
      error.value = "Company code is required";
      return { success: false, error: error.value };
    }

    isLoading.value = true;
    error.value = null;

    try {
      const params = {
        partner_type: filters.value.type,
        page: pagination.value.page,
        page_size: pagination.value.rows,
        ...options,
      };

      if (filters.value.dateFrom) {
        // Convert Date object to YYYY-MM-DD string format (LOCAL date, not UTC)
        if (filters.value.dateFrom instanceof Date) {
          const year = filters.value.dateFrom.getFullYear();
          const month = String(filters.value.dateFrom.getMonth() + 1).padStart(
            2,
            "0",
          );
          const day = String(filters.value.dateFrom.getDate()).padStart(2, "0");
          params.date_from = `${year}-${month}-${day}`;
        } else {
          params.date_from = filters.value.dateFrom;
        }
      }
      if (filters.value.dateTo) {
        // Convert Date object to YYYY-MM-DD string format (LOCAL date, not UTC)
        if (filters.value.dateTo instanceof Date) {
          const year = filters.value.dateTo.getFullYear();
          const month = String(filters.value.dateTo.getMonth() + 1).padStart(
            2,
            "0",
          );
          const day = String(filters.value.dateTo.getDate()).padStart(2, "0");
          params.date_to = `${year}-${month}-${day}`;
        } else {
          params.date_to = filters.value.dateTo;
        }
      }
      if (filters.value.searchTerm) {
        params.search = filters.value.searchTerm;
      }

      // Fixed: Use company as query parameter instead of path parameter
      const response = await api.get(`/invoices/`, {
        params: {
          company: companyCode,
          ...params,
        },
      });

      invoices.value = response.data.invoices || [];
      pagination.value.totalRecords = response.data.total_count || 0;

      // Store total sold from ALL filtered invoices (not just current page)
      totalSoldAll.value = response.data.total_sold_all || 0;

      // Store accounting period if available
      if (response.data.accounting_period) {
        accountingPeriod.value = response.data.accounting_period;
      }

      return { success: true };
    } catch (err) {
      error.value = err.response?.data?.detail || "Failed to load invoices";
      console.error("Failed to load invoices:", err);
      return { success: false, error: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  const setFilters = (newFilters) => {
    filters.value = { ...filters.value, ...newFilters };
  };

  const setPagination = (newPagination) => {
    pagination.value = { ...pagination.value, ...newPagination };
  };

  const setInvoiceType = (type) => {
    filters.value.type = type;
  };

  const clearFilters = () => {
    filters.value = {
      company: null,
      type: "CLIENTI",
      dateFrom: null,
      dateTo: null,
      searchTerm: "",
    };
  };

  const clearError = () => {
    error.value = null;
  };

  const reset = () => {
    invoices.value = [];
    isLoading.value = false;
    error.value = null;
    accountingPeriod.value = { an: null, luna: null };
    totalSoldAll.value = 0;
    clearFilters();
    pagination.value = {
      page: 1,
      rows: 50,
      totalRecords: 0,
    };
  };

  const getInvoiceById = (id) => {
    return invoices.value.find((invoice) => invoice.id === id);
  };

  return {
    // State
    invoices,
    isLoading,
    error,
    accountingPeriod,
    totalSoldAll,
    filters,
    pagination,

    // Getters
    invoiceList,
    hasInvoices,
    totalInvoices,
    paidInvoices,
    overdueInvoices,
    totalAmountPaid,
    totalAmountOverdue,

    // Actions
    loadInvoices,
    setFilters,
    setPagination,
    setInvoiceType,
    clearFilters,
    clearError,
    reset,
    getInvoiceById,
  };
});
