"""File/test management callbacks.

Handles:
- Open test modal
- Add overlay modal
- Test loading
- Page refresh after loading
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

import dash
from dash import Input, Output, State, html, no_update
from dash.exceptions import PreventUpdate

from impakt.web.state import AppState


def register_file_callbacks(app: dash.Dash, app_state: AppState) -> None:
    """Register file management callbacks."""

    @app.callback(
        Output("open-test-modal", "is_open"),
        [
            Input("open-test-btn", "n_clicks"),
            Input("open-test-cancel", "n_clicks"),
            Input("open-test-confirm", "n_clicks"),
        ],
        [State("open-test-modal", "is_open")],
    )
    def toggle_open_modal(
        open_clicks: int | None,
        cancel_clicks: int | None,
        confirm_clicks: int | None,
        is_open: bool,
    ) -> bool:
        trigger = dash.ctx.triggered_id
        if trigger == "open-test-btn":
            return True
        elif trigger in ("open-test-cancel", "open-test-confirm"):
            return False
        return is_open

    @app.callback(
        Output("overlay-test-modal", "is_open"),
        [
            Input("add-overlay-btn", "n_clicks"),
            Input("overlay-test-cancel", "n_clicks"),
            Input("overlay-test-confirm", "n_clicks"),
        ],
        [State("overlay-test-modal", "is_open")],
    )
    def toggle_overlay_modal(
        open_clicks: int | None,
        cancel_clicks: int | None,
        confirm_clicks: int | None,
        is_open: bool,
    ) -> bool:
        trigger = dash.ctx.triggered_id
        if trigger == "add-overlay-btn":
            return True
        elif trigger in ("overlay-test-cancel", "overlay-test-confirm"):
            return False
        return is_open

    @app.callback(
        [
            Output("open-test-error", "children"),
            Output("page-refresh-trigger", "data"),
        ],
        [Input("open-test-confirm", "n_clicks")],
        [State("open-test-path", "value")],
    )
    def load_test(n_clicks: int | None, path_str: str | None) -> tuple[str, Any]:
        if not n_clicks or not path_str:
            raise PreventUpdate

        path = Path(path_str.strip()).expanduser().resolve()

        if not path.exists():
            return f"Path does not exist: {path}", no_update

        if not path.is_dir():
            return f"Path is not a directory: {path}", no_update

        try:
            # Clear existing tests and load new one
            for tid in list(app_state.test_ids):
                app_state.remove_test(tid)
            app_state.load_test(path)
            return "", {"action": "reload"}
        except Exception as e:
            return f"Failed to load: {e}", no_update

    @app.callback(
        [
            Output("overlay-test-error", "children"),
            Output("page-refresh-trigger", "data", allow_duplicate=True),
        ],
        [Input("overlay-test-confirm", "n_clicks")],
        [State("overlay-test-path", "value")],
        prevent_initial_call=True,
    )
    def load_overlay(n_clicks: int | None, path_str: str | None) -> tuple[str, Any]:
        if not n_clicks or not path_str:
            raise PreventUpdate

        path = Path(path_str.strip()).expanduser().resolve()

        if not path.exists():
            return f"Path does not exist: {path}", no_update

        try:
            app_state.load_test(path)
            return "", {"action": "reload"}
        except Exception as e:
            return f"Failed to load: {e}", no_update
