from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import Annotated, Optional, List
from pydantic import BaseModel

from app.database.database import get_db
from app.schemas.staff.staff_auth_schemas import (
    StaffLoginBaseModel,
    StaffRegisterBaseModel,
    AdminRegisterRequest,
)
from app.schemas.staff.staff_schemas import (
    StaffUpdateRequest,
    StaffPasswordChangeRequest,
    StaffListResponse,
    StoreUnassignRequest,
    AdminListResponse,
)
from app.services.staff.staff_auth import StaffAuthService
from app.utils.auth import (
    get_current_user,
    get_admin_user,
    get_current_chain_id,
    get_optional_admin_user,
    get_superadmin_user,
)
from app.enums.enums import RoleTypeEnum

router = APIRouter()
db_dependency = Annotated[AsyncSession, Depends(get_db)]


class StoreAssignmentRequest(BaseModel):
    staff_id: int
    store_id: int


@router.post("/login")
async def login(login_request: StaffLoginBaseModel, db: db_dependency):
    """
    Staff login endpoint for EMPLOYEE and MANAGER (mobile app only).
    Admins cannot login through this endpoint.
    """
    return await StaffAuthService(db).login_staff(login_request)


@router.post("/admin/login")
async def admin_login(login_request: StaffLoginBaseModel, db: db_dependency):
    """
    Admin login endpoint (web/admin panel only).
    Only ADMIN and SUPERADMIN roles can login through this endpoint.
    Employees and managers should use the /login endpoint.
    """
    return await StaffAuthService(db).login_admin(login_request)


@router.post(
    "/register",
    openapi_extra={"security": [{"JWT Authentication": []}]},
)
async def register(
    register_request: StaffRegisterBaseModel,
    db: db_dependency,
    admin_user: Optional[dict] = Depends(get_optional_admin_user)
):
    """
    Register a new staff member.
    
    **Registration Rules:**
    - **Creating ADMIN without JWT**: chain_id must be provided in request body (for initial setup only)
    - **Creating ADMIN with admin JWT**: chain_id is automatically taken from admin's token
    - **Creating EMPLOYEE or MANAGER**: Requires admin JWT, chain_id automatically taken from admin's token
    """
    # Get chain_id from admin user if available
    chain_id: Optional[int] = None
    if admin_user:
        chain_id = admin_user.get("chain_id")
        if chain_id is not None:
            chain_id = int(chain_id)
    
    # Determine chain_id based on scenario
    if register_request.user_type == RoleTypeEnum.SUPERADMIN:
        if admin_user and admin_user.get("role_type") != RoleTypeEnum.SUPERADMIN:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Only superadmin can create another superadmin."
            )
        chain_context = None
    elif register_request.user_type == RoleTypeEnum.ADMIN:
        if admin_user:
            if not chain_id:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="Chain ID not found in admin token"
                )
            chain_context = chain_id
        else:
            if not register_request.chain_id:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                detail="chain_id is required when creating admin without authentication. This is for initial admin setup only."
                )
            chain_context = int(register_request.chain_id)
    else:
        if not admin_user:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Admin privileges required to create employees or managers. Please provide admin JWT token."
            )
        if not chain_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Chain ID not found in admin token"
            )
        chain_context = chain_id
    
    try:
        return await StaffAuthService(db).register_staff(register_request, chain_context)
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Failed to register staff: {exc}"
        ) from exc


@router.post("/assign-store")
async def assign_staff_to_store(
    assignment_data: StoreAssignmentRequest,
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user)
):
    """Assign a store to a staff member (Admin only)"""
    return await StaffAuthService(db).assign_staff_to_store(
        assignment_data.staff_id, 
        assignment_data.store_id
    )


@router.get("/my-stores")
async def get_my_assigned_stores(
    db: db_dependency,
    current_user: dict = Depends(get_current_user)
):
    """Get stores assigned to the current staff member"""
    return await StaffAuthService(db).get_my_assigned_stores(int(current_user["sub"]))


@router.get("/all", response_model=StaffListResponse)
async def get_all_staff(
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id),
    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")
):
    """Get all staff members for the chain (Admin only)"""
    service = StaffAuthService(db)
    staff_list = await service.get_all_staff(chain_id, skip, limit)
    
    return StaffListResponse(
        staff=staff_list,
        total=len(staff_list),
        skip=skip,
        limit=limit
    )


@router.post("/unassign-store")
async def unassign_staff_from_store(
    unassign_data: StoreUnassignRequest,
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user)
):
    """Unassign a store from a staff member (Admin only)"""
    service = StaffAuthService(db)
    return await service.unassign_staff_from_store(
        unassign_data.staff_id,
        unassign_data.store_id
    )


