from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import Query

from app.database.database import get_db
from app.services.user.user_auth_service import UserAuthService
from app.schemas.user.user_schemas import (
    UserRegisterRequest,
    OTPVerifyRequest,
    ResendOTPRequest,
    UserProfileCompleteRequest,
    UserLoginRequest,
    RefreshTokenRequest,
    LogoutRequest,
    RegisterResponse,
    OTPVerifyResponse,
    ProfileCompleteResponse,
    UserLoginResponse,
    RefreshTokenResponse,
    LogoutResponse,
    ForgotPasswordRequest,
    ResetPasswordRequest,
    UserResponse,
    UpdateProfileRequest,
    UpdateProfileResponse
)
from app.utils.auth import get_customer_user

router = APIRouter()


@router.post("/register", response_model=RegisterResponse, status_code=status.HTTP_201_CREATED)
async def register(
    register_data: UserRegisterRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    Step 1: Register a new user with email and password.
    OTP will be sent to the email for verification.
    """
    service = UserAuthService(db)
    result = await service.register_user(register_data)
    return result


@router.post("/verify-otp", response_model=OTPVerifyResponse)
async def verify_otp(
    verify_data: OTPVerifyRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    Step 2: Verify OTP sent to user's email.
    After successful verification, user can complete their profile.
    """
    service = UserAuthService(db)
    result = await service.verify_otp(verify_data.email, verify_data.otp_code)
    return result


@router.post("/resend-otp", response_model=RegisterResponse)
async def resend_otp(
    resend_data: ResendOTPRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    Resend OTP to user's email if previous OTP expired or was not received.
    """
    service = UserAuthService(db)
    result = await service.resend_otp(resend_data.email)
    return result


@router.post("/complete-profile", response_model=ProfileCompleteResponse)
async def complete_profile(
    profile_data: UserProfileCompleteRequest,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Step 3: Complete user profile after OTP verification.
    Provide full name, phone number, address, and optional profile image URL.
    Requires the access token received from OTP verification.
    Returns new access token upon successful completion.
    """
    service = UserAuthService(db)
    user_id = int(current_user["sub"])
    result = await service.complete_profile(user_id, profile_data)
    return result


@router.post("/login", response_model=UserLoginResponse)
async def login(
    login_data: UserLoginRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    Login with email and password.
    Returns access token, refresh token, and user information.
    """
    service = UserAuthService(db)
    result = await service.login_user(login_data.email, login_data.password)
    return result


@router.post("/refresh", response_model=RefreshTokenResponse)
async def refresh_token(
    refresh_data: RefreshTokenRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    Refresh access token using refresh token.
    Returns new access token and refresh token.
    When access token expires, use this endpoint to get a new one without re-logging in.
    
    Note: Old refresh token will be blacklisted and cannot be reused.
    """
    service = UserAuthService(db)
    result = await service.refresh_access_token(refresh_data.refresh_token)
    return result


@router.post("/forgot-password")
async def forgot_password(
    payload: ForgotPasswordRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    Send password reset OTP to user's email (generic response to avoid enumeration).
    """
    service = UserAuthService(db)
    return await service.forgot_password(payload.email)


@router.post("/reset-password")
async def reset_password(
    payload: ResetPasswordRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    Reset password using OTP sent to email.
    """
    service = UserAuthService(db)
    return await service.reset_password(payload.email, payload.otp_code, payload.new_password)

@router.post("/logout", response_model=LogoutResponse)
async def logout(
    logout_data: LogoutRequest,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Logout user by blacklisting their refresh token.
    After logout, the refresh token cannot be used to get new access tokens.
    User must login again to get new tokens.
    """
    service = UserAuthService(db)
    user_id = int(current_user["sub"])
    result = await service.logout_user(logout_data.refresh_token, user_id)
    return result


@router.get("/me", response_model=UserResponse)
async def get_current_user_profile(
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Get current authenticated user's profile information.
    Requires valid JWT token.
    """
    service = UserAuthService(db)
    user_id = int(current_user["sub"])
    return await service.get_current_user_profile(user_id)


@router.put("/update-profile", response_model=UpdateProfileResponse)
async def update_profile(
    profile_data: UpdateProfileRequest,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Update user profile information.
    All fields are optional - only provided fields will be updated.
    Requires valid JWT token.
    
    If latitude/longitude are updated and travel mode is enabled,
    will check for nearby favorite products and send notifications.
    """
    service = UserAuthService(db)
    user_id = int(current_user["sub"])
    
    # Check if location is being updated
    location_updated = profile_data.latitude is not None or profile_data.longitude is not None
    
    if location_updated:
        latitude = profile_data.latitude
        longitude = profile_data.longitude
        print(f"\n📍 PROFILE UPDATE - Location Change - User {user_id}")
        if latitude is not None and longitude is not None:
            print(f"   📍 New Location: ({latitude}, {longitude})")
        elif latitude is not None:
            print(f"   📍 Latitude Updated: {latitude}")
        elif longitude is not None:
            print(f"   📍 Longitude Updated: {longitude}")
    
    result = await service.update_profile(user_id, profile_data)
    
    # Check if travel mode is enabled and location was updated
    if location_updated:
        # Get fresh user data from database to check travel mode status
        from app.models.user.user_model import User
        from sqlalchemy import select
        user_stmt = select(User).where(User.user_id == user_id)
        user_result = await db.execute(user_stmt)
        user_obj = user_result.scalar_one_or_none()
        
        if user_obj:
            is_travel_enabled = user_obj.is_travel_enabled if user_obj else False
            has_device_token = bool(user_obj.device_token) if user_obj else False
            
            print(f"   🔍 User Status Check:")
            print(f"      Travel Mode: {'✅ ENABLED' if is_travel_enabled else '❌ DISABLED'}")
            print(f"      Device Token: {'✅ Set' if has_device_token else '❌ Missing'}")
            print(f"      Location: ({user_obj.latitude}, {user_obj.longitude})" if user_obj.latitude and user_obj.longitude else "      Location: ⚠️ Not set")
            
            if is_travel_enabled:
                print(f"   ✅ Travel Mode: ENABLED - Checking for nearby favorite products...")
                # Run notification check in background with a NEW session
                from app.services.user.notification_service import check_travel_mode_notifications
                import asyncio
                from app.database.database import AsyncSessionLocal
                async def _run_travel_check_bg(u_id: int):
                    async with AsyncSessionLocal() as session:
                        await check_travel_mode_notifications(session, u_id)
                asyncio.create_task(_run_travel_check_bg(user_id))
            else:
                print(f"   ⏸️  Travel Mode: DISABLED - Skipping notification check")
                print(f"   💡 To enable travel mode, set 'is_travel_enabled': true in your profile update")
        else:
            print(f"   ⚠️  Could not fetch user data for travel mode check")
    
    return result


@router.post("/admin/cleanup-blacklist")
async def cleanup_blacklist(
    db: AsyncSession = Depends(get_db)
):
    """
    Admin endpoint to cleanup expired tokens from blacklist.
    This should be called periodically (e.g., via cron job).
    
    Removes all tokens where expires_at < current time.
    """
    service = UserAuthService(db)
    result = await service.cleanup_expired_blacklist()
    return result


@router.get("/health")
async def health_check():
    """
    Health check endpoint for user authentication service.
    """
    return {
        "status": "healthy",
        "service": "user-authentication",
        "message": "User authentication service is running"
    }

