from __future__ import annotations

from typing import Any

from openpyxl.styles import Font

from app.common.excel_styler import (
    ALIGN_CENTER,
    ALIGN_LEFT,
    ALIGN_RIGHT,
    BORDER_BOX,
    FILL_HEADER,
    FILL_SECTION,
    FILL_TOTAL,
    FMT_CURRENCY_VND,
    FONT_DATA,
    FONT_HEADER,
    FONT_MONO,
    FONT_SECTION,
    FONT_SUBTITLE,
    FONT_TITLE,
    FONT_TOTAL,
)

from .boq_statutory_cost_service import StatutoryCostSummaryEngine


def build_statutory_sheet(ws, takeoff: dict[str, Any], items: list[dict[str, Any]]):
    ws.title = "1. TH Kinh Phí (NĐ 206)"
    ws.views.sheetView[0].showGridLines = True

    # Enterprise header
    ws["A1"] = "CÔNG TY TNHH XÂY DỰNG ĐỊNH SƠN"
    ws["A1"].font = Font(name="Arial", size=11, bold=True, color="0F172A")
    ws["A2"] = (
        "Mã số thuế: 0202111150 | Định mức & Pháp lý: Luật Xây dựng 2025 - Nghị định 206/2026/NĐ-CP"
    )
    ws["A2"].font = Font(name="Arial", size=9, italic=True, color="475569")

    ws.merge_cells("A4:G4")
    ws["A4"] = "BẢNG TỔNG HỢP DỰ TOÁN KINH PHÍ XÂY DỰNG CÔNG TRÌNH"
    ws["A4"].font = FONT_TITLE
    ws["A4"].alignment = ALIGN_CENTER

    drawing_type = takeoff.get("drawing_type") or "civil_building"
    summary_data = StatutoryCostSummaryEngine.calculate_statutory_summary(
        items, drawing_type=drawing_type
    )

    ws.merge_cells("A5:G5")
    ws["A5"] = (
        f"Loại công trình: {summary_data.get('project_type_name')} | Căn cứ: {summary_data.get('legal_basis')}"
    )
    ws["A5"].font = FONT_SUBTITLE
    ws["A5"].alignment = ALIGN_CENTER

    headers = [
        ("A7", "STT"),
        ("B7", "Ký Hiệu"),
        ("C7", "Khoản Mục Chi Phí"),
        ("D7", "Cách Tính Toán / Định Mức"),
        ("E7", "Hệ Số (%)"),
        ("F7", "Giá Trị Dự Toán (VNĐ)"),
        ("G7", "Ghi Chú Pháp Lý"),
    ]
    for cell_ref, text in headers:
        ws[cell_ref] = text
        ws[cell_ref].font = FONT_HEADER
        ws[cell_ref].fill = FILL_HEADER
        ws[cell_ref].alignment = ALIGN_CENTER
        ws[cell_ref].border = BORDER_BOX
    ws.row_dimensions[7].height = 28

    current_row = 8
    for row in summary_data.get("table_rows", []):
        is_hdr = row.get("is_header", False)
        is_grand = row.get("is_grand_total", False)

        fnt = FONT_TOTAL if is_grand else (FONT_SECTION if is_hdr else FONT_DATA)
        fill = FILL_TOTAL if is_grand else (FILL_SECTION if is_hdr else None)

        ws[f"A{current_row}"] = row.get("index")
        ws[f"A{current_row}"].font = fnt
        ws[f"A{current_row}"].alignment = ALIGN_CENTER
        ws[f"A{current_row}"].border = BORDER_BOX

        ws[f"B{current_row}"] = row.get("code")
        ws[f"B{current_row}"].font = FONT_MONO
        ws[f"B{current_row}"].alignment = ALIGN_CENTER
        ws[f"B{current_row}"].border = BORDER_BOX

        ws[f"C{current_row}"] = row.get("title")
        ws[f"C{current_row}"].font = fnt
        ws[f"C{current_row}"].alignment = ALIGN_LEFT
        ws[f"C{current_row}"].border = BORDER_BOX

        ws[f"D{current_row}"] = row.get("calculation_formula")
        ws[f"D{current_row}"].font = FONT_DATA
        ws[f"D{current_row}"].alignment = ALIGN_LEFT
        ws[f"D{current_row}"].border = BORDER_BOX

        ws[f"E{current_row}"] = row.get("coefficient_str")
        ws[f"E{current_row}"].font = FONT_MONO
        ws[f"E{current_row}"].alignment = ALIGN_CENTER
        ws[f"E{current_row}"].border = BORDER_BOX

        ws[f"F{current_row}"] = float(row.get("amount_vnd") or 0.0)
        ws[f"F{current_row}"].font = fnt
        ws[f"F{current_row}"].alignment = ALIGN_RIGHT
        ws[f"F{current_row}"].number_format = FMT_CURRENCY_VND
        ws[f"F{current_row}"].border = BORDER_BOX

        ws[f"G{current_row}"] = row.get("notes")
        ws[f"G{current_row}"].font = FONT_DATA
        ws[f"G{current_row}"].alignment = ALIGN_LEFT
        ws[f"G{current_row}"].border = BORDER_BOX

        if fill:
            for col_letter in ["A", "B", "C", "D", "E", "F", "G"]:
                ws[f"{col_letter}{current_row}"].fill = fill

        ws.row_dimensions[current_row].height = (
            24 if is_grand else (22 if is_hdr else 20)
        )
        current_row += 1

    # Adjust widths
    widths = {"A": 8, "B": 10, "C": 42, "D": 36, "E": 15, "F": 24, "G": 45}
    for col_letter, width in widths.items():
        ws.column_dimensions[col_letter].width = width