@router.put("/{staff_id}", response_model=dict)
async def update_staff(
    staff_id: int,
    update_data: StaffUpdateRequest,
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id)
):
    """Update staff details (Admin only). Admin can only update staff in their chain."""
    service = StaffAuthService(db)
    
    # Verify staff belongs to admin's chain
    from sqlalchemy import select, and_
    from app.models.staff.staff_model import Staff
    stmt = select(Staff).where(
        and_(
            Staff.id == staff_id,
            Staff.chain_id == chain_id,
            Staff.is_deleted == False
        )
    )
    result = await db.execute(stmt)
    staff = result.scalar_one_or_none()
    
    if not staff:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Staff not found, deleted, or does not belong to your chain"
        )
    
    # Convert Pydantic model to dict, excluding None values
    update_dict = update_data.dict(exclude_unset=True)
    updated_staff = await service.update_staff(staff_id, update_dict)
    
    return {
        "message": "Staff updated successfully",
        "staff": {
            "id": updated_staff.id,
            "username": updated_staff.username,
            "email": updated_staff.email,
            "role_type": updated_staff.role_type,
            "chain_id": updated_staff.chain_id,
            "full_name": updated_staff.full_name,
            "phone_number": updated_staff.phone_number,
            "profile_image": updated_staff.profile_image
        }
    }


@router.put("/{staff_id}/change-password")
async def change_staff_password(
    staff_id: int,
    password_data: StaffPasswordChangeRequest,
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id)
):
    """
    Change staff password (Admin only). 
    
    Note: Passwords are hashed and cannot be viewed. This allows admin to reset a staff member's password.
    Admin can only change passwords for staff in their chain.
    """
    service = StaffAuthService(db)
    
    # Verify staff belongs to admin's chain
    from sqlalchemy import select, and_
    from app.models.staff.staff_model import Staff
    stmt = select(Staff).where(
        and_(
            Staff.id == staff_id,
            Staff.chain_id == chain_id,
            Staff.is_deleted == False
        )
    )
    result = await db.execute(stmt)
    staff = result.scalar_one_or_none()
    
    if not staff:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Staff not found, deleted, or does not belong to your chain"
        )
    
    return await service.change_staff_password(staff_id, password_data.new_password)


@router.delete("/{staff_id}", status_code=status.HTTP_200_OK)
async def delete_staff(
    staff_id: int,
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id)
):
    """
    Delete a staff member (Admin only). This is a soft delete.
    
    Cannot delete if:
    - Staff has active product listings (as employee, manager, or staff)
    - Staff has manager discount records
    
    Store assignments will be automatically removed.
    Admin can only delete staff in their chain.
    """
    service = StaffAuthService(db)
    await service.delete_staff(staff_id, chain_id)
    return {
        "message": "Staff deleted successfully",
        "status": True,
        "staff_id": staff_id
    }


@router.post("/register-admin")
async def register_admin(
    admin_request: AdminRegisterRequest,
    db: db_dependency,
    superadmin_user: dict = Depends(get_superadmin_user)
):
    """Register a new admin for a chain (Superadmin only)"""
    from app.models.staff.store_model import Chain
    
    # Validate that chain exists
    chain_stmt = select(Chain).where(Chain.chain_id == admin_request.chain_id)
    chain_result = await db.execute(chain_stmt)
    chain = chain_result.scalar_one_or_none()
    
    if not chain:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Chain with ID {admin_request.chain_id} not found"
        )
    
    # Create StaffRegisterBaseModel with ADMIN role type
    register_request = StaffRegisterBaseModel(
        username=admin_request.username,
        email=admin_request.email,
        password=admin_request.password,
        user_type=RoleTypeEnum.ADMIN,
        chain_id=admin_request.chain_id,
        full_name=admin_request.full_name,
        phone_number=admin_request.phone_number,
        profile_image=admin_request.profile_image
    )
    
    # Register the admin
    try:
        return await StaffAuthService(db).register_staff(register_request, admin_request.chain_id)
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Failed to register admin: {str(exc)}"
        ) from exc


@router.get("/admins", response_model=AdminListResponse)
async def get_all_admins_with_chain(
    db: db_dependency,
    superadmin_user: dict = Depends(get_superadmin_user),
    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")
):
    """Get all admins with their chain information (Superadmin only)"""
    service = StaffAuthService(db)
    result = await service.get_all_admins_with_chain(skip, limit)
    
    return AdminListResponse(
        admins=result["admins"],
        total=result["total"],
        skip=skip,
        limit=limit
    )


@router.delete("/admins/{admin_id}", status_code=status.HTTP_200_OK)
async def delete_admin(
    admin_id: int,
    db: db_dependency,
    superadmin_user: dict = Depends(get_superadmin_user)
):
    """
    Delete an admin by superadmin (Superadmin only). This is a soft delete.
    
    Superadmin can delete admins from any chain.
    
    Cannot delete if:
    - Admin has active product listings (as employee, manager, or staff)
    - Admin has manager discount records
    
    Store assignments will be automatically removed.
    """
    service = StaffAuthService(db)
    await service.delete_admin_by_superadmin(admin_id)
    return {
        "message": "Admin deleted successfully",
        "status": True,
        "admin_id": admin_id
    }
