from typing import Optional
from sqlalchemy import select, func, and_
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.models.staff.store_model import Store, Chain
from app.models.user.order_model import UserOrder
from app.enums.enums import OrderStatusEnum


class DashboardService:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def get_chain_overview(self, chain_id: int) -> dict:
        """
        Get overview statistics for a chain including:
        - Total number of stores
        - Total number of orders
        - Total sales (sum of final_amount from completed orders)
        - Total sales profit (total_sales after deducting chain profit percentage)
        - Total sales share (10% of total_sales_profit going to superadmin)
        - Orders by status
        """
        # Get chain to retrieve profit_percentage (exclude deleted chains)
        chain_stmt = select(Chain).where(
            and_(
                Chain.chain_id == chain_id,
                Chain.is_deleted == False
            )
        )
        chain_result = await self.db.execute(chain_stmt)
        chain = chain_result.scalar_one_or_none()
        
        # Get profit_percentage (default to 10% if not set)
        profit_percentage = chain.profit_percentage if chain and chain.profit_percentage is not None else 10.0
        
        # Get total stores count
        stores_stmt = select(func.count(Store.store_id)).where(Store.chain_id == chain_id)
        stores_result = await self.db.execute(stores_stmt)
        total_stores = stores_result.scalar() or 0

        # Get store IDs for this chain
        store_ids_stmt = select(Store.store_id).where(Store.chain_id == chain_id)
        store_ids_result = await self.db.execute(store_ids_stmt)
        store_ids = [row[0] for row in store_ids_result.all()]

        if not store_ids:
            # No stores, return empty stats
            return {
                "chain_id": chain_id,
                "total_stores": 0,
                "total_orders": 0,
                "total_sales": 0.0,
                "total_sales_profit": 0.0,
                "total_sales_share": 0.0,
                "orders_by_status": {
                    "IN_PROCESS": 0,
                    "COMPLETED": 0,
                    "CANCELLED": 0,
                },
                "average_order_value": 0.0,
            }

        # Get total orders count
        orders_count_stmt = select(func.count(UserOrder.order_id)).where(
            UserOrder.store_id.in_(store_ids)
        )
        orders_count_result = await self.db.execute(orders_count_stmt)
        total_orders = orders_count_result.scalar() or 0

        # Get total sales (sum of final_amount from completed orders)
        sales_stmt = select(func.coalesce(func.sum(UserOrder.final_amount), 0.0)).where(
            and_(
                UserOrder.store_id.in_(store_ids),
                UserOrder.status == OrderStatusEnum.COMPLETED
            )
        )
        sales_result = await self.db.execute(sales_stmt)
        total_sales = float(sales_result.scalar() or 0.0)

        # Get orders by status
        orders_by_status = {}
        for status in OrderStatusEnum:
            status_stmt = select(func.count(UserOrder.order_id)).where(
                and_(
                    UserOrder.store_id.in_(store_ids),
                    UserOrder.status == status
                )
            )
            status_result = await self.db.execute(status_stmt)
            orders_by_status[status.value] = status_result.scalar() or 0

        # Calculate average order value (from completed orders)
        completed_orders_stmt = select(func.count(UserOrder.order_id)).where(
            and_(
                UserOrder.store_id.in_(store_ids),
                UserOrder.status == OrderStatusEnum.COMPLETED
            )
        )
        completed_count_result = await self.db.execute(completed_orders_stmt)
        completed_orders_count = completed_count_result.scalar() or 0

        average_order_value = 0.0
        if completed_orders_count > 0:
            average_order_value = total_sales / completed_orders_count

        # Calculate total_sales_profit (total_sales after deducting chain profit percentage)
        # If profit_percentage is 10%, then profit = total_sales * 0.10
        # total_sales_profit = total_sales - profit = total_sales * (1 - profit_percentage/100)
        total_sales_profit = total_sales * (1 - profit_percentage / 100.0)
        
        # Calculate total_sales_share (10% of total_sales_profit going to superadmin)
        total_sales_share = total_sales_profit * 0.10

        return {
            "chain_id": chain_id,
            "total_stores": total_stores,
            "total_orders": total_orders,
            "total_sales": round(total_sales, 2),
            "total_sales_profit": round(total_sales_profit, 2),
            "total_sales_share": round(total_sales_share, 2),
            "orders_by_status": orders_by_status,
            "average_order_value": round(average_order_value, 2),
        }

    async def get_superadmin_overview(self) -> dict:
        """
        Get overview statistics for superadmin including:
        - Total number of chains
        - Total number of stores (across all chains)
        - Total sales (sum of final_amount from all completed orders)
        - Total profit from chains (sum of all total_sales_share from all chains)
        - Total orders (across all chains)
        - Average order value
        - Chains breakdown (optional)
        """
        # Get total chains count
        chains_stmt = select(func.count(Chain.chain_id))
        chains_result = await self.db.execute(chains_stmt)
        total_chains = chains_result.scalar() or 0

        # Get total stores count (across all chains)
        stores_stmt = select(func.count(Store.store_id))
        stores_result = await self.db.execute(stores_stmt)
        total_stores = stores_result.scalar() or 0

        # Get all store IDs
        all_store_ids_stmt = select(Store.store_id)
        all_store_ids_result = await self.db.execute(all_store_ids_stmt)
        all_store_ids = [row[0] for row in all_store_ids_result.all()]

        if not all_store_ids:
            # No stores, return empty stats
            return {
                "total_chains": 0,
                "total_stores": 0,
                "total_orders": 0,
                "total_sales": 0.0,
                "total_profit_from_chains": 0.0,
                "average_order_value": 0.0,
                "orders_by_status": {
                    "IN_PROCESS": 0,
                    "COMPLETED": 0,
                    "CANCELLED": 0,
                },
            }

        # Get total orders count (across all chains)
        orders_count_stmt = select(func.count(UserOrder.order_id)).where(
            UserOrder.store_id.in_(all_store_ids)
        )
        orders_count_result = await self.db.execute(orders_count_stmt)
        total_orders = orders_count_result.scalar() or 0

        # Get total sales (sum of final_amount from all completed orders)
        sales_stmt = select(func.coalesce(func.sum(UserOrder.final_amount), 0.0)).where(
            and_(
                UserOrder.store_id.in_(all_store_ids),
                UserOrder.status == OrderStatusEnum.COMPLETED
            )
        )
        sales_result = await self.db.execute(sales_stmt)
        total_sales = float(sales_result.scalar() or 0.0)

        # Get orders by status
        orders_by_status = {}
        for status in OrderStatusEnum:
            status_stmt = select(func.count(UserOrder.order_id)).where(
                and_(
                    UserOrder.store_id.in_(all_store_ids),
                    UserOrder.status == status
                )
            )
            status_result = await self.db.execute(status_stmt)
            orders_by_status[status.value] = status_result.scalar() or 0

        # Calculate average order value (from completed orders)
        completed_orders_stmt = select(func.count(UserOrder.order_id)).where(
            and_(
                UserOrder.store_id.in_(all_store_ids),
                UserOrder.status == OrderStatusEnum.COMPLETED
            )
        )
        completed_count_result = await self.db.execute(completed_orders_stmt)
        completed_orders_count = completed_count_result.scalar() or 0

        average_order_value = 0.0
        if completed_orders_count > 0:
            average_order_value = total_sales / completed_orders_count

        # Calculate total profit from chains
        # This is the sum of all total_sales_share from all chains
        # For each chain: total_sales_share = total_sales_profit * 0.10
        # Where total_sales_profit = total_sales * (1 - profit_percentage/100)
        total_profit_from_chains = 0.0
        
        # Get all chains with their profit_percentage (exclude deleted chains)
        all_chains_stmt = select(Chain).where(Chain.is_deleted == False)
        all_chains_result = await self.db.execute(all_chains_stmt)
        all_chains = all_chains_result.scalars().all()

        for chain in all_chains:
            # Get profit_percentage (default to 10% if not set)
            profit_percentage = chain.profit_percentage if chain.profit_percentage is not None else 10.0
            
            # Get store IDs for this chain
            chain_store_ids_stmt = select(Store.store_id).where(Store.chain_id == chain.chain_id)
            chain_store_ids_result = await self.db.execute(chain_store_ids_stmt)
            chain_store_ids = [row[0] for row in chain_store_ids_result.all()]

            if not chain_store_ids:
                continue

            # Get total sales for this chain
            chain_sales_stmt = select(func.coalesce(func.sum(UserOrder.final_amount), 0.0)).where(
                and_(
                    UserOrder.store_id.in_(chain_store_ids),
                    UserOrder.status == OrderStatusEnum.COMPLETED
                )
            )
            chain_sales_result = await self.db.execute(chain_sales_stmt)
            chain_total_sales = float(chain_sales_result.scalar() or 0.0)

            # Calculate chain profit and superadmin share
            chain_sales_profit = chain_total_sales * (1 - profit_percentage / 100.0)
            chain_sales_share = chain_sales_profit * 0.10
            total_profit_from_chains += chain_sales_share

        return {
            "total_chains": total_chains,
            "total_stores": total_stores,
            "total_orders": total_orders,
            "total_sales": round(total_sales, 2),
            "total_profit_from_chains": round(total_profit_from_chains, 2),
            "average_order_value": round(average_order_value, 2),
            "orders_by_status": orders_by_status,
        }

