# app/modules/core/routes/pages/admin.py
"""
Core Admin Page Routes (HTML rendering).

Admin pages for core platform functionality:
- Login, logout, authentication
- Dashboard
- Settings
- Feature management
"""

from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session

from app.api.deps import get_current_admin_optional, get_db, require_menu_access
from app.modules.core.utils.page_context import get_admin_context
from app.modules.enums import FrontendType
from app.modules.tenancy.models import User
from app.templates_config import templates
from app.utils.i18n import get_jinja2_globals

router = APIRouter()


# ============================================================================
# PUBLIC ROUTES (No Authentication Required)
# ============================================================================


@router.get("/", response_class=RedirectResponse, include_in_schema=False)
async def admin_root(
    current_user: User | None = Depends(get_current_admin_optional),
):
    """
    Redirect /admin/ based on authentication status.

    - Authenticated admin users -> /admin/dashboard
    - Unauthenticated users -> /admin/login
    """
    if current_user:
        return RedirectResponse(url="/admin/dashboard", status_code=302)

    return RedirectResponse(url="/admin/login", status_code=302)


@router.get("/login", response_class=HTMLResponse, include_in_schema=False)
async def admin_login_page(
    request: Request,
    current_user: User | None = Depends(get_current_admin_optional),
):
    """
    Render admin login page.

    If user is already authenticated as admin, redirect to dashboard.
    Otherwise, show login form.
    """
    if current_user:
        return RedirectResponse(url="/admin/dashboard", status_code=302)

    language = getattr(request.state, "language", "en")
    context = {
        "request": request,
        "current_language": language,
        "frontend_type": "admin",
        **get_jinja2_globals(language),
    }
    return templates.TemplateResponse("tenancy/admin/login.html", context)


@router.get("/select-platform", response_class=HTMLResponse, include_in_schema=False)
async def admin_select_platform_page(
    request: Request,
    current_user: User | None = Depends(get_current_admin_optional),
):
    """
    Render platform selection page for admins.

    Platform admins with access to multiple platforms must select
    which platform they want to manage before accessing the dashboard.
    Super admins can optionally select a platform to scope their view.
    """
    if not current_user:
        return RedirectResponse(url="/admin/login", status_code=302)

    return templates.TemplateResponse(
        "tenancy/admin/select-platform.html",
        {"request": request, "user": current_user},
    )


# ============================================================================
# AUTHENTICATED ROUTES (Admin Only)
# ============================================================================


@router.get("/dashboard", response_class=HTMLResponse, include_in_schema=False)
async def admin_dashboard_page(
    request: Request,
    current_user: User = Depends(require_menu_access("dashboard", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render admin dashboard page.
    Shows platform statistics and recent activity.
    """
    return templates.TemplateResponse(
        "core/admin/dashboard.html",
        get_admin_context(request, db, current_user),
    )


@router.get("/settings", response_class=HTMLResponse, include_in_schema=False)
async def admin_settings_page(
    request: Request,
    current_user: User = Depends(require_menu_access("settings", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render admin settings page.
    Platform configuration and preferences.
    """
    return templates.TemplateResponse(
        "core/admin/settings.html",
        get_admin_context(request, db, current_user),
    )


@router.get("/features", response_class=HTMLResponse, include_in_schema=False)
async def admin_features_page(
    request: Request,
    current_user: User = Depends(
        require_menu_access("subscription-tiers", FrontendType.ADMIN)
    ),
    db: Session = Depends(get_db),
):
    """
    Render feature management page.
    Shows all features with tier assignments and allows editing.
    """
    return templates.TemplateResponse(
        "billing/admin/features.html",
        get_admin_context(request, db, current_user),
    )
