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

from app.database.database import get_db
from app.services.listing.product_service import ProductService
from app.utils.auth import (
    get_admin_user,
    get_current_chain_id,
    get_current_user,
    get_superadmin_user,
)
from app.enums.enums import ProductStatusEnum
from app.schemas.listing.product_schemas import (
    Product,
    ProductCreate,
    ProductUpdate,
    ProductCategory,
    ProductCategoryCreate,
    ProductCategoryUpdate,
    StoreProductInventory,
    ProductSearchParams,
    MultiStoreInventoryCreate,
    MultiStoreInventoryResponse,
    EmployeeProductWithStore,
    ManagerProductWithStores,
)

router = APIRouter()


# Product Category Endpoints
@router.post("/categories", response_model=ProductCategory, status_code=status.HTTP_201_CREATED)
async def create_category(
    category_data: ProductCategoryCreate,
    db: AsyncSession = Depends(get_db),
    superadmin_user: dict = Depends(get_superadmin_user)
):
    """Create a new product category (Superadmin only)"""
    service = ProductService(db)
    return await service.create_category(category_data, int(superadmin_user["sub"]))


@router.get("/categories", response_model=List[ProductCategory])
async def get_categories(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
):
    """Get all product categories (includes taxes for admin)"""
    service = ProductService(db)
    return await service.get_categories(skip=skip, limit=limit, include_taxes=True)


@router.get("/categories/{category_id}", response_model=ProductCategory)
async def get_category(
    category_id: int,
    db: AsyncSession = Depends(get_db),
):
    """Get a product category by ID (includes taxes for admin)"""
    service = ProductService(db)
    category = await service.get_category_by_id(category_id, include_taxes=True)
    if not category:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Category not found"
        )
    return category


@router.put("/categories/{category_id}", response_model=ProductCategory)
async def update_category(
    category_id: int,
    category_data: ProductCategoryUpdate,
    db: AsyncSession = Depends(get_db),
    superadmin_user: dict = Depends(get_superadmin_user)
):
    """Update a product category (Superadmin only)"""
    service = ProductService(db)
    category = await service.update_category(category_id, category_data, int(superadmin_user["sub"]))
    if not category:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Category not found"
        )
    return category


@router.delete("/categories/{category_id}", status_code=status.HTTP_200_OK)
async def delete_category(
    category_id: int,
    db: AsyncSession = Depends(get_db),
    superadmin_user: dict = Depends(get_superadmin_user)
):
    """Delete a product category (Superadmin only). Cannot delete if products are assigned to it."""
    service = ProductService(db)
    await service.delete_category(category_id, int(superadmin_user["sub"]))
    return {"message": "Category deleted successfully", "category_id": category_id}


# Product Endpoints
@router.post("/", response_model=Product, status_code=status.HTTP_201_CREATED)
async def create_product(
    product_data: ProductCreate,
    db: AsyncSession = Depends(get_db),
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id)
):
    """Create a new product (Admin only, submitted for approval)"""
    service = ProductService(db)
    return await service.create_product(product_data, chain_id)


@router.post(
    "/superadmin-create",
    response_model=Product,
    status_code=status.HTTP_201_CREATED,
    summary="Create a new product (Superadmin only, immediately approved)"
)
async def create_product_superadmin(
    product_data: ProductCreate,
    db: AsyncSession = Depends(get_db),
    superadmin_user: dict = Depends(get_superadmin_user),
):
    """
    Create a new product directly as Superadmin.

    - Product is created as APPROVED immediately
    - Not tied to any specific chain (global product)
    - Barcode must be unique across all products
    """
    service = ProductService(db)
    return await service.create_product_as_superadmin(product_data)


@router.get("/suggestions", response_model=List[Product])
async def get_product_suggestions(
    search: Optional[str] = Query(None, description="Search in product name, description, or barcode"),
    limit: int = Query(20, ge=1, le=100, description="Number of products to return"),
    db: AsyncSession = Depends(get_db)
):
    """
    Get approved products for suggestions (used when creating products).
    
    Returns only APPROVED products with optional search.
    Useful for providing product suggestions to admins during product creation.
    """
    service = ProductService(db)
    return await service.get_approved_products_for_suggestions(search_term=search, limit=limit)


@router.get("/", response_model=List[Product])
async def get_products(
    search_term: Optional[str] = Query(None, description="Search in product name, description, or barcode"),
    category_id: Optional[int] = Query(None, description="Filter by category ID"),
    min_price: Optional[float] = Query(None, ge=0, description="Minimum price filter"),
    max_price: Optional[float] = Query(None, ge=0, description="Maximum price filter"),
    status_filter: Optional[ProductStatusEnum] = Query(None, description="Filter by product approval status"),
    limit: int = Query(20, ge=1, le=100, description="Number of products to return"),
    offset: int = Query(0, ge=0, description="Number of products to skip"),
    admin_user: dict = Depends(get_admin_user),
    db: AsyncSession = Depends(get_db)
):
    """Get products with optional filtering and search"""
    service = ProductService(db)
    
    search_params = ProductSearchParams(
        search_term=search_term,
        category_id=category_id,
        status=status_filter,
        min_price=min_price,
        max_price=max_price,
        limit=limit,
        offset=offset
    )
    
    chain_id = int(admin_user["chain_id"])
    return await service.get_products_for_chain(chain_id, search_params=search_params)


