import pandas as pd


from great_tables import GT, loc, style


COLUMNS = ["Collection", "Loans 2024", "Loans 2025", "Renewals 2024", "Renewals 2025"]


FIELDS = ["collection", "loans_2024", "loans_2025", "renewals_2024", "renewals_2025"]


def load_data():
    return [
        ("Fiction", 240, 265, 88, 97),
        ("Picture books", 190, 204, 41, 39),
        ("Nonfiction", 180, 171, 73, 80),
        ("Chapter books", 90, 112, 22, 30),
    ]


def value_table(data):
    return {"columns": COLUMNS, "rows": [list(row) for row in data]}


def warm_editorial_table(table: GT) -> GT:
    return (
        table.opt_table_font(font=["Inter", "system-ui", "sans-serif"])
        .opt_align_table_header(align="left")
        .tab_options(
            table_background_color="#FFF7ED",
            table_font_color="#1C1917",
            table_font_size="14px",
            table_border_top_style="none",
            table_border_bottom_color="#E7DDD2",
            heading_title_font_size="18px",
            heading_subtitle_font_size="13px",
            heading_border_bottom_style="none",
            column_labels_font_weight="600",
            column_labels_border_top_style="none",
            column_labels_border_bottom_color="#1C1917",
            column_labels_border_bottom_width="1px",
            column_labels_vlines_style="none",
            table_body_hlines_color="#E7DDD2",
            table_body_vlines_style="none",
            table_body_border_bottom_color="#E7DDD2",
            row_group_font_weight="600",
            row_group_border_top_color="#E7DDD2",
            row_group_border_bottom_color="#E7DDD2",
            stub_border_style="none",
            summary_row_border_color="#1C1917",
            grand_summary_row_border_color="#1C1917",
            source_notes_font_size="12px",
        )
        .tab_style(
            style=style.text(font="Georgia, 'Times New Roman', serif", weight="600"),
            locations=loc.title(),
        )
        .tab_style(style=style.text(color="#57534E"), locations=loc.subtitle())
        .tab_style(style=style.text(color="#57534E"), locations=loc.source_notes())
    )


def loan_table(data) -> GT:
    frame = pd.DataFrame(data, columns=FIELDS)
    return warm_editorial_table(
        GT(frame, rowname_col="collection")
        .tab_header(
            title="Library loans and renewals by collection",
            subtitle="Items per month, 2024 and 2025",
        )
        .tab_source_note("Source: illustrative library circulation counts.")
    )


def make_after(data) -> GT:
    return (
        loan_table(data)
        .tab_spanner(label="Loans", columns=["loans_2024", "loans_2025"])
        .tab_spanner(label="Renewals", columns=["renewals_2024", "renewals_2025"])
        .cols_label(
            loans_2024="2024", loans_2025="2025", renewals_2024="2024", renewals_2025="2025"
        )
    )


if __name__ == "__main__":
    print(make_after(load_data()).as_raw_html())
