from fastapi import APIRouter, Depends, HTTPException, Query
from sqlmodel import Session, select
from uuid import UUID

from app.core.database import get_session
from app.models.user import User
from app.api.deps import get_current_admin

router = APIRouter(prefix="/api/users", tags=["users"])

@router.get("/search")
async def search_users(
    email: str = Query(..., description="Email to search for"),
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Search for users by email (Admin only)."""
    statement = select(User).where(User.email.contains(email))
    users = session.exec(statement).all()
    
    # Clean response (don't send hashed passwords)
    return [
        {
            "id": user.id,
            "email": user.email,
            "full_name": user.full_name,
            "role": user.role,
            "is_verified": user.is_verified,
            "created_at": user.created_at
        } for user in users
    ]

@router.get("/{user_id}")
async def get_user_details(
    user_id: UUID,
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Get detailed user info including driver profile (Admin only)."""
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    
    result = {
        "id": user.id,
        "email": user.email,
        "full_name": user.full_name,
        "role": user.role,
        "is_active": user.is_active,
        "is_verified": user.is_verified,
        "created_at": user.created_at,
        "driver_profile": None
    }
    
    if user.driver_profile:
        dp = user.driver_profile
        result["driver_profile"] = {
            "cedula": dp.cedula,
            "vehicle_type": dp.vehicle_type,
            "license_plate": dp.license_plate,
            "cooperative_name": dp.cooperative_name,
            "photo_url": dp.photo_url,
            "vehicle_photo_url": dp.vehicle_photo_url,
            "shift": dp.shift,
            "payment_methods": dp.payment_methods,
            "speaks_english": dp.speaks_english
        }
    
    return result

@router.get("/pending-drivers")
async def get_pending_drivers(
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """List drivers waiting for verification (Admin only)."""
    # Find users with DRIVER role who are NOT verified
    from app.models.user import UserRole
    statement = select(User).where(User.role == UserRole.DRIVER, User.is_verified.is_(False))
    
    return [
        {
            "id": driver.id,
            "email": driver.email,
            "full_name": driver.full_name,
            "created_at": driver.created_at,
            "driver_profile": {
                "cedula": driver.driver_profile.cedula,
                "vehicle_type": driver.driver_profile.vehicle_type,
                "license_plate": driver.driver_profile.license_plate,
                "cooperative_name": driver.driver_profile.cooperative_name,
                "shift": driver.driver_profile.shift,
                "payment_methods": driver.driver_profile.payment_methods,
                "speaks_english": driver.driver_profile.speaks_english
            } if driver.driver_profile else None
        } for driver in session.exec(statement).all()
    ]

@router.post("/{user_id}/verify")
async def verify_user(
    user_id: UUID,
    is_verified: bool = Query(..., description="True to approve, False to stay unverified/reject"),
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Approve or Reject a user verification (Admin only)."""
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    
    user.is_verified = is_verified
    session.add(user)
    session.commit()
    session.refresh(user)
    
    return {"id": user.id, "email": user.email, "is_verified": user.is_verified}