@router.get(
    "/submissions",
    response_model=List[Product],
    summary="List products submitted by the current chain (all statuses)"
)
async def get_chain_submissions(
    status_filter: Optional[ProductStatusEnum] = Query(None, description="Filter by product approval status"),
    limit: int = Query(20, ge=1, le=100, description="Number of products to return"),
    offset: int = Query(0, ge=0, description="Number of products to skip"),
    chain_id: int = Depends(get_current_chain_id),
    admin_user: dict = Depends(get_admin_user),
    db: AsyncSession = Depends(get_db)
):
    service = ProductService(db)
    return await service.get_products_submitted_by_chain(
        chain_id,
        status_filter=status_filter,
        limit=limit,
        offset=offset,
    )


@router.get(
    "/approval/pending",
    response_model=List[Product],
    summary="List pending products awaiting superadmin approval"
)
async def list_pending_products(
    search_term: Optional[str] = Query(None, description="Search in product name, description, or barcode"),
    category_id: Optional[int] = Query(None, description="Filter by category ID"),
    min_price: Optional[float] = Query(None, ge=0, description="Minimum price filter"),
    max_price: Optional[float] = Query(None, ge=0, description="Maximum price filter"),
    limit: int = Query(20, ge=1, le=100, description="Number of products to return"),
    offset: int = Query(0, ge=0, description="Number of products to skip"),
    superadmin_user: dict = Depends(get_superadmin_user),
    db: AsyncSession = Depends(get_db)
):
    service = ProductService(db)
    search_params = ProductSearchParams(
        search_term=search_term,
        category_id=category_id,
        min_price=min_price,
        max_price=max_price,
        limit=limit,
        offset=offset
    )
    return await service.get_products_global(
        search_params=search_params,
        status_filter=ProductStatusEnum.PENDING
    )


@router.get(
    "/approval/approved",
    response_model=List[Product],
    summary="List all approved products (Superadmin only)"
)
async def list_approved_products(
    search_term: Optional[str] = Query(None, description="Search in product name, description, or barcode"),
    category_id: Optional[int] = Query(None, description="Filter by category ID"),
    min_price: Optional[float] = Query(None, ge=0, description="Minimum price filter"),
    max_price: Optional[float] = Query(None, ge=0, description="Maximum price filter"),
    limit: int = Query(20, ge=1, le=100, description="Number of products to return"),
    offset: int = Query(0, ge=0, description="Number of products to skip"),
    include_taxes: bool = Query(True, description="Include taxes in response (default: true)"),
    superadmin_user: dict = Depends(get_superadmin_user),
    db: AsyncSession = Depends(get_db)
):
    """
    Get all approved products (Superadmin only).
    
    Returns products that have been approved by superadmin.
    Includes full product details with optional taxes for editing purposes.
    
    Use this endpoint to view and manage approved products before editing them.
    """
    service = ProductService(db)
    search_params = ProductSearchParams(
        search_term=search_term,
        category_id=category_id,
        min_price=min_price,
        max_price=max_price,
        limit=limit,
        offset=offset
    )
    return await service.get_products_global(
        search_params=search_params,
        status_filter=ProductStatusEnum.APPROVED,
        include_taxes=include_taxes
    )


@router.post(
    "/{product_id}/approve",
    response_model=Product,
    summary="Approve a pending product (superadmin only)"
)
async def approve_product(
    product_id: int,
    superadmin_user: dict = Depends(get_superadmin_user),
    db: AsyncSession = Depends(get_db)
):
    service = ProductService(db)
    return await service.approve_product(product_id)


@router.post(
    "/{product_id}/reject",
    response_model=Product,
    summary="Reject a product (superadmin only)"
)
async def reject_product(
    product_id: int,
    superadmin_user: dict = Depends(get_superadmin_user),
    db: AsyncSession = Depends(get_db)
):
    service = ProductService(db)
    return await service.reject_product(product_id)


@router.delete(
    "/{product_id}",
    response_model=Product,
    summary="Soft delete a product (Superadmin only)"
)
async def delete_product(
    product_id: int,
    db: AsyncSession = Depends(get_db),
    superadmin_user: dict = Depends(get_superadmin_user)
):
    """
    Soft delete a product (Superadmin only).
    
    - Sets is_deleted = True and deleted_at = current timestamp
    - Product will be hidden from all product listing APIs
    - Existing listings and orders will still work (product data preserved)
    - Product can be restored by setting is_deleted = False (if needed in future)
    """
    service = ProductService(db)
    return await service.soft_delete_product(product_id)


