from __future__ import annotations

from dataclasses import dataclass

from openpyxl.worksheet.worksheet import Worksheet

from xllayout.core.canvas import Anchor, Box
from xllayout.core.theme import Theme
from xllayout.core.utils import apply_range_style


@dataclass
class DescriptionBlock:
    text: str
    span_cols: int = 12
    height_rows: int = 3

    def measure(self, anchor: Anchor, span_rows: int | None = None, span_cols: int | None = None) -> Box:
        width = span_cols if span_cols is not None else self.span_cols
        height = span_rows if span_rows is not None else self.height_rows
        if width <= 0 or height <= 0:
            raise ValueError("DescriptionBlock width/height must be > 0")

        return Box(anchor.row, anchor.col, anchor.row + height - 1, anchor.col + width - 1)

    def draw(self, ws: Worksheet, box: Box, theme: Theme) -> None:
        ws.merge_cells(start_row=box.r1, start_column=box.c1, end_row=box.r2, end_column=box.c2)
        cell = ws.cell(row=box.r1, column=box.c1, value=self.text)
        cell.font = theme.fonts.body
        cell.alignment = theme.alignments.wrap_left
        cell.fill = theme.fills.muted_bg

        apply_range_style(ws, box, border=theme.borders.thin)
