"""
Customer APIs for browsing products, stores, and categories
Public endpoints - no authentication required
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.database import get_db
from app.enums.enums import ListingTypeEnum
from app.services.user.customer_service import CustomerService
from app.services.user.address_service import UserAddressService
from app.services.user.user_auth_service import UserAuthService
from app.schemas.user.customer_schemas import CategoryResponse
from app.schemas.user.user_schemas import (
    UserAddressCreateRequest,
    UserAddressResponse,
    UserAddressUpdateRequest,
    UserAddressDeleteResponse,
    UpdateProfileRequest,
)
from app.schemas.user.notification_schemas import (
    NotificationListResponse,
    UnreadCountResponse,
    MarkReadResponse,
    MarkAllReadResponse,
    DeleteNotificationResponse
)
from app.services.user.notification_history_service import NotificationHistoryService
from app.utils.auth import get_customer_user

router = APIRouter()

@router.get("/categories/{category_id}/stores")
async def get_stores_by_category(
    category_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_customer_user),
    chain_id: Optional[int] = Query(None, description="Filter by chain id"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=200)
):
    """
    Get stores that have at least one live (UTC) approved listing for products in the given category.
    """
    service = CustomerService(db)
    return await service.get_stores_by_category(
        category_id=category_id,
        chain_id=chain_id,
        skip=skip,
        limit=limit
    )

@router.get("/categories", response_model=List[CategoryResponse])
async def get_all_categories(
    chain_id: Optional[int] = Query(None, description="Filter by chain ID"),
    db: AsyncSession = Depends(get_db)
):
    """
    Get all product categories.
    Optionally filter by chain_id to see categories for a specific chain.
    
    Public endpoint - no authentication required.
    """
    service = CustomerService(db)
    return await service.get_all_categories(chain_id)


@router.get("/stores")
async def get_all_stores(
    chain_id: Optional[int] = Query(None, description="Filter by chain ID"),
    search: Optional[str] = Query(None, description="Search by store name or location"),
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(100, ge=1, le=100, description="Maximum number of records to return"),
    db: AsyncSession = Depends(get_db)
):
    """
    Get all stores with pagination.
    
    Returns list of stores without product details.
    Use /stores/{store_id}/products to get products for a specific store.
    
    Filters:
    - chain_id: Show stores from specific chain
    - search: Search by store name or location
    
    Public endpoint - no authentication required.
    """
    service = CustomerService(db)
    return await service.get_all_stores(
        chain_id=chain_id,
        search=search,
        skip=skip,
        limit=limit
    )


@router.get("/nearby-stores")
async def get_nearby_stores(
    current_user: dict = Depends(get_customer_user),
    radius_km: Optional[float] = Query(None, ge=0.1, le=100, description="Search radius in kilometers (default: 10km)"),
    chain_id: Optional[int] = Query(None, description="Filter by chain ID"),
    limit: int = Query(100, ge=1, le=100, description="Maximum number of stores to return"),
    db: AsyncSession = Depends(get_db)
):
    """
    Get stores within a specified radius from user's current location.
    
    Requires user authentication and user must have location data set.
    Returns stores sorted by distance (closest first).
    
    If radius_km is not provided, defaults to 10km.
    
    Authentication required.
    """
    service = CustomerService(db)
    user_id = int(current_user["sub"])
    # Set default radius to 10km if not provided
    if radius_km is None:
        radius_km = 10.0
    return await service.get_nearby_stores(
        user_id=user_id,
        radius_km=radius_km,
        chain_id=chain_id,
        limit=limit
    )


@router.get("/stores/{store_id}/products")
async def get_store_products(
    store_id: int,
    category_id: Optional[int] = Query(None, description="Filter by category"),
    search: Optional[str] = Query(None, description="Search by product name"),
    listing_type_filter: Optional[ListingTypeEnum] = Query(None, description="Filter by listing type"),
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(100, ge=1, le=100, description="Maximum number of records to return"),
    db: AsyncSession = Depends(get_db)
):
    """
    Get all approved products for a specific store.
    
    Shows products with current discounts and pricing.
    Only shows listings with APPROVED status and go_live_date <= today.
    
    Public endpoint - no authentication required.
    """
    service = CustomerService(db)
    return await service.get_store_live_products(
        store_id=store_id,
        category_id=category_id,
        search=search,
        listing_type_filter=listing_type_filter,
        skip=skip,
        limit=limit
    )


@router.get("/products")
async def get_all_products(
    category_id: Optional[int] = Query(None, description="Filter by category ID"),
    search: Optional[str] = Query(None, description="Search by product name, description, or barcode"),
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(100, ge=1, le=100, description="Maximum number of records to return"),
    db: AsyncSession = Depends(get_db)
):
    """
    Get all approved products from any store.
    
    Returns products that are:
    - Approved by superadmin (ProductStatusEnum.APPROVED)
    - Have approved listings (ListingStatusEnum.APPROVED)
    - Have go_live_date <= today
    
    Supports:
    - Pagination (skip, limit)
    - Search by product name, description, or barcode
    - Filter by category
    
    Public endpoint - no authentication required.
    """
    service = CustomerService(db)
    return await service.get_all_approved_products(
        category_id=category_id,
        search=search,
        skip=skip,
        limit=limit
    )


@router.get("/products/barcode/{barcode}")
async def get_product_by_barcode(
    barcode: str,
    store_id: Optional[int] = Query(None, description="Filter listings by specific store"),
    db: AsyncSession = Depends(get_db)
):
    """
    Get product details by barcode.
    
    Only returns products that are:
    - Approved by superadmin (ProductStatusEnum.APPROVED)
    - Have approved listings (ListingStatusEnum.APPROVED)
    - Have go_live_date <= today
    
    Returns:
    - Product details
    - List of stores where the product is available with listing details
    
    If store_id is provided, only returns listings from that store.
    
    Public endpoint - no authentication required.
    """
    service = CustomerService(db)
    return await service.get_product_by_barcode(
        barcode=barcode,
        store_id=store_id
    )


@router.get("/products/{product_id}")
async def get_product_details(
    product_id: int,
    store_id: Optional[int] = Query(None, description="Check availability in specific store"),
    db: AsyncSession = Depends(get_db)
):
    """
    Get detailed information about a specific product.
    
    Optionally provide store_id to see:
    - Current pricing at that store
    - Active discounts at that store
    - Availability
    
    Public endpoint - no authentication required.
    """
    service = CustomerService(db)
    return await service.get_product_details(
        product_id=product_id,
        store_id=store_id
    )


@router.post(
    "/addresses",
    response_model=UserAddressResponse,
    status_code=status.HTTP_201_CREATED
)
async def create_user_address(
    address_data: UserAddressCreateRequest,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Create a new address for the authenticated user.
    If marked as active (or the first address), any previous active address is deactivated.
    """
    service = UserAddressService(db)
    user_id = int(current_user["sub"])
    return await service.create_address(user_id, address_data)


