from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy import func
from datetime import date, datetime, timedelta
from app.database import get_db
from app.models.plant import Plant
from app.models.production import ProductionBatch
from app.models.inventory import InventoryItem
from app.models.sale import Sale, SaleItem
from app.models.customer import Customer
from app.models.supplier import Supplier
from app.models.employee import Employee
from app.models.finance import Expense, Income
from app.models.alert import Alert
from app.services.auth import get_current_user

router = APIRouter(prefix="/dashboard", tags=["dashboard"])


@router.get("")
def get_dashboard(db: Session = Depends(get_db), current_user=Depends(get_current_user)):
    today = date.today()
    month_start = today.replace(day=1)

    total_plants = db.query(func.count(Plant.id)).filter(Plant.is_active == True).scalar() or 0
    active_batches = db.query(func.count(ProductionBatch.id)).filter(
        ProductionBatch.status.notin_(["completed", "sold"])
    ).scalar() or 0

    plants_ready = db.query(func.count(ProductionBatch.id)).filter(
        ProductionBatch.status == "ready"
    ).scalar() or 0

    today_sales = db.query(func.coalesce(func.sum(Sale.total), 0)).filter(Sale.date == today).scalar()
    month_sales = db.query(func.coalesce(func.sum(Sale.total), 0)).filter(Sale.date >= month_start).scalar()
    total_revenue = db.query(func.coalesce(func.sum(Sale.total), 0)).scalar()

    today_expenses = db.query(func.coalesce(func.sum(Expense.amount), 0)).filter(Expense.date == today).scalar()
    month_expenses = db.query(func.coalesce(func.sum(Expense.amount), 0)).filter(Expense.date >= month_start).scalar()

    low_stock = db.query(func.count(InventoryItem.id)).filter(
        InventoryItem.quantity <= InventoryItem.min_quantity
    ).scalar() or 0

    total_customers = db.query(func.count(Customer.id)).scalar() or 0
    total_suppliers = db.query(func.count(Supplier.id)).scalar() or 0
    total_employees = db.query(func.count(Employee.id)).filter(Employee.is_active == True).scalar() or 0

    active_alerts = db.query(func.count(Alert.id)).filter(Alert.is_resolved == False).scalar() or 0

    recent_sales = db.query(Sale).order_by(Sale.created_at.desc()).limit(5).all()
    top_plants = db.query(
        Plant.name, func.sum(SaleItem.quantity).label("total_sold")
    ).join(SaleItem, SaleItem.plant_id == Plant.id).group_by(Plant.name).order_by(func.sum(SaleItem.quantity).desc()).limit(5).all()

    return {
        "stats": {
            "total_plants": total_plants,
            "active_batches": active_batches,
            "plants_ready": plants_ready,
            "today_sales": round(today_sales, 2),
            "month_sales": round(month_sales, 2),
            "total_revenue": round(total_revenue, 2),
            "today_expenses": round(today_expenses, 2),
            "month_expenses": round(month_expenses, 2),
            "low_stock": low_stock,
            "total_customers": total_customers,
            "total_suppliers": total_suppliers,
            "total_employees": total_employees,
            "active_alerts": active_alerts,
            "profit_today": round(today_sales - today_expenses, 2),
            "profit_month": round(month_sales - month_expenses, 2),
        },
        "recent_sales": [{"id": s.id, "invoice": s.invoice_number, "total": s.total, "date": str(s.date), "status": s.status} for s in recent_sales],
        "top_plants": [{"name": p[0], "sold": p[1]} for p in top_plants],
    }
