from datetime import datetime, timedelta
from typing import Optional
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from fastapi import HTTPException, status
from passlib.context import CryptContext

from app.models.user.user_model import User, TokenBlacklist
from app.schemas.user.user_schemas import (
    UserRegisterRequest,
    UserProfileCompleteRequest,
    UserResponse,
    UpdateProfileRequest
)
from app.utils.jwt import create_access_token, create_refresh_token, verify_token
from app.services.user.otp_service import OTPService

# Password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


class UserAuthService:
    """Service for user authentication and registration"""
    
    def __init__(self, db: AsyncSession):
        self.db = db
        self.otp_service = OTPService(db)
    
    def _hash_password(self, password: str) -> str:
        """Hash a password"""
        return pwd_context.hash(password)
    
    def _verify_password(self, plain_password: str, hashed_password: str) -> bool:
        """Verify a password against its hash"""
        return pwd_context.verify(plain_password, hashed_password)
    
    async def get_user_by_email(self, email: str) -> Optional[User]:
        """Get user by email (case-insensitive)"""
        # Normalize email to lowercase for case-insensitive lookup
        email_lower = email.lower().strip()
        from sqlalchemy import func
        stmt = select(User).where(func.lower(User.email) == email_lower)
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()
    
    async def get_user_by_id(self, user_id: int) -> Optional[User]:
        """Get user by ID"""
        stmt = select(User).where(User.user_id == user_id)
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()
    
    async def register_user(self, register_data: UserRegisterRequest) -> dict:
        """Step 1: Register user with email and password, send OTP"""
        # Normalize email to lowercase
        email_normalized = register_data.email.lower().strip()
        
        # Check if user already exists
        existing_user = await self.get_user_by_email(email_normalized)
        
        if existing_user:
            if existing_user.is_verified:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="User with this email already exists"
                )
            else:
                # User exists but not verified, invalidate old OTPs and send new one
                await self.otp_service.invalidate_old_otps(email_normalized)
                await self.otp_service.create_and_send_otp(email_normalized)
                
                return {
                    "message": "OTP sent to your email. Please verify to continue.",
                    "email": email_normalized,
                    "otp_sent": True
                }
        
        # Create new user (unverified) - store email in lowercase
        hashed_password = self._hash_password(register_data.password)
        new_user = User(
            email=email_normalized,
            hashed_password=hashed_password,
            is_verified=False,
            is_active=True
        )
        
        self.db.add(new_user)
        await self.db.commit()
        
        # Send OTP
        await self.otp_service.create_and_send_otp(email_normalized)
        
        return {
            "message": "Registration successful! OTP sent to your email.",
            "email": email_normalized,
            "otp_sent": True
        }
    
    async def verify_otp(self, email: str, otp_code: str) -> dict:
        """Step 2: Verify OTP and return access token"""
        # Normalize email to lowercase
        email_normalized = email.lower().strip()
        
        # Verify OTP
        is_valid = await self.otp_service.verify_otp(email_normalized, otp_code)
        
        if not is_valid:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid or expired OTP code"
            )
        
        # Get user
        user = await self.get_user_by_email(email_normalized)
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Generate access token and refresh token for partially verified user
        token_data = {
            "sub": str(user.user_id),
            "email": user.email,
            "user_type": "customer",
            "profile_completed": False  # Flag to indicate profile not completed yet
        }
        access_token = create_access_token(data=token_data)
        refresh_token = create_refresh_token(data=token_data)
        
        return {
            "message": "OTP verified successfully. Please complete your profile.",
            "email": email_normalized,
            "verified": True,
            "access_token": access_token,
            "refresh_token": refresh_token,
            "token_type": "bearer"
        }
    
    async def resend_otp(self, email: str) -> dict:
        """Resend OTP to user email"""
        # Normalize email to lowercase
        email_normalized = email.lower().strip()
        
        # Check if user exists
        user = await self.get_user_by_email(email_normalized)
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        if user.is_verified:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="User is already verified"
            )
        
        # Invalidate old OTPs and send new one
        await self.otp_service.invalidate_old_otps(email_normalized)
        await self.otp_service.create_and_send_otp(email_normalized)
        
        return {
            "message": "OTP sent to your email",
            "email": email_normalized,
            "otp_sent": True
        }
    
    async def complete_profile(self, user_id: int, profile_data: UserProfileCompleteRequest) -> dict:
        """Step 3: Complete user profile after OTP verification"""
        # Get user by ID from token
        user = await self.get_user_by_id(user_id)
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        if user.is_verified and user.full_name:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Profile already completed"
            )
        
        # Update user profile
        user.full_name = profile_data.full_name
        user.phone_number = profile_data.phone_number
        user.address = profile_data.address
        user.profile_image = profile_data.profile_image
        user.latitude = profile_data.latitude
        user.longitude = profile_data.longitude
        user.is_verified = True
        user.updated_at = datetime.utcnow()
        
        await self.db.commit()
        await self.db.refresh(user)
        
        # Generate new access token and refresh token with profile_completed flag
        token_data = {
            "sub": str(user.user_id),
            "email": user.email,
            "user_type": "customer",
            "profile_completed": True
        }
        access_token = create_access_token(data=token_data)
        refresh_token = create_refresh_token(data=token_data)
        
        return {
            "message": "Profile completed successfully",
            "user": UserResponse.model_validate(user),
            "access_token": access_token,
            "refresh_token": refresh_token,
            "token_type": "bearer"
        }
    
    async def login_user(self, email: str, password: str) -> dict:
        """Login user with email and password (case-insensitive email)"""
        # Normalize email to lowercase for case-insensitive lookup
        email_normalized = email.lower().strip()
        
        # Get user
        user = await self.get_user_by_email(email_normalized)
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid email or password"
            )
        
        # Verify password
        if not self._verify_password(password, user.hashed_password):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid email or password"
            )
        
        # Check if user is verified
        if not user.is_verified:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Please verify your email first"
            )
        
        # Check if user is active
        if not user.is_active:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Your account has been deactivated"
            )
        
        # Check subscription expiry before returning user data
        await self._check_subscription_expiry(user)
        
        # Generate access token and refresh token
        token_data = {
            "sub": str(user.user_id),
            "email": user.email,
            "user_type": "customer",
            "profile_completed": True  # Login only works after profile is completed
        }
        access_token = create_access_token(data=token_data)
        refresh_token = create_refresh_token(data=token_data)
        
        return {
            "access_token": access_token,
            "refresh_token": refresh_token,
            "token_type": "bearer",
            "user": UserResponse.model_validate(user)
        }
    
    async def _check_subscription_expiry(self, user: User) -> None:
        """Check if subscription has expired and update user status"""
        if user.is_pro and user.subscription_expires_at:
            from datetime import datetime, timezone
            now = datetime.now(timezone.utc)
            if user.subscription_expires_at <= now:
                # Subscription expired
                user.is_pro = False
                user.subscription_expires_at = None
                
                # Update subscription status in database
                from app.models.user.subscription_model import UserSubscription, SubscriptionStatus
                from sqlalchemy import select, and_, cast, String
                # Cast status to string to handle VARCHAR column type mismatch
                stmt = select(UserSubscription).where(
                    and_(
                        UserSubscription.user_id == user.user_id,
                        cast(UserSubscription.status, String) == SubscriptionStatus.ACTIVE.value
                    )
                )
                result = await self.db.execute(stmt)
                active_subscription = result.scalar_one_or_none()
                
                if active_subscription:
                    active_subscription.status = SubscriptionStatus.EXPIRED
                    active_subscription.expires_at = now
                
                await self.db.commit()
                await self.db.refresh(user)
    
    async def get_current_user_profile(self, user_id: int) -> UserResponse:
        """Get current user profile"""
        user = await self.get_user_by_id(user_id)
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Check subscription expiry before returning user data
        await self._check_subscription_expiry(user)
        
        return UserResponse.model_validate(user)
    
    async def update_profile(self, user_id: int, profile_data: UpdateProfileRequest) -> dict:
        """Update user profile (partial update)"""
        user = await self.get_user_by_id(user_id)
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Update only provided fields
        update_data = profile_data.model_dump(exclude_unset=True)
        
        if not update_data:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="No fields provided for update"
            )
        
        for field, value in update_data.items():
            setattr(user, field, value)
        
        user.updated_at = datetime.utcnow()
        
        await self.db.commit()
        await self.db.refresh(user)
        
        return {
            "message": "Profile updated successfully",
            "user": UserResponse.model_validate(user)
        }
    
    async def refresh_access_token(self, refresh_token: str) -> dict:
        """Refresh access token using refresh token"""
        # Check if token is already blacklisted
        blacklist_stmt = select(TokenBlacklist).where(TokenBlacklist.token == refresh_token)
        blacklist_result = await self.db.execute(blacklist_stmt)
        blacklisted_token = blacklist_result.scalar_one_or_none()
        
        if blacklisted_token:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Token has been revoked. Please login again."
            )
        
        # Verify refresh token
        payload = verify_token(refresh_token, "refresh")
        
        # Verify it's a customer user
        if payload.get("user_type") != "customer":
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Invalid token type"
            )
        
        # Get user to ensure they still exist and are active
        user_id = int(payload.get("sub"))
        user = await self.get_user_by_id(user_id)
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        if not user.is_active:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Your account has been deactivated"
            )
        
        # Generate new access token and refresh token
        token_data = {
            "sub": str(user.user_id),
            "email": user.email,
            "user_type": "customer",
            "profile_completed": user.is_verified and user.full_name is not None
        }
        new_access_token = create_access_token(data=token_data)
        new_refresh_token = create_refresh_token(data=token_data)
        
        # Add old refresh token to blacklist
        # Use the token's actual expiration time from JWT payload
        token_exp = payload.get("exp")
        if token_exp:
            # Convert Unix timestamp to datetime
            from datetime import timezone
            expires_at = datetime.fromtimestamp(token_exp, tz=timezone.utc)
        else:
            # Fallback: 7 days from now if no exp claim
            from datetime import timedelta
            expires_at = datetime.utcnow() + timedelta(days=7)
        
        blacklist_entry = TokenBlacklist(
            token=refresh_token,
            user_id=user_id,
            expires_at=expires_at,
            reason="refresh"
        )
        self.db.add(blacklist_entry)
        await self.db.commit()
        
        return {
            "access_token": new_access_token,
            "refresh_token": new_refresh_token,
            "token_type": "bearer"
        }
    
    async def logout_user(self, refresh_token: str, user_id: int) -> dict:
        """Logout user by blacklisting their refresh token and clearing device token to stop notifications"""
        # Check if token is already blacklisted
        blacklist_stmt = select(TokenBlacklist).where(TokenBlacklist.token == refresh_token)
        blacklist_result = await self.db.execute(blacklist_stmt)
        blacklisted_token = blacklist_result.scalar_one_or_none()
        
        if blacklisted_token:
            # Even if token already blacklisted, still clear device token
            user = await self.get_user_by_id(user_id)
            if user and user.device_token:
                user.device_token = None
                await self.db.commit()
            return {
                "message": "Already logged out",
                "success": True
            }
        
        # Verify token to get expiration time
        try:
            payload = verify_token(refresh_token, "refresh")
            token_exp = payload.get("exp")
            if token_exp:
                # Use token's actual expiration
                from datetime import timezone
                expires_at = datetime.fromtimestamp(token_exp, tz=timezone.utc)
            else:
                # Fallback
                from datetime import timedelta
                expires_at = datetime.utcnow() + timedelta(days=7)
        except:
            # If token verification fails, use default expiration
            from datetime import timedelta
            expires_at = datetime.utcnow() + timedelta(days=7)
        
        # Add refresh token to blacklist
        blacklist_entry = TokenBlacklist(
            token=refresh_token,
            user_id=user_id,
            expires_at=expires_at,
            reason="logout"
        )
        self.db.add(blacklist_entry)
        # Clear device token so user won't receive push notifications after logout
        user = await self.get_user_by_id(user_id)
        if user and user.device_token:
            user.device_token = None
        await self.db.commit()
        
        return {
            "message": "Logged out successfully",
            "success": True
        }
    
    async def cleanup_expired_blacklist(self) -> dict:
        """Remove expired tokens from blacklist (maintenance task)"""
        from sqlalchemy import delete
        
        # Delete expired blacklist entries
        delete_stmt = delete(TokenBlacklist).where(
            TokenBlacklist.expires_at < datetime.utcnow()
        )
        result = await self.db.execute(delete_stmt)
        await self.db.commit()
        
        return {
            "message": "Blacklist cleanup completed",
            "deleted_count": result.rowcount
        }

    async def forgot_password(self, email: str) -> dict:
        """Send password reset OTP to user's email if account exists (do not reveal existence)."""
        # Normalize email to lowercase
        email_normalized = email.lower().strip()
        user = await self.get_user_by_email(email_normalized)
        # To prevent user enumeration, always respond success, but only send OTP if user exists and verified
        if user and user.is_active:
            await self.otp_service.invalidate_old_otps(email_normalized)
            await self.otp_service.create_and_send_otp(email_normalized)
        return {"message": "If the email exists, an OTP has been sent"}

    async def reset_password(self, email: str, otp_code: str, new_password: str) -> dict:
        """Verify OTP and set a new password."""
        # Normalize email to lowercase
        email_normalized = email.lower().strip()
        user = await self.get_user_by_email(email_normalized)
        if not user:
            # Same generic message to avoid enumeration
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid email or OTP"
            )
        is_valid = await self.otp_service.verify_otp(email_normalized, otp_code)
        if not is_valid:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid or expired OTP"
            )
        user.hashed_password = self._hash_password(new_password)
        user.updated_at = datetime.utcnow()
        await self.db.commit()
        return {"message": "Password has been reset successfully"}

