"""Header/navbar component.

Contains the Impakt branding, test info summary, file open button,
and template selector.
"""

from __future__ import annotations

import dash_bootstrap_components as dbc
from dash import dcc, html

from impakt.web.state import AppState


def build_header(app_state: AppState, template_names: list[str] | None = None) -> dbc.Navbar:
    """Build the top navigation bar."""

    # Test info summary
    test_info = ""
    if not app_state.is_empty:
        primary = app_state.primary_test
        if primary:
            meta = primary.data.metadata
            parts = [f"Test: {meta.test_number}"]
            if meta.vehicle.make:
                parts.append(f"{meta.vehicle.make} {meta.vehicle.model}".strip())
            if meta.dummy.dummy_type:
                parts.append(meta.dummy.dummy_type)
            if meta.impact.test_type:
                parts.append(meta.impact.test_type)
            if meta.impact.speed_kmh > 0:
                parts.append(f"{meta.impact.speed_kmh:.1f} km/h")
            test_info = " | ".join(parts)

            if len(app_state.tests) > 1:
                test_info += f"  (+{len(app_state.tests) - 1} overlay)"

    return dbc.Navbar(
        dbc.Container(
            [
                # Brand
                dbc.NavbarBrand(
                    "Impakt", className="ms-2", style={"fontWeight": "bold", "fontSize": "18px"}
                ),
                # Test info
                html.Span(
                    test_info,
                    className="text-light ms-3",
                    style={"fontSize": "12px", "opacity": "0.9"},
                ),
                # Right-side controls
                dbc.Nav(
                    [
                        # Open test button
                        dbc.NavItem(
                            dbc.Button(
                                "Open Test",
                                id="open-test-btn",
                                color="light",
                                size="sm",
                                outline=True,
                                className="me-2",
                            ),
                        ),
                        # Add overlay button
                        dbc.NavItem(
                            dbc.Button(
                                "Add Overlay",
                                id="add-overlay-btn",
                                color="light",
                                size="sm",
                                outline=True,
                                className="me-2",
                                disabled=app_state.is_empty,
                            ),
                        ),
                        # Template selector
                        dbc.NavItem(
                            dbc.Select(
                                id="template-select",
                                options=[{"label": t, "value": t} for t in (template_names or [])],
                                placeholder="Template...",
                                style={"width": "180px", "fontSize": "12px"},
                            ),
                        ),
                    ],
                    className="ms-auto",
                    navbar=True,
                ),
            ],
            fluid=True,
        ),
        color="dark",
        dark=True,
    )


def build_test_info_panel(app_state: AppState) -> dbc.Card:
    """Build a collapsible test info summary card."""
    if app_state.is_empty:
        return dbc.Card(
            dbc.CardBody(
                html.Div(
                    "No test loaded. Click 'Open Test' to begin.",
                    className="text-muted text-center py-3",
                ),
            ),
        )

    rows = []
    for loaded in app_state.tests:
        meta = loaded.data.metadata
        badge_color = "primary" if loaded == app_state.primary_test else "secondary"

        rows.append(
            html.Tr(
                [
                    html.Td(
                        dbc.Badge(meta.test_number, color=badge_color, className="me-1"),
                        style={"fontSize": "12px"},
                    ),
                    html.Td(
                        f"{meta.vehicle.make} {meta.vehicle.model}".strip() or "—",
                        style={"fontSize": "12px"},
                    ),
                    html.Td(meta.dummy.dummy_type or "—", style={"fontSize": "12px"}),
                    html.Td(meta.impact.test_type or "—", style={"fontSize": "12px"}),
                    html.Td(
                        f"{meta.impact.speed_kmh:.1f}" if meta.impact.speed_kmh else "—",
                        style={"fontSize": "12px"},
                    ),
                    html.Td(str(loaded.channel_count), style={"fontSize": "12px"}),
                    html.Td(
                        dbc.Button(
                            "x",
                            id={"type": "remove-test-btn", "index": loaded.test_id},
                            color="danger",
                            size="sm",
                            outline=True,
                            style={"padding": "0 6px", "fontSize": "10px", "lineHeight": "1.4"},
                        )
                        if loaded != app_state.primary_test
                        else "",
                        style={"width": "30px"},
                    ),
                ]
            )
        )

    return dbc.Card(
        dbc.CardBody(
            [
                html.Table(
                    [
                        html.Thead(
                            html.Tr(
                                [
                                    html.Th("Test", style={"fontSize": "11px"}),
                                    html.Th("Vehicle", style={"fontSize": "11px"}),
                                    html.Th("Dummy", style={"fontSize": "11px"}),
                                    html.Th("Type", style={"fontSize": "11px"}),
                                    html.Th("km/h", style={"fontSize": "11px"}),
                                    html.Th("Ch.", style={"fontSize": "11px"}),
                                    html.Th("", style={"fontSize": "11px"}),
                                ]
                            )
                        ),
                        html.Tbody(rows),
                    ],
                    className="table table-sm table-borderless mb-0",
                ),
            ],
            className="py-1",
        ),
        className="mb-2",
        style={"backgroundColor": "#f8f9fa"},
    )


def build_open_test_modal() -> dbc.Modal:
    """Build the modal dialog for opening a test."""
    return dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("Open Test Data")),
            dbc.ModalBody(
                [
                    dbc.Label("Path to test directory:", size="sm"),
                    dbc.Input(
                        id="open-test-path",
                        type="text",
                        placeholder="/path/to/test_data",
                        size="sm",
                        className="mb-2",
                    ),
                    html.Div(id="open-test-error", className="text-danger small"),
                ]
            ),
            dbc.ModalFooter(
                [
                    dbc.Button("Cancel", id="open-test-cancel", color="secondary", size="sm"),
                    dbc.Button("Open", id="open-test-confirm", color="primary", size="sm"),
                ]
            ),
        ],
        id="open-test-modal",
        is_open=False,
        centered=True,
    )


def build_overlay_modal() -> dbc.Modal:
    """Build the modal dialog for adding an overlay test."""
    return dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("Add Overlay Test")),
            dbc.ModalBody(
                [
                    dbc.Label("Path to overlay test directory:", size="sm"),
                    dbc.Input(
                        id="overlay-test-path",
                        type="text",
                        placeholder="/path/to/overlay_test",
                        size="sm",
                        className="mb-2",
                    ),
                    html.Div(id="overlay-test-error", className="text-danger small"),
                ]
            ),
            dbc.ModalFooter(
                [
                    dbc.Button("Cancel", id="overlay-test-cancel", color="secondary", size="sm"),
                    dbc.Button("Add", id="overlay-test-confirm", color="primary", size="sm"),
                ]
            ),
        ],
        id="overlay-test-modal",
        is_open=False,
        centered=True,
    )