@router.get("/addresses", response_model=List[UserAddressResponse])
async def list_user_addresses(
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Get all addresses for the authenticated user.
    The active address will be listed first.
    """
    service = UserAddressService(db)
    user_id = int(current_user["sub"])
    return await service.get_addresses(user_id)


@router.put("/addresses/{address_id}/activate", response_model=UserAddressResponse)
async def activate_user_address(
    address_id: int,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Set the specified address as the active address for the authenticated user.
    """
    service = UserAddressService(db)
    user_id = int(current_user["sub"])
    return await service.set_active_address(user_id, address_id)


@router.put("/addresses/{address_id}", response_model=UserAddressResponse)
async def update_user_address(
    address_id: int,
    address_data: UserAddressUpdateRequest,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Update an existing address for the authenticated user.
    You can change address details and optionally set it as the active address.
    """
    service = UserAddressService(db)
    user_id = int(current_user["sub"])
    return await service.update_address(user_id, address_id, address_data)


@router.delete(
    "/addresses/{address_id}",
    response_model=UserAddressDeleteResponse,
    status_code=status.HTTP_200_OK,
)
async def delete_user_address(
    address_id: int,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Delete an address belonging to the authenticated user.
    If the address was active, another address (if available) will be marked active.
    """
    service = UserAddressService(db)
    user_id = int(current_user["sub"])
    return await service.delete_address(user_id, address_id)


@router.post("/update-location")
async def update_user_location(
    latitude: float = Query(..., ge=-90, le=90, description="User's current latitude"),
    longitude: float = Query(..., ge=-180, le=180, description="User's current longitude"),
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Update user's current location (for travel mode).
    
    This endpoint:
    1. Updates the user's latitude and longitude
    2. If travel mode is enabled, checks if user is within radius of stores
       that have live listings for their favorite products
    3. Sends push notifications if conditions are met
    
    Should be called periodically (every 10-15 seconds) when travel mode is enabled.
    """
    from app.services.user.notification_service import check_travel_mode_notifications
    
    user_id = int(current_user["sub"])
    
    print(f"\n📍 BACKGROUND LOCATION UPDATE - User {user_id}")
    print(f"   📍 New Location: ({latitude}, {longitude})")
    
    # Update user location
    user_service = UserAuthService(db)
    update_data = UserAuthService.UpdateProfileRequest(latitude=latitude, longitude=longitude)
    result = await user_service.update_profile(user_id, update_data)
    
    # Check if travel mode is enabled
    user = result.get("user", {})
    is_travel_enabled = user.get("is_travel_enabled", False)
    
    if is_travel_enabled:
        print(f"   ✅ Travel Mode: ENABLED - Checking for nearby favorite products...")
        # Run notification check in background with a NEW session
        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")
    
    return {
        "message": "Location updated successfully",
        "user": result["user"]
    }


@router.get("/notifications", response_model=NotificationListResponse)
async def get_user_notifications(
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(100, ge=1, le=100, description="Maximum number of records to return"),
    unread_only: bool = Query(False, description="Filter to show only unread notifications"),
    notification_type: Optional[str] = Query(None, description="Filter by notification type (e.g., 'favorite_product_travel', 'favorite_product')"),
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Get user's notification history.
    
    Returns all notifications for the authenticated user, sorted by most recent first.
    Can filter by read status and notification type.
    
    Authentication required.
    """
    service = NotificationHistoryService(db)
    user_id = int(current_user["sub"])
    return await service.get_user_notifications(
        user_id=user_id,
        skip=skip,
        limit=limit,
        unread_only=unread_only,
        notification_type=notification_type
    )


@router.get("/notifications/unread-count", response_model=UnreadCountResponse)
async def get_unread_notification_count(
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Get count of unread notifications for the authenticated user.
    
    Returns the total number of unread notifications.
    
    Authentication required.
    """
    service = NotificationHistoryService(db)
    user_id = int(current_user["sub"])
    return await service.get_unread_count(user_id)


@router.put("/notifications/{notification_id}/read", response_model=MarkReadResponse)
async def mark_notification_as_read(
    notification_id: int,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Mark a specific notification as read.
    
    The notification must belong to the authenticated user.
    
    Authentication required.
    """
    service = NotificationHistoryService(db)
    user_id = int(current_user["sub"])
    return await service.mark_notification_as_read(user_id, notification_id)


@router.put("/notifications/mark-all-read", response_model=MarkAllReadResponse)
async def mark_all_notifications_as_read(
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Mark all notifications as read for the authenticated user.
    
    Returns the count of notifications that were marked as read.
    
    Authentication required.
    """
    service = NotificationHistoryService(db)
    user_id = int(current_user["sub"])
    return await service.mark_all_as_read(user_id)


@router.delete("/notifications/{notification_id}", response_model=DeleteNotificationResponse)
async def delete_notification(
    notification_id: int,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Delete a specific notification.
    
    The notification must belong to the authenticated user.
    
    Authentication required.
    """
    service = NotificationHistoryService(db)
    user_id = int(current_user["sub"])
    return await service.delete_notification(user_id, notification_id)

