from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi.security import HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.database import get_db
from app.services.listing.listing_service import ListingService
from app.schemas.listing.product_schemas import (
    ProductListing,
    ProductListingCreate,
    ProductListingUpdate,
    ManagerReviewRequest,
    PreviousDiscountSuggestion,
    ManagerListingCreate,
    EmployeeDetailsUpdate,
    EmployeeListingUpdate,
    ManagerListingUpdate,
    ListingStatusUpdate
)
from app.enums.enums import ListingStatusEnum, ListingTypeEnum, RoleTypeEnum
from app.utils.auth import get_current_user, get_employee_user, get_manager_user, get_current_chain_id

router = APIRouter()
security = HTTPBearer()


# Employee endpoints
@router.post("/", status_code=status.HTTP_201_CREATED)
async def create_listing(
    listing_data: ProductListingCreate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_employee_user)
):
    """Create a new product listing (Employee only)"""
    if current_user["role_type"] != RoleTypeEnum.EMPLOYEE:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only employees can create listings"
        )
    
    service = ListingService(db)
    return await service.create_listing(listing_data, int(current_user["sub"]))


@router.get("/my-listings")
async def get_my_listings(
    status_filter: Optional[ListingStatusEnum] = Query(None, description="Filter by listing status"),
    listing_type_filter: Optional[ListingTypeEnum] = Query(None, description="Filter by listing type"),
    category_id: Optional[List[int]] = Query(None, description="Filter by product categories (can pass multiple)"),
    search: Optional[str] = Query(None, description="Search by product name, description, or category"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_employee_user)
):
    """Get current employee's listings"""
    service = ListingService(db)
    # Get employee's assigned store
    store_id = await service.get_employee_assigned_store(int(current_user["sub"]))
    return await service.get_listings_by_store(store_id, status_filter, listing_type_filter, category_id, search, skip, limit, int(current_user["sub"]))


@router.get("/live")
async def get_live_listings(
    listing_type_filter: Optional[ListingTypeEnum] = Query(None, description="Filter by listing type"),
    category_id: Optional[List[int]] = Query(None, description="Filter by product categories (can pass multiple)"),
    store_id: Optional[List[int]] = Query(None, description="Filter by stores (can pass multiple)"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Get live/approved listings for manager (Manager only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can view live listings"
        )
    
    service = ListingService(db)
    return await service.get_live_listings_for_manager(int(current_user["sub"]), listing_type_filter, category_id, store_id, skip, limit)


@router.get("/manager/all")
async def get_all_manager_listings(
    status_filter: Optional[ListingStatusEnum] = Query(None, description="Filter by listing status"),
    listing_type_filter: Optional[ListingTypeEnum] = Query(None, description="Filter by listing type"),
    category_id: Optional[List[int]] = Query(None, description="Filter by product categories (can pass multiple)"),
    search: Optional[str] = Query(None, description="Search by product name, description, or category"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Get all listings for manager with optional status and listing type filters (Manager only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can view all listings"
        )
    
    service = ListingService(db)
    return await service.get_all_listings_for_manager(int(current_user["sub"]), status_filter, listing_type_filter, category_id, search, skip, limit)


@router.get("/pending-discount")
async def get_pending_manager_discount_listings(
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Get listings that need manager to add discount (Manager only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can view pending discount listings"
        )
    
    service = ListingService(db)
    return await service.get_pending_manager_discount_listings(int(current_user["sub"]))


@router.get("/pending-employee-tasks")
async def get_pending_employee_tasks(
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_employee_user)
):
    """Get listings that need employee to add details (Employee only)"""
    if current_user["role_type"] != RoleTypeEnum.EMPLOYEE:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only employees can view pending tasks"
        )
    
    service = ListingService(db)
    return await service.get_pending_employee_tasks(int(current_user["sub"]))


@router.get("/{listing_id}")
async def get_listing(
    listing_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """Get a specific listing by ID"""
    service = ListingService(db)
    listing = await service.get_listing_by_id(listing_id)
    
    if not listing:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Listing not found"
        )
    
    return listing


@router.post("/{listing_id}/submit", response_model=ProductListing)
async def submit_for_review(
    listing_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_employee_user)
):
    """Submit listing for manager review (Employee only)"""
    if current_user["role_type"] != RoleTypeEnum.EMPLOYEE:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only employees can submit listings for review"
        )
    
    service = ListingService(db)
    return await service.submit_for_manager_review(listing_id, current_user["id"])


@router.delete("/{listing_id}", status_code=status.HTTP_200_OK)
async def delete_listing(
    listing_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_employee_user)
):
    """Delete a draft or pending manager review listing (Employee only)"""
    if current_user["role_type"] != RoleTypeEnum.EMPLOYEE:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only employees can delete listings"
        )
    
    service = ListingService(db)
    await service.delete_listing(listing_id, int(current_user["sub"]))
    
    return {
        "message": "Listing deleted successfully",
        "status": True,
        "listing_id": listing_id
    }


@router.patch("/{listing_id}/status", response_model=ProductListing)
async def update_listing_status(
    listing_id: int,
    status_update: ListingStatusUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """Update listing status (pause, resume, cancel) - Available for employees and managers"""
    service = ListingService(db)
    return await service.update_listing_status(
        listing_id, 
        status_update, 
        int(current_user["sub"]),
        current_user["role_type"]
    )


@router.put("/{listing_id}")
async def update_employee_listing(
    listing_id: int,
    update_data: EmployeeListingUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_employee_user)
):
    """Employee updates their own listing - can change listing type and related fields (Employee only - DRAFT or PENDING_MANAGER_REVIEW status)"""
    if current_user["role_type"] != RoleTypeEnum.EMPLOYEE:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only employees can update listings"
        )
    
    service = ListingService(db)
    return await service.update_employee_listing(listing_id, update_data, int(current_user["sub"]))


