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 TitleBlock:
    title: str
    subtitle: str | None = None
    span_cols: int = 12

    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
        if width <= 0:
            raise ValueError("TitleBlock span_cols must be > 0")

        rows = span_rows if span_rows is not None else (2 if self.subtitle else 1)
        if rows <= 0:
            raise ValueError("TitleBlock span_rows must be > 0")

        return Box(anchor.row, anchor.col, anchor.row + rows - 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.r1, end_column=box.c2)
        title_cell = ws.cell(row=box.r1, column=box.c1, value=self.title)
        title_cell.font = theme.fonts.title
        title_cell.fill = theme.fills.title_bg
        title_cell.alignment = theme.alignments.left

        if box.height >= 2:
            ws.merge_cells(start_row=box.r1 + 1, start_column=box.c1, end_row=box.r1 + 1, end_column=box.c2)
            subtitle_cell = ws.cell(row=box.r1 + 1, column=box.c1, value=self.subtitle)
            subtitle_cell.font = theme.fonts.small
            subtitle_cell.alignment = theme.alignments.left

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