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

Admin pages for multi-tenant management:
- Companies
- Vendors
- Vendor domains
- Vendor themes
- Admin users
- Platforms
"""

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

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

router = APIRouter()


# ============================================================================
# COMPANY MANAGEMENT ROUTES
# ============================================================================


@router.get("/companies", response_class=HTMLResponse, include_in_schema=False)
async def admin_companies_list_page(
    request: Request,
    current_user: User = Depends(require_menu_access("companies", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render companies management page.
    Shows list of all companies with stats.
    """
    return templates.TemplateResponse(
        "tenancy/admin/companies.html",
        get_admin_context(request, db, current_user),
    )


@router.get("/companies/create", response_class=HTMLResponse, include_in_schema=False)
async def admin_company_create_page(
    request: Request,
    current_user: User = Depends(require_menu_access("companies", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render company creation form.
    """
    return templates.TemplateResponse(
        "tenancy/admin/company-create.html",
        get_admin_context(request, db, current_user),
    )


@router.get(
    "/companies/{company_id}", response_class=HTMLResponse, include_in_schema=False
)
async def admin_company_detail_page(
    request: Request,
    company_id: int = Path(..., description="Company ID"),
    current_user: User = Depends(require_menu_access("companies", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render company detail view.
    """
    return templates.TemplateResponse(
        "tenancy/admin/company-detail.html",
        get_admin_context(request, db, current_user, company_id=company_id),
    )


@router.get(
    "/companies/{company_id}/edit",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_company_edit_page(
    request: Request,
    company_id: int = Path(..., description="Company ID"),
    current_user: User = Depends(require_menu_access("companies", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render company edit form.
    """
    return templates.TemplateResponse(
        "tenancy/admin/company-edit.html",
        get_admin_context(request, db, current_user, company_id=company_id),
    )


# ============================================================================
# VENDOR MANAGEMENT ROUTES
# ============================================================================


@router.get("/vendors", response_class=HTMLResponse, include_in_schema=False)
async def admin_vendors_list_page(
    request: Request,
    current_user: User = Depends(require_menu_access("vendors", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render vendors management page.
    Shows list of all vendors with stats.
    """
    return templates.TemplateResponse(
        "tenancy/admin/vendors.html",
        get_admin_context(request, db, current_user),
    )


@router.get("/vendors/create", response_class=HTMLResponse, include_in_schema=False)
async def admin_vendor_create_page(
    request: Request,
    current_user: User = Depends(require_menu_access("vendors", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render vendor creation form.
    """
    return templates.TemplateResponse(
        "tenancy/admin/vendor-create.html",
        get_admin_context(request, db, current_user),
    )


@router.get(
    "/vendors/{vendor_code}", response_class=HTMLResponse, include_in_schema=False
)
async def admin_vendor_detail_page(
    request: Request,
    vendor_code: str = Path(..., description="Vendor code"),
    current_user: User = Depends(require_menu_access("vendors", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render vendor detail page.
    Shows full vendor information.
    """
    return templates.TemplateResponse(
        "tenancy/admin/vendor-detail.html",
        get_admin_context(request, db, current_user, vendor_code=vendor_code),
    )


@router.get(
    "/vendors/{vendor_code}/edit", response_class=HTMLResponse, include_in_schema=False
)
async def admin_vendor_edit_page(
    request: Request,
    vendor_code: str = Path(..., description="Vendor code"),
    current_user: User = Depends(require_menu_access("vendors", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render vendor edit form.
    """
    return templates.TemplateResponse(
        "tenancy/admin/vendor-edit.html",
        get_admin_context(request, db, current_user, vendor_code=vendor_code),
    )


# ============================================================================
# VENDOR DOMAINS ROUTES
# ============================================================================


@router.get(
    "/vendors/{vendor_code}/domains",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_vendor_domains_page(
    request: Request,
    vendor_code: str = Path(..., description="Vendor code"),
    current_user: User = Depends(require_menu_access("vendors", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render vendor domains management page.
    Shows custom domains, verification status, and DNS configuration.
    """
    return templates.TemplateResponse(
        "tenancy/admin/vendor-domains.html",
        get_admin_context(request, db, current_user, vendor_code=vendor_code),
    )


# ============================================================================
# VENDOR THEMES ROUTES
# ============================================================================


@router.get("/vendor-themes", response_class=HTMLResponse, include_in_schema=False)
async def admin_vendor_themes_page(
    request: Request,
    current_user: User = Depends(
        require_menu_access("vendor-themes", FrontendType.ADMIN)
    ),
    db: Session = Depends(get_db),
):
    """
    Render vendor themes selection page.
    Allows admins to select a vendor to customize their theme.
    """
    return templates.TemplateResponse(
        "tenancy/admin/vendor-themes.html",
        get_admin_context(request, db, current_user),
    )


@router.get(
    "/vendors/{vendor_code}/theme",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_vendor_theme_page(
    request: Request,
    vendor_code: str = Path(..., description="Vendor code"),
    current_user: User = Depends(
        require_menu_access("vendor-themes", FrontendType.ADMIN)
    ),
    db: Session = Depends(get_db),
):
    """
    Render vendor theme customization page.
    Allows admins to customize colors, fonts, layout, and branding.
    """
    return templates.TemplateResponse(
        "tenancy/admin/vendor-theme.html",
        get_admin_context(request, db, current_user, vendor_code=vendor_code),
    )


# ============================================================================
# ADMIN USER MANAGEMENT ROUTES (Super Admin Only)
# ============================================================================


@router.get("/admin-users", response_class=HTMLResponse, include_in_schema=False)
async def admin_users_list_page(
    request: Request,
    current_user: User = Depends(
        require_menu_access("admin-users", FrontendType.ADMIN)
    ),
    db: Session = Depends(get_db),
):
    """
    Render admin users management page.
    Shows list of all admin users (super admins and platform admins).
    Super admin only (menu is in super_admin_only section).
    """
    return templates.TemplateResponse(
        "tenancy/admin/admin-users.html",
        get_admin_context(request, db, current_user),
    )


@router.get(
    "/admin-users/create", response_class=HTMLResponse, include_in_schema=False
)
async def admin_user_create_page(
    request: Request,
    current_user: User = Depends(
        require_menu_access("admin-users", FrontendType.ADMIN)
    ),
    db: Session = Depends(get_db),
):
    """
    Render admin user creation form.
    Super admin only (menu is in super_admin_only section).
    """
    return templates.TemplateResponse(
        "tenancy/admin/user-create.html",
        get_admin_context(request, db, current_user),
    )


@router.get(
    "/admin-users/{user_id}", response_class=HTMLResponse, include_in_schema=False
)
async def admin_user_detail_page(
    request: Request,
    user_id: int = Path(..., description="User ID"),
    current_user: User = Depends(
        require_menu_access("admin-users", FrontendType.ADMIN)
    ),
    db: Session = Depends(get_db),
):
    """
    Render admin user detail view.
    Super admin only (menu is in super_admin_only section).
    """
    return templates.TemplateResponse(
        "tenancy/admin/admin-user-detail.html",
        get_admin_context(request, db, current_user, user_id=user_id),
    )


@router.get(
    "/admin-users/{user_id}/edit", response_class=HTMLResponse, include_in_schema=False
)
async def admin_user_edit_page(
    request: Request,
    user_id: int = Path(..., description="User ID"),
    current_user: User = Depends(
        require_menu_access("admin-users", FrontendType.ADMIN)
    ),
    db: Session = Depends(get_db),
):
    """
    Render admin user edit form.
    Super admin only (menu is in super_admin_only section).
    """
    return templates.TemplateResponse(
        "tenancy/admin/admin-user-edit.html",
        get_admin_context(request, db, current_user, user_id=user_id),
    )


# ============================================================================
# USER MANAGEMENT ROUTES (Legacy - Redirects)
# ============================================================================


@router.get("/users", response_class=RedirectResponse, include_in_schema=False)
async def admin_users_page_redirect():
    """
    Redirect old /admin/users to /admin/admin-users.
    """
    return RedirectResponse(url="/admin/admin-users", status_code=302)


@router.get("/users/create", response_class=RedirectResponse, include_in_schema=False)
async def admin_user_create_page_redirect():
    """
    Redirect old /admin/users/create to /admin/admin-users/create.
    """
    return RedirectResponse(url="/admin/admin-users/create", status_code=302)


@router.get(
    "/users/{user_id}", response_class=RedirectResponse, include_in_schema=False
)
async def admin_user_detail_page_redirect(
    user_id: int = Path(..., description="User ID"),
):
    """
    Redirect old /admin/users/{id} to /admin/admin-users/{id}.
    """
    return RedirectResponse(url=f"/admin/admin-users/{user_id}", status_code=302)


@router.get(
    "/users/{user_id}/edit", response_class=RedirectResponse, include_in_schema=False
)
async def admin_user_edit_page_redirect(
    user_id: int = Path(..., description="User ID"),
):
    """
    Redirect old /admin/users/{id}/edit to /admin/admin-users/{id}/edit.
    """
    return RedirectResponse(url=f"/admin/admin-users/{user_id}/edit", status_code=302)


# ============================================================================
# PLATFORM MANAGEMENT ROUTES (Multi-Platform Support)
# ============================================================================


@router.get("/platforms", response_class=HTMLResponse, include_in_schema=False)
async def admin_platforms_list(
    request: Request,
    current_user: User = Depends(require_menu_access("platforms", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render platforms management page.
    Shows all platforms (OMS, Loyalty, etc.) with their configuration.
    """
    return templates.TemplateResponse(
        "tenancy/admin/platforms.html",
        get_admin_context(request, db, current_user),
    )


@router.get(
    "/platforms/{platform_code}", response_class=HTMLResponse, include_in_schema=False
)
async def admin_platform_detail(
    request: Request,
    platform_code: str = Path(..., description="Platform code (oms, loyalty, etc.)"),
    current_user: User = Depends(require_menu_access("platforms", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render platform detail page.
    Shows platform configuration, marketing pages, and vendor defaults.
    """
    return templates.TemplateResponse(
        "tenancy/admin/platform-detail.html",
        get_admin_context(request, db, current_user, platform_code=platform_code),
    )


@router.get(
    "/platforms/{platform_code}/edit",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_platform_edit(
    request: Request,
    platform_code: str = Path(..., description="Platform code"),
    current_user: User = Depends(require_menu_access("platforms", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render platform edit form.
    Allows editing platform settings, branding, and configuration.
    """
    return templates.TemplateResponse(
        "tenancy/admin/platform-edit.html",
        get_admin_context(request, db, current_user, platform_code=platform_code),
    )


@router.get(
    "/platforms/{platform_code}/menu-config",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_platform_menu_config(
    request: Request,
    platform_code: str = Path(..., description="Platform code"),
    current_user: User = Depends(require_menu_access("platforms", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render platform menu configuration page.
    Super admin only - allows configuring which menu items are visible
    for the platform's admin and vendor frontends.
    """
    if not current_user.is_super_admin:
        return RedirectResponse(
            url=f"/admin/platforms/{platform_code}", status_code=302
        )

    return templates.TemplateResponse(
        "tenancy/admin/platform-menu-config.html",
        get_admin_context(request, db, current_user, platform_code=platform_code),
    )


@router.get(
    "/platforms/{platform_code}/modules",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_platform_modules(
    request: Request,
    platform_code: str = Path(..., description="Platform code"),
    current_user: User = Depends(require_menu_access("platforms", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render platform module configuration page.
    Super admin only - allows enabling/disabling feature modules
    for the platform.
    """
    if not current_user.is_super_admin:
        return RedirectResponse(
            url=f"/admin/platforms/{platform_code}", status_code=302
        )

    return templates.TemplateResponse(
        "tenancy/admin/platform-modules.html",
        get_admin_context(request, db, current_user, platform_code=platform_code),
    )


@router.get(
    "/platforms/{platform_code}/modules/{module_code}",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_module_info(
    request: Request,
    platform_code: str = Path(..., description="Platform code"),
    module_code: str = Path(..., description="Module code"),
    current_user: User = Depends(require_menu_access("platforms", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render module info/detail page.
    Shows module details including features, menu items, dependencies,
    and self-contained module information.
    """
    if not current_user.is_super_admin:
        return RedirectResponse(
            url=f"/admin/platforms/{platform_code}", status_code=302
        )

    return templates.TemplateResponse(
        "tenancy/admin/module-info.html",
        get_admin_context(
            request, current_user, platform_code=platform_code, module_code=module_code
        ),
    )


@router.get(
    "/platforms/{platform_code}/modules/{module_code}/config",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def admin_module_config(
    request: Request,
    platform_code: str = Path(..., description="Platform code"),
    module_code: str = Path(..., description="Module code"),
    current_user: User = Depends(require_menu_access("platforms", FrontendType.ADMIN)),
    db: Session = Depends(get_db),
):
    """
    Render module configuration page.
    Allows configuring module-specific settings.
    """
    if not current_user.is_super_admin:
        return RedirectResponse(
            url=f"/admin/platforms/{platform_code}", status_code=302
        )

    return templates.TemplateResponse(
        "tenancy/admin/module-config.html",
        get_admin_context(
            request, current_user, platform_code=platform_code, module_code=module_code
        ),
    )
