import uuid

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from app.api.v1.deps import require_role
from app.core.config import settings
from app.db.session import get_db
from app.models.order import OrderStatus
from app.models.otp import OTPPurpose
from app.models.user import User, UserRole
from app.schemas.analytics import (
    AdminAnalyticsOut,
    OrderStatusBreakdownOut,
    TopBranchOut,
    TopMerchantOut,
)
from app.schemas.auth import (
    InviteResponse,
    PhoneAndNameRequest,
    UserOut,
    UserStatusUpdateRequest,
)
from app.schemas.delivery import (
    CourierEarningsSummaryOut,
    CourierProfileOut,
    CourierProfileUpdateRequest,
)
from app.services import analytics as analytics_service
from app.services import dispatch as dispatch_service
from app.services import earnings as earnings_service
from app.services import otp as otp_service

router = APIRouter(prefix="/admin", tags=["admin"])

_ACCOUNT_EXISTS = HTTPException(
    status_code=status.HTTP_409_CONFLICT,
    detail="An account with this phone number already exists.",
)
_EMAIL_EXISTS = HTTPException(
    status_code=status.HTTP_409_CONFLICT,
    detail="An account with this email already exists.",
)


def _invite_user(
    db: Session, payload: PhoneAndNameRequest, role: UserRole
) -> InviteResponse:
    """Create a User row for the given role with no PIN yet, and send
    them an SMS code to activate it themselves via /auth/activate/*.
    Never sets a PIN here — that would mean transmitting it out of
    band, which is exactly what this flow avoids."""
    if db.query(User).filter(User.phone == payload.phone).first() is not None:
        raise _ACCOUNT_EXISTS
    if db.query(User).filter(User.email == payload.email).first() is not None:
        raise _EMAIL_EXISTS

    user = User(
        phone=payload.phone,
        name=payload.name,
        email=payload.email,
        role=role.value,
        pin_hash=None,
    )
    db.add(user)
    db.commit()
    db.refresh(user)

    code = otp_service.create_and_send_otp(
        db, payload.phone, OTPPurpose.ACTIVATE_ACCOUNT
    )
    message = f"{role.value.capitalize()} invited. They'll receive an SMS code to activate their account."

    response = InviteResponse(message=message, user=UserOut.model_validate(user))
    if code is not None and settings.environment == "development":
        response.debug_otp = code
    return response


@router.post("/couriers", response_model=InviteResponse)
def invite_courier(
    payload: PhoneAndNameRequest,
    db: Session = Depends(get_db),
    _admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
) -> InviteResponse:
    return _invite_user(db, payload, UserRole.COURIER)


@router.patch("/couriers/{courier_id}", response_model=CourierProfileOut)
def update_courier_profile(
    courier_id: uuid.UUID,
    payload: CourierProfileUpdateRequest,
    db: Session = Depends(get_db),
    _admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
) -> CourierProfileOut:
    """Both shift hours and the online/offline switch are admin-only —
    couriers here are full-time staff on a schedule the business sets,
    not gig workers picking their own hours (see
    app.api.v1.endpoints.courier.get_profile for the courier's
    read-only view of what's configured for them). A courier needs
    both is_online and to be inside their shift window to receive
    offers — see app.services.dispatch.dispatch_next_courier.
    All fields optional: send just the ones you're changing."""
    courier = db.query(User).filter(User.id == courier_id).first()
    if courier is None or courier.role != UserRole.COURIER.value:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Courier not found."
        )

    profile = dispatch_service.get_or_create_profile(db, courier.id)
    updates = payload.model_dump(exclude_unset=True)
    for field, value in updates.items():
        setattr(profile, field, value)
    db.commit()
    db.refresh(profile)
    return CourierProfileOut.model_validate(profile)


@router.get("/couriers/{courier_id}/earnings", response_model=CourierEarningsSummaryOut)
def get_courier_earnings(
    courier_id: uuid.UUID,
    db: Session = Depends(get_db),
    _admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
) -> CourierEarningsSummaryOut:
    courier = db.query(User).filter(User.id == courier_id).first()
    if courier is None or courier.role != UserRole.COURIER.value:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Courier not found."
        )

    total, count = earnings_service.get_summary(db, courier_id)
    return CourierEarningsSummaryOut(total_earnings=total, delivery_count=count)


@router.post("/suppliers", response_model=InviteResponse)
def invite_supplier(
    payload: PhoneAndNameRequest,
    db: Session = Depends(get_db),
    _admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
) -> InviteResponse:
    return _invite_user(db, payload, UserRole.SUPPLIER)


