from fastapi import APIRouter, Request, Depends, Query
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from app.core.database import get_db
from app.core.security import require_roles, get_current_user
from app.models.models import Customer
import os
import traceback
from datetime import datetime, timezone, timedelta

router = APIRouter(dependencies=[Depends(require_roles("admin_cs", "teknisi", "agen_voucher"))])
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))

@router.get("/api/customers/live")
async def get_live_customers(ids: str = Query(""), db: AsyncSession = Depends(get_db)):
    if not ids:
        return JSONResponse({"customers": []})
    id_list = [int(i.strip()) for i in ids.split(",") if i.strip().isdigit()]
    if not id_list:
        return JSONResponse({"customers": []})
    
    result = await db.execute(select(Customer).where(Customer.id.in_(id_list)))
    customers = result.scalars().all()
    
    out = []
    for c in customers:
        # Status utama pelanggan dan status layanan WiFi adalah dua hal berbeda.
        if c.status == "active":
            customer_indicator = '<span class="status-icon status-icon-online" title="Pelanggan aktif" aria-label="Pelanggan aktif"></span>'
            customer_explanation = "Hijau — pelanggan aktif"
        elif c.status == "isolir":
            customer_indicator = '<span class="status-icon status-icon-los" title="Pelanggan diisolir" aria-label="Pelanggan diisolir"></span>'
            customer_explanation = "Merah — pelanggan diisolir"
        elif c.status in ("request", "pending_provisioning", "configuring"):
            customer_indicator = '<span class="status-icon status-icon-waiting" title="Status pelanggan masih diproses" aria-label="Status pelanggan masih diproses"></span>'
            customer_explanation = "Kuning — status pelanggan masih diproses"
        else:
            customer_indicator = '<span class="status-icon status-icon-offline" title="Status pelanggan tidak aktif" aria-label="Status pelanggan tidak aktif"></span>'
            customer_explanation = "Abu-abu — pelanggan tidak aktif"

        wifi_pending = (
            (c.service_mode == "hotspot" or c.type == "hotspot_voucher")
            and (
                c.acs_wifi_status == "pending"
                or c.mikrotik_provisioning_status in ("pending_configuration", "waiting_session", "waiting_internet")
                or c.provisioning_status != "provisioned"
            )
        )
        wifi_badge = (
            '<span class="status-icon status-icon-waiting" title="Layanan WiFi/Hotspot masih menunggu konfigurasi" aria-label="WiFi pending"></span>'
            if wifi_pending else ""
        )
        indicator = f'<div class="inline-flex items-center justify-center gap-2">{customer_indicator}{wifi_badge}</div>'
        wifi_explanation = (
            f"Kuning berkedip — layanan WiFi/Hotspot masih pending "
            f"(ACS: {c.acs_wifi_status or '-'}, MikroTik: {c.mikrotik_provisioning_status or '-'}, provisioning: {c.provisioning_status or '-'})"
            if wifi_pending else "Tidak ada indikator tambahan — layanan WiFi tidak pending"
        )

        out.append({
            "id": c.id,
            "power": c.ont_rx_power or "N/A",
            "indicator": indicator,
            "customer_explanation": customer_explanation,
            "wifi_explanation": wifi_explanation,
        })
    return JSONResponse({"customers": out})

@router.get("/customers", response_class=HTMLResponse)
async def list_customers(
    request: Request,
    type: str | None = Query(default=None),
    status: str | None = Query(default=None),
    page: int = Query(default=1, ge=1),
    db: AsyncSession = Depends(get_db),
    user = Depends(get_current_user),
):
    """Server-side pagination: safe for large customer populations."""
    if user.role == "teknisi":
        return RedirectResponse(url="/tasks", status_code=303)
    try:
        page_size = 25
        filters = [Customer.is_archived == False]
        if type:
            filters.append(Customer.type == type)
        if status == "pending":
            filters.append(Customer.status.in_(("request", "pending_provisioning")))
        elif status:
            filters.append(Customer.status == status)
        total = await db.scalar(select(func.count(Customer.id)).where(*filters)) or 0
        total_pages = max(1, (total + page_size - 1) // page_size)
        page = min(page, total_pages)
        from sqlalchemy.orm import selectinload
        result = await db.execute(
            select(Customer).options(selectinload(Customer.odp), selectinload(Customer.service_package), selectinload(Customer.olt_device)).where(*filters).order_by(Customer.created_at.desc()).offset((page - 1) * page_size).limit(page_size)
        )
        customers = result.scalars().all()
        return templates.TemplateResponse(
            request=request, name="customers.html",
            context={
                "customers": customers, "type_filter": type, "status_filter": status,
                "page": page, "page_size": page_size, "total": total, "total_pages": total_pages,
                "page_numbers": range(max(1, page - 2), min(total_pages, page + 2) + 1),
            },
        )
    except Exception:
        traceback.print_exc()
        return HTMLResponse(content="Gagal memuat data pelanggan.", status_code=500)
