from __future__ import annotations
import html

"""MISA meInvoice XML Generator, HTML Representation, and Excel Exporter.
Fully compliant with Decree 123/2020/ND-CP, Circular 78/2021/TT-BTC & MISA meInvoice standards.
"""

import hashlib
import io
import json
import logging
from datetime import date, datetime
from decimal import ROUND_HALF_UP, Decimal
from typing import Any

from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter

from .common import DSCONS_DEFAULT_COMPANY_NAME, DSCONS_DEFAULT_TAX_CODE, to_decimal

logger = logging.getLogger("dscons.invoice.misa_exporter")


def vietnamese_number_to_words(amount: Decimal | float | str) -> str:
    """Chuyển đổi số tiền thành chữ tiếng Việt chuẩn xác cho hóa đơn GTGT / Kế toán."""
    try:
        val = int(Decimal(str(amount)).quantize(Decimal(1), rounding=ROUND_HALF_UP))
    except Exception:
        return "Không đồng chẵn."

    if val == 0:
        return "Không đồng chẵn."

    is_negative = val < 0
    val = abs(val)

    units = ["", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín"]
    scales = ["", "nghìn", "triệu", "tỷ", "nghìn tỷ", "triệu tỷ"]

    def read_three_digits(n: int, is_highest_group: bool = False) -> str:
        hundred = n // 100
        remainder = n % 100
        ten = remainder // 10
        one = remainder % 10

        res = []

        if hundred > 0 or not is_highest_group:
            res.append(f"{units[hundred]} trăm")

        if ten > 1:
            res.append(f"{units[ten]} mươi")
            if one == 1:
                res.append("mốt")
            elif one == 5:
                res.append("lăm")
            elif one > 0:
                res.append(units[one])
        elif ten == 1:
            res.append("mười")
            if one == 5:
                res.append("lăm")
            elif one > 0:
                res.append(units[one])
        elif ten == 0 and one > 0:
            if hundred > 0 or not is_highest_group:
                res.append(f"linh {units[one]}")
            else:
                res.append(units[one])

        return " ".join(res)

    groups = []
    temp = val
    while temp > 0:
        groups.append(temp % 1000)
        temp //= 1000

    words = []
    for i in range(len(groups) - 1, -1, -1):
        g_val = groups[i]
        if g_val > 0:
            g_str = read_three_digits(g_val, is_highest_group=(i == len(groups) - 1))
            scale = scales[i]
            if scale:
                words.append(f"{g_str} {scale}")
            else:
                words.append(g_str)

    result_text = " ".join(words).strip()
    result_text = " ".join(result_text.split())
    # Viết hoa chữ cái đầu tiên
    result_text = result_text[0].upper() + result_text[1:] + " đồng chẵn."
    if is_negative:
        result_text = "Âm " + result_text[0].lower() + result_text[1:]

    return result_text


class InvoiceMisaExportMixin:
    """Mixin cung cấp khả năng xuất XML, HTML bản thể hiện và Excel chuẩn MISA meInvoice."""

    def generate_misa_xml(
        self, invoice: dict[str, Any], items: list[dict[str, Any]]
    ) -> str:
        """Sinh chuỗi XML chuẩn định dạng MISA meInvoice & Nghị định 123/2020/NĐ-CP."""
        inv_no = str(invoice.get("invoice_number", "00000001")).zfill(8)
        series = invoice.get("invoice_series", "1C26TDS")
        template = invoice.get("template_code", "1")
        issue_date_val = invoice.get("issue_date")
        issue_date_str = str(issue_date_val) if issue_date_val else str(date.today())

        seller_name = invoice.get("seller_name") or DSCONS_DEFAULT_COMPANY_NAME
        seller_tax = invoice.get("seller_tax_code") or DSCONS_DEFAULT_TAX_CODE
        seller_addr = (
            invoice.get("seller_address")
            or "Thôn Tú Đôi 3, xã Kiến Minh, huyện Kiến Thụy, TP Hải Phòng"
        )

        buyer_name = invoice.get("buyer_name") or "Khách hàng mua lẻ"
        buyer_tax = invoice.get("buyer_tax_code") or ""
        buyer_addr = invoice.get("buyer_address") or ""

        subtotal = to_decimal(invoice.get("subtotal_amount_vnd", 0))
        vat_rate = to_decimal(invoice.get("vat_rate_percent", 8))
        vat_amount = to_decimal(invoice.get("vat_amount_vnd", 0))
        total = to_decimal(invoice.get("total_amount_vnd", 0))

        amount_in_words = invoice.get("amount_in_words") or vietnamese_number_to_words(
            total
        )

        items_xml_lines = []
        for idx, itm in enumerate(items, 1):
            i_name = (
                (itm.get("item_name") or "")
                .replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
            )
            i_code = itm.get("item_code") or f"SP-{idx:03d}"
            i_unit = itm.get("unit") or "Lô"
            i_qty = to_decimal(itm.get("quantity", 1.0))
            i_price = to_decimal(itm.get("unit_price_vnd", 0))
            i_amount = to_decimal(itm.get("amount_before_vat_vnd", 0))
            i_vat = to_decimal(itm.get("vat_amount_vnd", 0))
            i_total = to_decimal(itm.get("total_item_amount_vnd", 0))
            if i_total == Decimal(0):
                i_total = i_amount + i_vat

            items_xml_lines.append(f"""    <Item>
      <LineNumber>{idx}</LineNumber>
      <ItemCode>{i_code}</ItemCode>
      <ItemName>{i_name}</ItemName>
      <UnitName>{i_unit}</UnitName>
      <Quantity>{i_qty:.4f}</Quantity>
      <UnitPrice>{i_price:.4f}</UnitPrice>
      <AmountWithoutVAT>{i_amount:.4f}</AmountWithoutVAT>
      <VATRateName>{vat_rate:.0f}%</VATRateName>
      <VATRate>{vat_rate:.2f}</VATRate>
      <ItemVATAmount>{i_vat:.4f}</ItemVATAmount>
      <ItemTotalAmount>{i_total:.4f}</ItemTotalAmount>
    </Item>""")

        items_block = "\n".join(items_xml_lines)

        xml_content = f"""<?xml version="1.0" encoding="utf-8"?>
<Invoice xmlns="http://meinvoice.vn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <InvoiceHeader>
    <TemplateCode>{template}</TemplateCode>
    <InvoiceSeries>{series}</InvoiceSeries>
    <InvoiceNo>{inv_no}</InvoiceNo>
    <InvoiceDate>{issue_date_str}</InvoiceDate>
    <CurrencyCode>VND</CurrencyCode>
    <ExchangeRate>1.0000</ExchangeRate>
    <PaymentMethod>TM/CK</PaymentMethod>
    <SellerTaxCode>{seller_tax}</SellerTaxCode>
    <SellerLegalName>{seller_name}</SellerLegalName>
    <SellerAddress>{seller_addr}</SellerAddress>
    <SellerPhone>0904.388.999</SellerPhone>
    <SellerEmail>contact@dinhsonconstruction.com</SellerEmail>
    <BuyerTaxCode>{buyer_tax}</BuyerTaxCode>
    <BuyerLegalName>{buyer_name}</BuyerLegalName>
    <BuyerAddress>{buyer_addr}</BuyerAddress>
    <TotalAmountWithoutVAT>{subtotal:.4f}</TotalAmountWithoutVAT>
    <VATAmount>{vat_amount:.4f}</VATAmount>
    <TotalAmountWithVAT>{total:.4f}</TotalAmountWithVAT>
    <TotalAmountInWords>{amount_in_words}</TotalAmountInWords>
    <SignDate>{datetime.now().strftime("%Y-%m-%dT%H:%M:%S")}</SignDate>
    <SignerName>{seller_name}</SignerName>
    <SoftwareProvider>MISA meInvoice - Integrated DSCons ERP</SoftwareProvider>
  </InvoiceHeader>
  <InvoiceDetails>
{items_block}
  </InvoiceDetails>
</Invoice>"""
        return xml_content

    def issue_output_invoice(
        self,
        buyer_name: str,
        buyer_tax_code: str | None = None,
        buyer_address: str | None = None,
        buyer_email: str | None = None,
        buyer_phone: str | None = None,
        buyer_representative: str | None = None,
        items: list[dict[str, Any]] | None = None,
        vat_rate_percent: float = 8.0,
        invoice_series: str = "1C26TDS",
        invoice_number: str | None = None,
        issue_date: str | None = None,
        payment_method: str = "TM/CK",
        notes: str | None = None,
        project_id: str | None = None,
        is_draft: bool = False,
        user_name: str = "SuperAdmin",
    ) -> dict[str, Any]:
        """Lập và xuất hóa đơn đầu ra (bán ra) mới chuẩn MISA meInvoice (hỗ trợ cả Ký phát hành hoặc Lưu nháp)."""
        items = items or []
        if not items:
            return {
                "status": "error",
                "message": "Hóa đơn phải có ít nhất 1 dòng hàng hóa / dịch vụ.",
            }

        parsed_items = []
        subtotal_vnd = Decimal("0.0000")
        total_vat_vnd = Decimal("0.0000")
        default_vat_rate = Decimal(str(vat_rate_percent))

        for idx, itm in enumerate(items, 1):
            name = itm.get("item_name") or f"Hàng hóa / Dịch vụ #{idx}"
            code = itm.get("item_code") or f"VT-{idx:03d}"
            unit = itm.get("unit") or "Lô"
            qty = to_decimal(itm.get("quantity", 1.0))
            price = to_decimal(itm.get("unit_price_vnd", 0.0))
            amount = (qty * price).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)

            # Thuế suất dòng
            if "vat_rate_percent" in itm and itm["vat_rate_percent"] is not None:
                line_vat_rate = Decimal(str(itm["vat_rate_percent"]))
            else:
                line_vat_rate = default_vat_rate

            # Chiết khấu dòng
            disc_pct = Decimal(str(itm.get("discount_rate_percent", 0.0)))
            if itm.get("discount_amount_vnd"):
                disc_amt = to_decimal(itm["discount_amount_vnd"])
            else:
                disc_amt = (amount * (disc_pct / Decimal("100.0"))).quantize(
                    Decimal("0.0001"), rounding=ROUND_HALF_UP
                )

            net_line_amt = amount - disc_amt
            line_vat_amt = (net_line_amt * (line_vat_rate / Decimal("100.0"))).quantize(
                Decimal("0.0001"), rounding=ROUND_HALF_UP
            )
            total_amt = net_line_amt + line_vat_amt

            subtotal_vnd += net_line_amt
            total_vat_vnd += line_vat_amt

            parsed_items.append(
                {
                    "item_order": idx,
                    "item_name": name,
                    "item_code": code,
                    "unit": unit,
                    "quantity": qty,
                    "unit_price_vnd": price,
                    "amount_before_vat_vnd": net_line_amt,
                    "vat_rate_percent": line_vat_rate,
                    "vat_amount_vnd": line_vat_amt,
                    "total_item_amount_vnd": total_amt,
                    "discount_rate_percent": disc_pct,
                    "discount_amount_vnd": disc_amt,
                    "cost_category": self.categorize_item_cost(name, code),
                }
            )

        total_amount_vnd = subtotal_vnd + total_vat_vnd
        amount_words = vietnamese_number_to_words(total_amount_vnd)

        with self.get_connection() as conn:
            with conn.cursor() as cur:
                # Tự động sinh số hóa đơn nếu chưa truyền
                if not invoice_number:
                    cur.execute(
                        "SELECT COUNT(*) AS c FROM erp_invoices WHERE direction = 'output'"
                    )
                    next_no = cur.fetchone()["c"] + 1
                    final_inv_no = str(next_no).zfill(8)
                else:
                    final_inv_no = str(invoice_number).zfill(8)

                final_issue_date = issue_date or str(date.today())
                inv_status = "draft" if is_draft else "valid"
                is_signed = not is_draft
                signed_by = DSCONS_DEFAULT_COMPANY_NAME if is_signed else None

                inv_dict = {
                    "invoice_number": final_inv_no,
                    "invoice_series": invoice_series,
                    "template_code": "1",
                    "issue_date": final_issue_date,
                    "seller_name": DSCONS_DEFAULT_COMPANY_NAME,
                    "seller_tax_code": DSCONS_DEFAULT_TAX_CODE,
                    "seller_address": "Thôn Tú Đôi 3, xã Kiến Minh, huyện Kiến Thụy, TP Hải Phòng",
                    "buyer_name": buyer_name,
                    "buyer_tax_code": buyer_tax_code or "",
                    "buyer_address": buyer_address or "",
                    "subtotal_amount_vnd": subtotal_vnd,
                    "vat_rate_percent": default_vat_rate,
                    "vat_amount_vnd": total_vat_vnd,
                    "total_amount_vnd": total_amount_vnd,
                    "amount_in_words": amount_words,
                }

                xml_str = self.generate_misa_xml(inv_dict, parsed_items)
                xml_hash = hashlib.sha256(xml_str.encode("utf-8")).hexdigest()

                note_text = notes or (
                    "Bản nháp hóa đơn điện tử MISA meInvoice"
                    if is_draft
                    else "Lập hóa đơn điện tử chuẩn MISA meInvoice"
                )
                if buyer_email:
                    note_text += f" [Email: {buyer_email}]"

                insert_sql = """
                    INSERT INTO erp_invoices (
                        direction, invoice_type, invoice_number, invoice_series, template_code,
                        issue_date, seller_tax_code, seller_name, seller_address,
                        buyer_tax_code, buyer_name, buyer_address,
                        subtotal_amount_vnd, vat_rate_percent, vat_amount_vnd, total_amount_vnd,
                        amount_in_words, status, signature_valid, signed_by, signed_at,
                        source_channel, reconciliation_status, matched_project_id, notes,
                        xml_raw_content, xml_hash_sha256
                    ) VALUES (
                        'output', 'vat', %s, %s, '1',
                        %s, %s, %s, %s,
                        %s, %s, %s,
                        %s, %s, %s, %s,
                        %s, %s, %s, %s, CASE WHEN %s THEN CURRENT_TIMESTAMP ELSE NULL END,
                        'misa_meinvoice', 'unreconciled', %s, %s,
                        %s, %s
                    ) RETURNING id;
                """
                cur.execute(
                    insert_sql,
                    (
                        final_inv_no,
                        invoice_series,
                        final_issue_date,
                        DSCONS_DEFAULT_TAX_CODE,
                        DSCONS_DEFAULT_COMPANY_NAME,
                        "Thôn Tú Đôi 3, xã Kiến Minh, huyện Kiến Thụy, TP Hải Phòng",
                        buyer_tax_code or "",
                        buyer_name,
                        buyer_address or "",
                        subtotal_vnd,
                        default_vat_rate,
                        total_vat_vnd,
                        total_amount_vnd,
                        amount_words,
                        inv_status,
                        is_signed,
                        signed_by,
                        is_signed,
                        project_id,
                        note_text,
                        xml_str,
                        xml_hash,
                    ),
                )
                new_id = str(cur.fetchone()["id"])

                # Insert line items
                item_sql = """
                    INSERT INTO erp_invoice_items (
                        invoice_id, item_order, item_name, item_code, unit, quantity,
                        unit_price_vnd, amount_before_vat_vnd, vat_rate_percent, vat_amount_vnd,
                        total_item_amount_vnd, cost_category
                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
                """
                for itm in parsed_items:
                    cur.execute(
                        item_sql,
                        (
                            new_id,
                            itm["item_order"],
                            itm["item_name"],
                            itm["item_code"],
                            itm["unit"],
                            itm["quantity"],
                            itm["unit_price_vnd"],
                            itm["amount_before_vat_vnd"],
                            itm["vat_rate_percent"],
                            itm["vat_amount_vnd"],
                            itm["total_item_amount_vnd"],
                            itm["cost_category"],
                        ),
                    )

                # Audit Log
                action_name = (
                    "CREATE_MISA_DRAFT_INVOICE"
                    if is_draft
                    else "ISSUE_MISA_OUTPUT_INVOICE"
                )
                cur.execute(
                    """
                    INSERT INTO erp_invoice_audit_logs (invoice_id, action_type, performed_by, details_json)
                    VALUES (%s, %s, %s, %s);
                """,
                    (
                        new_id,
                        action_name,
                        user_name,
                        json.dumps(
                            {
                                "source": "misa_meinvoice",
                                "status": inv_status,
                                "total": float(total_amount_vnd),
                            },
                            ensure_ascii=False,
                        ),
                    ),
                )

                conn.commit()

                status_label = (
                    "Lưu nháp thành công" if is_draft else "Lập và phát hành thành công"
                )
                return {
                    "status": "success",
                    "message": f"Đã {status_label} Hóa đơn MISA meInvoice số {final_inv_no} (Ký hiệu {invoice_series}).",
                    "invoice_id": new_id,
                    "invoice_number": final_inv_no,
                    "invoice_series": invoice_series,
                    "is_draft": is_draft,
                    "total_amount_vnd": float(total_amount_vnd),
                    "amount_in_words": amount_words,
                }

    def sign_and_issue_invoice(
        self, invoice_id: str, user_name: str = "SuperAdmin"
    ) -> dict[str, Any]:
        """Ký số điện tử và chính thức phát hành hóa đơn nháp (Draft -> Valid)."""
        with self.get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute("SELECT * FROM erp_invoices WHERE id = %s", (invoice_id,))
                inv = cur.fetchone()
                if not inv:
                    return {
                        "status": "error",
                        "message": "Không tìm thấy hóa đơn cần ký số.",
                    }

                cur.execute(
                    """
                    UPDATE erp_invoices
                    SET status = 'valid',
                        signature_valid = TRUE,
                        signed_by = %s,
                        signed_at = CURRENT_TIMESTAMP,
                        updated_at = CURRENT_TIMESTAMP
                    WHERE id = %s;
                """,
                    (DSCONS_DEFAULT_COMPANY_NAME, invoice_id),
                )

                cur.execute(
                    """
                    INSERT INTO erp_invoice_audit_logs (invoice_id, action_type, performed_by, details_json)
                    VALUES (%s, 'SIGN_AND_ISSUE_MISA_INVOICE', %s, %s);
                """,
                    (
                        invoice_id,
                        user_name,
                        json.dumps(
                            {"signed_by": DSCONS_DEFAULT_COMPANY_NAME},
                            ensure_ascii=False,
                        ),
                    ),
                )

                conn.commit()

                return {
                    "status": "success",
                    "message": f"Đã ký số điện tử và phát hành thành công Hóa đơn số {inv['invoice_number']}.",
                    "invoice_id": invoice_id,
                }

    async def send_invoice_to_buyer_email(
        self, invoice_id: str, buyer_email: str
    ) -> dict[str, Any]:
        """Gửi email thông báo phát hành hóa đơn điện tử cho khách hàng."""
        from app.modules.core.application.alert_service import BrevoEmailService

        inv = self.get_invoice_detail(invoice_id)
        if not inv:
            return {"status": "error", "message": "Không tìm thấy hóa đơn."}

        inv_num = inv.get("invoice_number", "00000000")
        series = inv.get("invoice_series", "1C26TDS")
        total_vnd = float(inv.get("total_amount_vnd", 0))
        seller = inv.get("seller_name", DSCONS_DEFAULT_COMPANY_NAME)
        buyer = inv.get("buyer_name", "Quý Khách Hàng")

        html_body = f"""
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background-color: #0b0f19; color: #f8fafc; padding: 24px; border-radius: 8px; max-width: 650px; margin: 0 auto; border: 1px solid #1e293b;">
            <div style="border-bottom: 1px solid #334155; padding-bottom: 14px; margin-bottom: 16px;">
                <h2 style="color: #06b6d4; margin: 0; font-size: 18px;">📄 Thông Báo Phát Hành Hóa Đơn Điện Tử</h2>
            </div>
            <p style="color: #cbd5e1; font-size: 14px;">Kính gửi: <strong>{buyer}</strong>,</p>
            <p style="color: #cbd5e1; font-size: 13px; line-height: 1.5;">
                <strong>{seller}</strong> xin trân trọng thông báo đã phát hành Hóa đơn điện tử Giá Trị Gia Tăng với các thông tin chi tiết như sau:
            </p>
            <div style="background: #1e293b; padding: 14px; border-radius: 6px; margin: 16px 0; font-size: 13px;">
                <div style="margin-bottom: 6px;">Mẫu số: <strong>{html.escape(str(inv.get("template_code", "1")) or '')}</strong> · Ký hiệu: <strong>{series}</strong></div>
                <div style="margin-bottom: 6px;">Số hóa đơn: <strong style="color: #34d399; font-size: 15px;">{inv_num}</strong></div>
                <div style="margin-bottom: 6px;">Ngày lập: <strong>{html.escape(str(inv.get("issue_date")) or '')}</strong></div>
                <div style="margin-bottom: 6px;">Tổng thanh toán: <strong style="color: #38bdf8; font-size: 15px;">{total_vnd:,.0f} VNĐ</strong></div>
                <div style="font-style: italic; color: #94a3b8;">(Bằng chữ: {html.escape(str(inv.get("amount_in_words", "")) or '')})</div>
            </div>
            <p style="color: #94a3b8; font-size: 12px;">
                Quý khách có thể xem và tải bản thể hiện hóa đơn điện tử chính thức bất kỳ lúc nào qua hệ thống cổng tra cứu của chúng tôi.
            </p>
            <hr style="border: none; border-top: 1px solid #334155; margin: 20px 0 12px 0;" />
            <p style="font-size: 11px; color: #64748b; margin: 0; text-align: center;">
                {seller} · MST: 0202111150 · Hotline: 0904.388.999 · Email: contact@dinhsonconstruction.com
            </p>
        </div>
        """

        subject = f"📄 [{seller}] Thông báo phát hành Hóa đơn điện tử số {inv_num} (Ký hiệu {series})"
        res = await BrevoEmailService.send_email(
            recipient_email=buyer_email,
            subject=subject,
            html_content=html_body,
            recipient_name=buyer,
            sender_name=f"{seller} E-Invoice",
        )

        return {
            "status": "success" if res.get("success") else "email_error",
            "message": "Đã gửi email hóa đơn thành công."
            if res.get("success")
            else f"Lỗi gửi email: {res.get('error')}",
            "buyer_email": buyer_email,
        }

    def render_misa_invoice_html(self, invoice_id: str) -> str:
        """Render bản thể hiện HTML khổ A4 chuẩn MISA meInvoice & Nghị định 123/2020/NĐ-CP."""
        inv = self.get_invoice_detail(invoice_id)
        if not inv:
            return "<html><body><h3>Không tìm thấy hóa đơn điện tử.</h3></body></html>"

        items = inv.get("items", [])
        total_vnd = float(inv.get("total_amount_vnd", 0))
        subtotal_vnd = float(inv.get("subtotal_amount_vnd", 0))
        vat_vnd = float(inv.get("vat_amount_vnd", 0))
        amount_words = inv.get("amount_in_words") or vietnamese_number_to_words(
            total_vnd
        )

        item_rows = ""
        for itm in items:
            qty_str = f"{float(itm.get('quantity', 0)):,.2f}"
            price_str = f"{float(itm.get('unit_price_vnd', 0)):,.0f}"
            amt_str = f"{float(itm.get('amount_before_vat_vnd', 0)):,.0f}"
            item_rows += f"""
            <tr>
                <td style="text-align: center; padding: 6px; border: 1px solid #94a3b8;">{itm.get("item_order")}</td>
                <td style="padding: 6px 8px; border: 1px solid #94a3b8; font-weight: 500;">{html.escape(itm.get("item_name") or "")}</td>
                <td style="text-align: center; padding: 6px; border: 1px solid #94a3b8;">{html.escape(itm.get("unit", "") or "")}</td>
                <td style="text-align: right; padding: 6px; border: 1px solid #94a3b8;">{qty_str}</td>
                <td style="text-align: right; padding: 6px; border: 1px solid #94a3b8;">{price_str}</td>
                <td style="text-align: right; padding: 6px; border: 1px solid #94a3b8; font-weight: 600;">{amt_str}</td>
            </tr>
            """

        signed_at_str = inv.get("signed_at") or datetime.now().strftime(
            "%d/%m/%Y %H:%M:%S"
        )

        html_template = f"""<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Hóa Đơn Điện Tử - {html.escape(inv.get("invoice_series") or "")}_{html.escape(inv.get("invoice_number") or "")}</title>
    <style>
        @page {{ size: A4; margin: 15mm; }}
        body {{
            font-family: 'Times New Roman', Times, serif;
            color: #1e293b;
            background: #fff;
            margin: 0;
            padding: 20px;
            font-size: 14px;
            line-height: 1.4;
        }}
        .invoice-box {{
            max-width: 800px;
            margin: auto;
            border: 2px solid #0284c7;
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }}
        .header-table, .info-table, .items-table, .footer-table {{
            width: 100%;
            border-collapse: collapse;
        }}
        .title-section {{
            text-align: center;
        }}
        .title-main {{
            font-size: 20px;
            font-weight: bold;
            color: #0369a1;
            text-transform: uppercase;
            margin: 4px 0;
        }}
        .items-table th {{
            background-color: #f0f9ff;
            border: 1px solid #94a3b8;
            padding: 8px 4px;
            text-align: center;
            font-size: 13px;
        }}
        .stamp-box {{
            border: 2px dashed #ef4444;
            padding: 10px;
            border-radius: 6px;
            color: #ef4444;
            background: #fef2f2;
            text-align: center;
            display: inline-block;
            font-size: 12px;
            margin-top: 10px;
        }}
        @media print {{
            body {{ padding: 0; background: none; }}
            .invoice-box {{ border: 1.5px solid #0284c7; box-shadow: none; }}
            .no-print {{ display: none; }}
        }}
    </style>
</head>
<body>
    <div class="no-print" style="max-width: 800px; margin: 0 auto 16px auto; display: flex; justify-content: space-between; align-items: center;">
        <button onclick="window.print()" style="background: #0284c7; color: #fff; border: none; padding: 8px 20px; border-radius: 6px; font-weight: bold; cursor: pointer;">
            🖨️ In Hóa Đơn / Lưu PDF (A4)
        </button>
        <div style="color: #64748b; font-size: 13px;">Bản thể hiện chuẩn MISA meInvoice · Nghị định 123/2020/NĐ-CP</div>
    </div>

    <div class="invoice-box">
        <table class="header-table" style="margin-bottom: 12px;">
            <tr>
                <td style="width: 20%; vertical-align: top;">
                    <div style="font-weight: bold; font-size: 24px; color: #0284c7; letter-spacing: 1px;">DSCONS</div>
                    <div style="font-size: 11px; color: #64748b;">XÂY DỰNG ĐỊNH SƠN</div>
                </td>
                <td style="width: 50%; vertical-align: top; text-align: center;">
                    <div class="title-main">HÓA ĐƠN GIÁ TRỊ GIA TĂNG</div>
                    <div style="font-size: 12px; color: #64748b; font-style: italic;">(Bản thể hiện của hóa đơn điện tử)</div>
                    <div style="margin-top: 4px; font-size: 13px;">Ngày {str(inv.get("issue_date"))[8:10]} tháng {str(inv.get("issue_date"))[5:7]} năm {str(inv.get("issue_date"))[:4]}</div>
                </td>
                <td style="width: 30%; vertical-align: top; text-align: right; font-size: 13px;">
                    <div>Mẫu số: <strong>{html.escape(str(inv.get("template_code", "1")) or '')}</strong></div>
                    <div>Ký hiệu: <strong>{html.escape(inv.get("invoice_series") or "")}</strong></div>
                    <div>Số HĐ: <strong style="color: #ef4444; font-size: 16px;">{html.escape(inv.get("invoice_number") or "")}</strong></div>
                </td>
            </tr>
        </table>

        <hr style="border: none; border-top: 1px solid #0284c7; margin: 10px 0;" />

        <!-- Seller & Buyer -->
        <table class="info-table" style="margin-bottom: 14px; font-size: 13px;">
            <tr>
                <td style="width: 140px; font-weight: bold; color: #0369a1;">Đơn vị bán hàng:</td>
                <td style="font-weight: bold; font-size: 14px; color: #0f172a;">{html.escape(str(inv.get("seller_name")) or '')}</td>
            </tr>
            <tr>
                <td style="font-weight: bold; color: #0369a1;">Mã số thuế:</td>
                <td style="font-weight: bold; font-size: 14px; color: #0284c7;">{html.escape(str(inv.get("seller_tax_code")) or '')}</td>
            </tr>
            <tr>
                <td style="font-weight: bold; color: #0369a1;">Địa chỉ:</td>
                <td>{html.escape(str(inv.get("seller_address")) or '')}</td>
            </tr>
            <tr>
                <td colspan="2"><hr style="border: none; border-top: 1px dashed #cbd5e1; margin: 8px 0;" /></td>
            </tr>
            <tr>
                <td style="font-weight: bold; color: #059669;">Tên đơn vị mua:</td>
                <td style="font-weight: bold; font-size: 14px;">{html.escape(str(inv.get("buyer_name")) or '')}</td>
            </tr>
            <tr>
                <td style="font-weight: bold; color: #059669;">Mã số thuế:</td>
                <td style="font-weight: bold;">{inv.get("buyer_tax_code") or "Chưa cung cấp"}</td>
            </tr>
            <tr>
                <td style="font-weight: bold; color: #059669;">Địa chỉ:</td>
                <td>{inv.get("buyer_address") or "Theo hợp đồng thi công"}</td>
            </tr>
            <tr>
                <td style="font-weight: bold; color: #059669;">Hình thức thanh toán:</td>
                <td>Chuyển khoản / Tiền mặt (TM/CK)</td>
            </tr>
        </table>

        <!-- Line Items -->
        <table class="items-table" style="margin-bottom: 14px;">
            <thead>
                <tr>
                    <th style="width: 40px;">STT</th>
                    <th>Tên Hàng Hóa, Dịch Vụ, Khối Lượng Thi Công</th>
                    <th style="width: 50px;">ĐVT</th>
                    <th style="width: 70px;">Số Lượng</th>
                    <th style="width: 100px;">Đơn Giá</th>
                    <th style="width: 120px;">Thành Tiền (VNĐ)</th>
                </tr>
            </thead>
            <tbody>
                {item_rows}
            </tbody>
        </table>

        <!-- Summary -->
        <table class="info-table" style="margin-bottom: 16px; font-size: 13px;">
            <tr>
                <td style="text-align: right; padding-right: 12px; font-weight: bold;">Cộng tiền hàng:</td>
                <td style="width: 140px; text-align: right; font-weight: bold;">{subtotal_vnd:,.0f} đ</td>
            </tr>
            <tr>
                <td style="text-align: right; padding-right: 12px; font-weight: bold;">Thuế suất GTGT ({html.escape(str(inv.get("vat_rate_percent", 8)))}%):</td>
                <td style="text-align: right; font-weight: bold;">{vat_vnd:,.0f} đ</td>
            </tr>
            <tr>
                <td style="text-align: right; padding-right: 12px; font-weight: bold; font-size: 15px; color: #0369a1;">Tổng cộng tiền thanh toán:</td>
                <td style="text-align: right; font-weight: bold; font-size: 16px; color: #ef4444;">{total_vnd:,.0f} đ</td>
            </tr>
            <tr>
                <td colspan="2" style="font-style: italic; padding-top: 6px; font-size: 13px;">
                    Số tiền viết bằng chữ: <strong>{amount_words}</strong>
                </td>
            </tr>
        </table>

        <!-- Signatures -->
        <table class="footer-table" style="margin-top: 20px;">
            <tr>
                <td style="width: 50%; text-align: center; vertical-align: top;">
                    <div style="font-weight: bold; text-transform: uppercase;">Người Mua Hàng</div>
                    <div style="font-size: 11px; color: #64748b; font-style: italic;">(Ký, ghi rõ họ tên)</div>
                </td>
                <td style="width: 50%; text-align: center; vertical-align: top;">
                    <div style="font-weight: bold; text-transform: uppercase;">Người Bán Hàng</div>
                    <div style="font-size: 11px; color: #64748b; font-style: italic;">(Chữ ký số điện tử hợp lệ)</div>
                    <div class="stamp-box">
                        <div style="font-weight: bold;">✓ ĐÃ KÝ ĐIỆN TỬ BỞI:</div>
                        <div style="font-weight: bold; font-size: 13px; margin: 2px 0;">{html.escape(str(inv.get("seller_name")) or '')}</div>
                        <div>Ngày ký: {signed_at_str}</div>
                    </div>
                </td>
            </tr>
        </table>

        <div style="border-top: 1px solid #cbd5e1; margin-top: 24px; padding-top: 8px; text-align: center; font-size: 11px; color: #64748b;">
            Hóa đơn điện tử tra cứu tại Cổng Tổng Cục Thuế: <i>https://hoadondientu.gdt.gov.vn</i> · Mã tra cứu: <strong>{html.escape(str(inv.get("xml_hash_sha256", ""))[:16])}</strong>
        </div>
    </div>
</body>
</html>"""
        return html_template

    def export_misa_excel(
        self,
        from_date: str | None = None,
        to_date: str | None = None,
        direction: str = "all",
    ) -> bytes:
        """Xuất bảng kê danh sách hóa đơn theo chuẩn mẫu Excel nhập liệu MISA SME / meInvoice."""
        invoices, _ = self.list_invoices(
            direction=None if direction == "all" else direction,
            from_date=from_date,
            to_date=to_date,
            limit=5000,
            offset=0,
        )

        wb = Workbook()
        ws = wb.active
        ws.title = "Bang_Ke_Hoa_Don_MISA"

        # Fonts & Styles
        title_font = Font(name="Arial", size=14, bold=True, color="003366")
        sub_font = Font(name="Arial", size=10, italic=True, color="555555")
        header_font = Font(name="Arial", size=10, bold=True, color="FFFFFF")
        header_fill = PatternFill(
            start_color="1E40AF", end_color="1E40AF", fill_type="solid"
        )
        data_font = Font(name="Arial", size=10)
        bold_data_font = Font(name="Arial", size=10, bold=True)
        thin_border = Border(
            left=Side(style="thin", color="CCCCCC"),
            right=Side(style="thin", color="CCCCCC"),
            top=Side(style="thin", color="CCCCCC"),
            bottom=Side(style="thin", color="CCCCCC"),
        )

        # Header Title
        dir_label = (
            "MUA VÀO & BÁN RA"
            if direction == "all"
            else ("MUA VÀO" if direction == "input" else "BÁN RA")
        )
        ws.merge_cells("A1:M1")
        ws["A1"] = f"BẢNG KÊ HÓA ĐƠN ĐIỆN TỬ {dir_label} (CHUẨN MISA MEINVOICE)"
        ws["A1"].font = title_font
        ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
        ws.row_dimensions[1].height = 28

        period_str = (
            f"Từ ngày {from_date} đến ngày {to_date}"
            if from_date and to_date
            else "Toàn bộ kỳ kế toán"
        )
        ws.merge_cells("A2:M2")
        ws["A2"] = (
            f"Đơn vị: CÔNG TY TNHH XÂY DỰNG ĐỊNH SƠN (MST: 0202111150) · {period_str}"
        )
        ws["A2"].font = sub_font
        ws["A2"].alignment = Alignment(horizontal="center", vertical="center")
        ws.row_dimensions[2].height = 18

        headers = [
            "STT",
            "Loại HĐ",
            "Ngày HĐ",
            "Mẫu Số",
            "Ký Hiệu",
            "Số Hóa Đơn",
            "MST Người Bán",
            "Tên Người Bán",
            "MST Người Mua",
            "Tên Người Mua",
            "Tiền Hàng (VNĐ)",
            "Tiền Thuế GTGT (VNĐ)",
            "Tổng Thanh Toán (VNĐ)",
        ]

        ws.append([])  # Row 3 empty
        ws.append(headers)  # Row 4
        ws.row_dimensions[4].height = 24

        for col_num in range(1, len(headers) + 1):
            cell = ws.cell(row=4, column=col_num)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = Alignment(
                horizontal="center", vertical="center", wrap_text=True
            )
            cell.border = thin_border

        # Populate Data
        total_subtotal = 0
        total_vat = 0
        total_all = 0

        for idx, inv in enumerate(invoices, 1):
            dir_str = "Bán ra" if inv.get("direction") == "output" else "Mua vào"
            subtotal = float(inv.get("subtotal_amount_vnd", 0))
            vat = float(inv.get("vat_amount_vnd", 0))
            tot = float(inv.get("total_amount_vnd", 0))

            total_subtotal += subtotal
            total_vat += vat
            total_all += tot

            row_data = [
                idx,
                dir_str,
                str(inv.get("issue_date", "")),
                inv.get("template_code", "1"),
                inv.get("invoice_series", ""),
                inv.get("invoice_number", ""),
                inv.get("seller_tax_code", ""),
                inv.get("seller_name", ""),
                inv.get("buyer_tax_code", ""),
                inv.get("buyer_name", ""),
                subtotal,
                vat,
                tot,
            ]
            ws.append(row_data)
            row_idx = ws.max_row
            ws.row_dimensions[row_idx].height = 20

            for col_idx in range(1, len(row_data) + 1):
                c = ws.cell(row=row_idx, column=col_idx)
                c.font = data_font
                c.border = thin_border
                if col_idx in (1, 2, 3, 4, 5, 6, 7, 9):
                    c.alignment = Alignment(horizontal="center", vertical="center")
                elif col_idx in (11, 12, 13):
                    c.alignment = Alignment(horizontal="right", vertical="center")
                    c.number_format = "#,##0"
                else:
                    c.alignment = Alignment(horizontal="left", vertical="center")

        # Total Summary Row
        summary_row_idx = ws.max_row + 1
        ws.merge_cells(
            start_row=summary_row_idx,
            start_column=1,
            end_row=summary_row_idx,
            end_column=10,
        )
        sum_cell = ws.cell(
            row=summary_row_idx, column=1, value="TỔNG CỘNG TIỀN HÓA ĐƠN:"
        )
        sum_cell.font = bold_data_font
        sum_cell.alignment = Alignment(horizontal="right", vertical="center")

        ws.cell(
            row=summary_row_idx, column=11, value=total_subtotal
        ).number_format = "#,##0"
        ws.cell(row=summary_row_idx, column=11).font = bold_data_font
        ws.cell(row=summary_row_idx, column=12, value=total_vat).number_format = "#,##0"
        ws.cell(row=summary_row_idx, column=12).font = bold_data_font
        ws.cell(row=summary_row_idx, column=13, value=total_all).number_format = "#,##0"
        ws.cell(row=summary_row_idx, column=13).font = bold_data_font

        for col_idx in range(1, 14):
            ws.cell(row=summary_row_idx, column=col_idx).border = thin_border

        # Adjust Column Widths
        col_widths = [6, 10, 12, 8, 12, 14, 15, 30, 15, 30, 18, 18, 20]
        for i, width in enumerate(col_widths, 1):
            ws.column_dimensions[get_column_letter(i)].width = width

        output_stream = io.BytesIO()
        wb.save(output_stream)
        return output_stream.getvalue()
