from typing import List, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func

from app.database import get_db
from app.core.permissions import UserRole
from app.models.user import User
from app.models.tenant import Tenant
from app.models.device import Device
from app.models.alert import AlertLog
from app.schemas.tenant import TenantCreate, TenantUpdate, TenantResponse, TenantStats
from app.schemas.common import PaginatedResponse, MessageResponse
from app.api.deps import get_current_user, require_super_admin

router = APIRouter()


@router.get("", response_model=PaginatedResponse[TenantResponse])
async def list_tenants(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    is_active: Optional[bool] = None,
    current_user: User = Depends(require_super_admin()),
    db: AsyncSession = Depends(get_db)
):
    """قائمة العملاء (Super Admin فقط)"""
    query = select(Tenant)
    
    if is_active is not None:
        query = query.where(Tenant.is_active == is_active)
    
    # Count total
    count_query = select(func.count()).select_from(query.subquery())
    total = await db.scalar(count_query)
    
    # Paginate
    query = query.offset((page - 1) * page_size).limit(page_size)
    result = await db.execute(query)
    tenants = result.scalars().all()
    
    # Add stats to each tenant
    tenant_responses = []
    for tenant in tenants:
        # Get counts
        devices_count = await db.scalar(
            select(func.count()).select_from(Device).where(Device.tenant_id == tenant.id)
        )
        users_count = await db.scalar(
            select(func.count()).select_from(User).where(User.tenant_id == tenant.id)
        )
        active_alerts = await db.scalar(
            select(func.count()).select_from(AlertLog).where(
                AlertLog.tenant_id == tenant.id,
                AlertLog.is_resolved == False
            )
        )
        
        tenant_dict = {
            **tenant.__dict__,
            "devices_count": devices_count,
            "users_count": users_count,
            "active_alerts": active_alerts
        }
        tenant_responses.append(TenantResponse(**tenant_dict))
    
    return PaginatedResponse(
        items=tenant_responses,
        total=total,
        page=page,
        page_size=page_size,
        total_pages=(total + page_size - 1) // page_size
    )


@router.post("", response_model=TenantResponse, status_code=status.HTTP_201_CREATED)
async def create_tenant(
    tenant_data: TenantCreate,
    current_user: User = Depends(require_super_admin()),
    db: AsyncSession = Depends(get_db)
):
    """إنشاء عميل جديد"""
    # Check if email exists
    result = await db.execute(select(Tenant).where(Tenant.email == tenant_data.email))
    if result.scalar_one_or_none():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Email already registered"
        )
    
    tenant = Tenant(**tenant_data.model_dump())
    db.add(tenant)
    await db.commit()
    await db.refresh(tenant)
    
    return TenantResponse(
        **tenant.__dict__,
        devices_count=0,
        users_count=0,
        active_alerts=0
    )


@router.get("/{tenant_id}", response_model=TenantResponse)
async def get_tenant(
    tenant_id: UUID,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """الحصول على عميل محدد"""
    # Check access
    if current_user.role != UserRole.SUPER_ADMIN.value and current_user.tenant_id != tenant_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Access denied"
        )
    
    result = await db.execute(select(Tenant).where(Tenant.id == tenant_id))
    tenant = result.scalar_one_or_none()
    
    if tenant is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Tenant not found"
        )
    
    # Get counts
    devices_count = await db.scalar(
        select(func.count()).select_from(Device).where(Device.tenant_id == tenant.id)
    )
    users_count = await db.scalar(
        select(func.count()).select_from(User).where(User.tenant_id == tenant.id)
    )
    active_alerts = await db.scalar(
        select(func.count()).select_from(AlertLog).where(
            AlertLog.tenant_id == tenant.id,
            AlertLog.is_resolved == False
        )
    )
    
    return TenantResponse(
        **tenant.__dict__,
        devices_count=devices_count,
        users_count=users_count,
        active_alerts=active_alerts
    )


@router.patch("/{tenant_id}", response_model=TenantResponse)
async def update_tenant(
    tenant_id: UUID,
    tenant_data: TenantUpdate,
    current_user: User = Depends(require_super_admin()),
    db: AsyncSession = Depends(get_db)
):
    """تحديث عميل"""
    result = await db.execute(select(Tenant).where(Tenant.id == tenant_id))
    tenant = result.scalar_one_or_none()
    
    if tenant is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Tenant not found"
        )
    
    update_data = tenant_data.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(tenant, field, value)
    
    await db.commit()
    await db.refresh(tenant)
    
    return TenantResponse(**tenant.__dict__, devices_count=0, users_count=0, active_alerts=0)


@router.delete("/{tenant_id}", response_model=MessageResponse)
async def delete_tenant(
    tenant_id: UUID,
    current_user: User = Depends(require_super_admin()),
    db: AsyncSession = Depends(get_db)
):
    """حذف عميل"""
    result = await db.execute(select(Tenant).where(Tenant.id == tenant_id))
    tenant = result.scalar_one_or_none()
    
    if tenant is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Tenant not found"
        )
    
    await db.delete(tenant)
    await db.commit()
    
    return MessageResponse(
        message="Tenant deleted successfully",
        message_ar="تم حذف العميل بنجاح"
    )


@router.get("/{tenant_id}/stats", response_model=TenantStats)
async def get_tenant_stats(
    tenant_id: UUID,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """إحصائيات العميل"""
    # Check access
    if current_user.role != UserRole.SUPER_ADMIN.value and current_user.tenant_id != tenant_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Access denied"
        )
    
    total_devices = await db.scalar(
        select(func.count()).select_from(Device).where(Device.tenant_id == tenant_id)
    )
    online_devices = await db.scalar(
        select(func.count()).select_from(Device).where(
            Device.tenant_id == tenant_id,
            Device.is_online == True
        )
    )
    total_users = await db.scalar(
        select(func.count()).select_from(User).where(User.tenant_id == tenant_id)
    )
    active_alerts = await db.scalar(
        select(func.count()).select_from(AlertLog).where(
            AlertLog.tenant_id == tenant_id,
            AlertLog.is_resolved == False
        )
    )
    from app.models.alert import AlertRule
    total_alert_rules = await db.scalar(
        select(func.count()).select_from(AlertRule).where(AlertRule.tenant_id == tenant_id)
    )
    
    return TenantStats(
        total_devices=total_devices or 0,
        online_devices=online_devices or 0,
        offline_devices=(total_devices or 0) - (online_devices or 0),
        total_users=total_users or 0,
        active_alerts=active_alerts or 0,
        total_alert_rules=total_alert_rules or 0
    )