@router.get("/employee-product-database", response_model=List[EmployeeProductWithStore])
async def get_employee_product_database(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    search: Optional[str] = Query(None, description="Search by product name, description, or barcode"),
    category_id: Optional[List[int]] = Query(None, description="Filter by category IDs (can pass multiple)"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """Get products with store information for employee's assigned store only"""
    from app.services.staff.staff_auth import StaffAuthService
    
    # Get employee's assigned stores
    staff_service = StaffAuthService(db)
    assigned_stores = await staff_service.get_my_assigned_stores(int(current_user["sub"]))
    
    if not assigned_stores["assigned_stores"]:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="No store assigned to this employee"
        )
    
    # Get the first (and only) store for employees
    employee_store_id = assigned_stores["assigned_stores"][0]["store_id"]
    
    service = ProductService(db)
    return await service.get_employee_products_with_store(employee_store_id, skip=skip, limit=limit, search=search, category_id=category_id)


@router.get("/manager-product-database", response_model=List[ManagerProductWithStores])
async def get_manager_product_database(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    search: Optional[str] = Query(None, description="Search by product name, description, or barcode"),
    category_id: Optional[List[int]] = Query(None, description="Filter by category IDs (can pass multiple)"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """Get products with store information for all manager's assigned stores"""
    from app.services.staff.staff_auth import StaffAuthService
    from app.enums.enums import RoleTypeEnum
    
    # Verify user is manager or admin
    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 access this endpoint"
        )
    
    # Get manager's assigned stores
    staff_service = StaffAuthService(db)
    assigned_stores = await staff_service.get_my_assigned_stores(int(current_user["sub"]))
    
    if not assigned_stores["assigned_stores"]:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="No stores assigned to this manager"
        )
    
    # Get all store IDs for the manager
    manager_store_ids = [store["store_id"] for store in assigned_stores["assigned_stores"]]
    
    service = ProductService(db)
    return await service.get_manager_products_with_stores(manager_store_ids, skip=skip, limit=limit, search=search, category_id=category_id)


@router.get("/{product_id}", response_model=Product)
async def get_product(
    product_id: int,
    db: AsyncSession = Depends(get_db)
):
    """Get a product by ID (includes taxes for admin)"""
    service = ProductService(db)
    product = await service.get_product_by_id(product_id, include_taxes=True)
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    return product


@router.delete("/{product_id}/remove-from-chain", status_code=status.HTTP_200_OK)
async def remove_product_from_chain(
    product_id: int,
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id),
    db: AsyncSession = Depends(get_db)
):
    """
    Remove a product from your chain (Admin only).
    
    - If product is APPROVED: Only removes the chain association (product remains in database for other chains)
    - If product is PENDING and submitted by your chain: Cannot remove (must wait for approval/rejection)
    - If product is PENDING and submitted by another chain: Removes association if exists
    
    The product will no longer appear in your chain's product list, but other chains can still use it.
    """
    service = ProductService(db)
    return await service.remove_product_from_chain(product_id, chain_id)


@router.delete("/{product_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_product(
    product_id: int,
    db: AsyncSession = Depends(get_db),
    superadmin_user: dict = Depends(get_superadmin_user)
):
    """Delete a product (Superadmin only)"""
    service = ProductService(db)
    success = await service.delete_product(product_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    return None


@router.get("/barcode/{barcode}", response_model=Product)
async def get_product_by_barcode(
    barcode: str,
    db: AsyncSession = Depends(get_db)
):
    """Get a product by barcode"""
    service = ProductService(db)
    product = await service.get_product_by_barcode(barcode)
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    return product


@router.put("/{product_id}", response_model=Product)
async def update_product(
    product_id: int,
    product_data: ProductUpdate,
    db: AsyncSession = Depends(get_db),
    superadmin_user: dict = Depends(get_superadmin_user)
):
    """
    Update a product (Superadmin only).
    
    Allows editing any product field including:
    - Product name, description, barcode, image
    - Category, base price
    - Taxes (state-based tax configuration)
    
    Can update products in any status (PENDING, APPROVED, REJECTED).
    When updating taxes, existing taxes are deleted and replaced with the new ones.
    """
    service = ProductService(db)
    product = await service.update_product(product_id, product_data)
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    return product






# Inventory Endpoints
@router.post("/inventory/multi-store", response_model=MultiStoreInventoryResponse, status_code=status.HTTP_201_CREATED)
async def create_multi_store_inventory(
    inventory_data: MultiStoreInventoryCreate,
    db: AsyncSession = Depends(get_db),
    admin_user: dict = Depends(get_admin_user)
):
    """Create inventory records for a product in multiple stores (Admin only)"""
    service = ProductService(db)
    return await service.create_multi_store_inventory(inventory_data)


@router.get("/inventory/store/{store_id}", response_model=List[StoreProductInventory])
async def get_store_inventory(
    store_id: int,
    db: AsyncSession = Depends(get_db)
):
    """Get all inventory records for a store"""
    service = ProductService(db)
    return await service.get_inventory_by_store(store_id)


@router.get("/inventory/product/{product_id}", response_model=List[StoreProductInventory])
async def get_product_inventory(
    product_id: int,
    db: AsyncSession = Depends(get_db)
):
    """Get all inventory records for a product"""
    service = ProductService(db)
    return await service.get_inventory_by_product(product_id)