@router.post("/admins", response_model=InviteResponse)
def invite_admin(
    payload: PhoneAndNameRequest,
    db: Session = Depends(get_db),
    _superadmin: User = Depends(require_role(UserRole.SUPERADMIN)),
) -> InviteResponse:
    """Only a superadmin can invite another admin — a regular admin
    cannot grant admin access to anyone, including themselves."""
    return _invite_user(db, payload, UserRole.ADMIN)


@router.get("/users", response_model=list[UserOut])
def list_users(
    role: str | None = None,
    is_active: bool | None = None,
    db: Session = Depends(get_db),
    _admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
) -> list[UserOut]:
    """Every account on the platform, across every role — the roster
    an admin console needs (who's a courier, who's a supplier, who's
    been deactivated). Pass role to narrow to one (customer/courier/
    supplier/manager/admin/superadmin) and/or is_active to filter by
    active status."""
    query = db.query(User)
    if role is not None:
        query = query.filter(User.role == role)
    if is_active is not None:
        query = query.filter(User.is_active.is_(is_active))
    users = query.order_by(User.created_at.desc()).all()
    return [UserOut.model_validate(u) for u in users]


@router.patch("/users/{user_id}/status", response_model=UserOut)
def update_user_status(
    user_id: uuid.UUID,
    payload: UserStatusUpdateRequest,
    db: Session = Depends(get_db),
    admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
) -> UserOut:
    """Deactivating blocks both login and any already-issued access/
    refresh token immediately (see UserStatusUpdateRequest) — no
    separate session-revocation step needed. Changing an admin's or
    superadmin's own status is superadmin-only, the same restriction
    already used for inviting one in the first place (see
    invite_admin) — a regular admin can't lock out, or reactivate,
    another admin."""
    target = db.query(User).filter(User.id == user_id).first()
    if target is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="User not found."
        )

    if (
        target.role in {UserRole.ADMIN.value, UserRole.SUPERADMIN.value}
        and admin.role != UserRole.SUPERADMIN.value
    ):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only a superadmin can change another admin's status.",
        )

    target.is_active = payload.is_active
    db.commit()
    db.refresh(target)
    return UserOut.model_validate(target)


@router.get("/analytics", response_model=AdminAnalyticsOut)
def get_analytics(
    days: int = Query(30, ge=1, le=365),
    db: Session = Depends(get_db),
    admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
) -> AdminAnalyticsOut:
    """System-performance snapshot for the admin console. Order
    volume, the status breakdown, cancellation rate, and top
    merchants/branches are windowed to the last `days` days (default
    30); active couriers/branches are a live right-now count, not
    windowed — "how many can take an order right now" isn't a
    historical question. revenue (Yeneb's own cut, not gross order
    value — see app.services.analytics.get_platform_revenue) is
    superadmin-only: a regular admin gets null there. Kept as one
    shared endpoint rather than a second superadmin-only one, since
    every other field is identical for both roles."""
    breakdown = analytics_service.get_order_status_breakdown(db, days)
    order_volume = sum(breakdown.values())
    cancelled = breakdown[OrderStatus.CANCELLED.value]
    cancellation_rate = (cancelled / order_volume) if order_volume else 0.0

    top_merchants = [
        TopMerchantOut(
            merchant_id=merchant_id,
            merchant_name=name,
            order_count=count,
            total_sales=total,
        )
        for merchant_id, name, count, total in analytics_service.get_top_merchants(
            db, days
        )
    ]
    top_branches = [
        TopBranchOut(
            branch_id=branch_id,
            branch_name=name,
            order_count=count,
            total_sales=total,
        )
        for branch_id, name, count, total in analytics_service.get_top_branches(
            db, days
        )
    ]

    revenue = None
    if admin.role == UserRole.SUPERADMIN.value:
        revenue = analytics_service.get_platform_revenue(db, days)

    return AdminAnalyticsOut(
        period_days=days,
        order_volume=order_volume,
        order_status_breakdown=[
            OrderStatusBreakdownOut(status=s, count=c) for s, c in breakdown.items()
        ],
        cancellation_rate=cancellation_rate,
        active_couriers=analytics_service.get_active_courier_count(db),
        active_branches=analytics_service.get_active_branch_count(db),
        top_merchants=top_merchants,
        top_branches=top_branches,
        revenue=revenue,
    )