@router.get("/suggestions/discount/{product_id}", response_model=Optional[PreviousDiscountSuggestion])
async def get_discount_suggestion(
    product_id: int,
    store_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Get previous discount suggestion for a product (Manager only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can view discount suggestions"
        )
    
    service = ListingService(db)
    return await service.get_previous_discount_suggestion(product_id, store_id)


@router.get("/suggestions/auto-apply/{product_id}")
async def check_auto_apply_availability(
    product_id: int,
    store_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Check if auto-apply discount is available for a product (Manager only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can view auto-apply suggestions"
        )
    
    service = ListingService(db)
    return await service.check_auto_apply_availability(product_id, store_id)


# Manager endpoints
@router.get("/pending/review")
async def get_pending_listings(
    listing_type_filter: Optional[ListingTypeEnum] = Query(None, description="Filter by listing type"),
    category_id: Optional[List[int]] = Query(None, description="Filter by product categories (can pass multiple)"),
    store_id: Optional[List[int]] = Query(None, description="Filter by stores (can pass multiple)"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Get pending listings for manager review - includes PENDING_MANAGER_REVIEW and PENDING_MANAGER_DISCOUNT (Manager only)"""
    if current_user["role_type"] != RoleTypeEnum.MANAGER:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers can view pending listings"
        )
    
    service = ListingService(db)
    return await service.get_pending_listings_for_manager(int(current_user["sub"]), listing_type_filter, category_id, store_id, skip, limit)




@router.post("/review")
async def manager_review_listing(
    review_data: ManagerReviewRequest,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Manager reviews and approves a listing (Manager only)"""
    if current_user["role_type"] != RoleTypeEnum.MANAGER:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers can review listings"
        )
    
    service = ListingService(db)
    return await service.manager_review_listing(review_data, int(current_user["sub"]))


@router.put("/manager/{listing_id}")
async def update_manager_listing(
    listing_id: int,
    update_data: ManagerListingUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Manager updates a listing - can change listing type and related fields. Status changes to PENDING_MANAGER_DISCOUNT after update. Works with PENDING_MANAGER_REVIEW, PENDING_MANAGER_DISCOUNT, APPROVED, ACTIVE, and PAUSED listings (Manager/Admin only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can update listings"
        )
    
    service = ListingService(db)
    return await service.update_manager_listing(listing_id, update_data, int(current_user["sub"]))


@router.delete("/manager/{listing_id}", status_code=status.HTTP_200_OK)
async def delete_manager_listing(
    listing_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Manager deletes a listing. Works with DRAFT, PENDING_MANAGER_REVIEW, APPROVED, and PAUSED listings (Manager/Admin only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can delete listings"
        )
    
    service = ListingService(db)
    await service.delete_manager_listing(listing_id, int(current_user["sub"]))
    
    return {
        "message": "Listing deleted successfully",
        "status": True,
        "listing_id": listing_id
    }


@router.post("/manager-create", status_code=status.HTTP_201_CREATED)
async def create_manager_listing(
    listing_data: ManagerListingCreate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_manager_user)
):
    """Create listing requests initiated by manager (Manager only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can create manager-initiated listings"
        )
    
    service = ListingService(db)
    return await service.create_manager_listing(listing_data, int(current_user["sub"]))




@router.put("/{listing_id}/employee-details")
async def update_employee_details(
    listing_id: int,
    details_data: EmployeeDetailsUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_employee_user)
):
    """Employee adds quantity and dates to manager-initiated listing (Employee only)"""
    if current_user["role_type"] != RoleTypeEnum.EMPLOYEE:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only employees can update listing details"
        )
    
    service = ListingService(db)
    return await service.update_employee_details(listing_id, details_data, int(current_user["sub"]))




# Store-specific endpoints
@router.get("/store/{store_id}/active", response_model=List[ProductListing])
async def get_active_listings(
    store_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """Get active listings for a store (Public endpoint for customers)"""
    service = ListingService(db)
    return await service.get_active_listings_for_store(store_id)


@router.get("/store/{store_id}/all", response_model=List[ProductListing])
async def get_all_store_listings(
    store_id: int,
    status_filter: Optional[ListingStatusEnum] = Query(None, description="Filter by listing status"),
    listing_type_filter: Optional[ListingTypeEnum] = Query(None, description="Filter by listing type"),
    category_id: Optional[List[int]] = Query(None, description="Filter by product categories (can pass multiple)"),
    search: Optional[str] = Query(None, description="Search by product name, description, or category"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """Get all listings for a store (Manager/Admin only)"""
    if current_user["role_type"] not in [RoleTypeEnum.MANAGER, RoleTypeEnum.ADMIN]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only managers and admins can view all store listings"
        )
    
    service = ListingService(db)
    return await service.get_listings_by_store(store_id, status_filter, listing_type_filter, category_id, search, skip, limit)


# Utility endpoints
@router.get("/{listing_id}/discount/current")
async def get_current_discount(
    listing_id: int,
    current_date: Optional[str] = Query(None, description="Date in YYYY-MM-DD format"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """Get current discount percentage for a listing"""
    from datetime import datetime
    
    service = ListingService(db)
    
    if current_date:
        try:
            parsed_date = datetime.strptime(current_date, "%Y-%m-%d").date()
        except ValueError:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid date format. Use YYYY-MM-DD"
            )
    else:
        parsed_date = None
    
    discount = await service.calculate_current_discount(listing_id, parsed_date)
    
    return {
        "listing_id": listing_id,
        "current_discount_percent": discount,
        "date": parsed_date or service.calculate_current_discount.__defaults__[0]
    }
