import frappe, json
from custom_ui.db_utils import process_query_conditions, build_datatable_dict, get_count_or_filters, build_success_response, build_error_response
from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice

# ===============================================================================
# INVOICES API METHODS
# ===============================================================================


@frappe.whitelist()
def create_invoice_for_job(job_name):
    """Create the invoice from a sales order of a job."""
    try:
        project = frappe.get_doc("Project", job_name)
        sales_order = project.sales_order
        invoice = make_sales_invoice(sales_order)
        invoice.save()
        return build_success_response(invoice.as_dict())
    except Exception as e:
        return build_error_response(str(e), 500)


@frappe.whitelist()
def get_invoices_late_count():
    """Return Due, 30-day late, 90-day late, and Lien-worthy late accounts."""
    try:
        dummy_result = [10, 4, 5, 1]
        print("DEBUG: DUMMY RESULT:", dummy_result)
        return build_success_response(dummy_result)
    except Exception as e:
        return build_error_response(str(e), 500)


@frappe.whitelist()
def get_invoice_table_data(filters={}, sortings=[], page=1, page_size=10):
    """Get paginated invoice table data with filtering and sorting support."""
    print("DEBUG: Raw invoice options received:", filters, sortings, page, page_size)

    processed_filters, processed_sortings, is_or, page, page_size = process_query_conditions(filters, sortings, page, page_size)

    if is_or:
        count = frappe.db.sql(*get_count_or_filters("Sales Invoice", processed_filters))[0][0]
    else:
        count = frappe.db.count("Sales Invoice", filters=processed_filters)

    print(f"DEBUG: Number of invoices returned: {count}")

    invoices = frappe.db.get_all(
        "Sales Invoice",
        fields=["*"],
        filters=processed_filters if not is_or else None,
        or_filters=processed_filters if is_or else None,
        limit=page_size,
        start=(page - 1) * page_size,
        order_by=processed_sortings
    )

    tableRows = []
    for invoice in invoices:
        tableRow = {}
        tableRow["id"] = invoice["name"]
        tableRow["address"] = invoice.get("custom_installation_address", "")
        tableRow["customer"] = invoice.get("customer", "")
        tableRow["grand_total"] = f"${invoice.get('grand_total', '')}0"
        tableRow["status"] = invoice.get("status", "")
        tableRow["items"] = invoice.get("items", "")
        tableRows.append(tableRow)

    table_data_dict = build_datatable_dict(data=tableRows, count=count, page=page, page_size=page_size)
    return build_success_response(table_data_dict)


@frappe.whitelist()
def get_invoice(invoice_name):
    """Get detailed information for a specific invoice."""
    try:
        invoice = frappe.get_doc("Sales Invoice", invoice_name)
        return build_success_response(invoice.as_dict())
    except Exception as e:
        return build_error_response(str(e), 500)


@frappe.whitelist()
def get_invoice_items():
    items = frappe.db.get_all("Sales Invoice Item", fields=["*"])
    return build_success_response(items)


@frappe.whitelist()
def get_invoice_from_address(full_address):
    invoice = frappe.db.sql("""
        SELECT i.name, i.custom_installation_address
        FROM `tabSalesInvoice` i
        JOIN `tabAddress` a
          ON i.custom_installation_address = a.name
        WHERE a.full_address =%s
        """, (full_address,), as_dict=True)
    if invoice:
        return build_success_response(invoice)
    else:
        return build_error_response("No invoice found for the given address.", 404)


@frappe.whitelist()
def upsert_invoice(data):
    """Create or update an invoice."""
    print("DOIFJSEOFJISLFK")
    try:
        data = json.loads(data) if isinstance(data, str) else data
        print("DEBUG: Retrieved address name:", data.get("address_name"))
        new_invoice = frappe.get_doc({
            "doctype": "Sales Invoice",
            "custom_installation_address": data.get("address_name"),
            "contact_email": data.get("contact_email"),
            "party_name": data.get("contact_name"),
            "customer_name": data.get("customer_name"),
        })
        for item in data.get("items", []):
            item = json.loads(item) if isinstance(item, str) else item
            new_invoice.append("items", {
                "item_code": item.get("item_code"),
                "qty": item.get("qty"),
            })
        new_invoice.insert()
        print("DEBUG: New invoice created with name:", new_invoice.name)
        return build_success_response(new_invoice.as_dict())
    except Exception as e:
        return build_error_response(str(e), 500)


