from fastapi import APIRouter, Depends, HTTPException, Query, Path, Body, Request
from typing import Optional, List, Dict, Any
from datetime import datetime
from pydantic import BaseModel, Field
from app.db import database
from ...dependencies.auth import get_current_userdetails
from ...services.saas.support import (
    create_activity_service,
    list_activities_service,
    get_activity_service,
    update_activity_service,
    delete_activity_service,
    get_support_dashboard_service,
    update_pipeline_status_service
)

router = APIRouter()

# ------------------------------------------------------------------
# Pydantic Models for Support Activities
# (You can also place these in a separate models file if preferred)
# ------------------------------------------------------------------
class SupportActivityBase(BaseModel):
    type: str = Field(..., description="Type of activity, e.g. 'comment', 'meeting', 'note', 'pipeline_update'")
    account_id: str = Field(..., description="Account ID associated with this activity")
    user_id: Optional[str] = Field(None, description="ID of the user performing the activity")
    content: Optional[str] = Field(None, description="Main content (comment text, meeting notes, etc.)")
    additional_data: Optional[Dict[str, Any]] = Field(
        None, description="Extra details (for meetings: scheduled_date, for pipeline updates: old and new status, etc.)"
    )

class SupportActivityCreate(SupportActivityBase):
    pass

class SupportActivityUpdate(BaseModel):
    content: Optional[str] = Field(None, description="Updated content")
    additional_data: Optional[Dict[str, Any]] = Field(None, description="Updated extra details")

class SupportActivity(SupportActivityBase):
    activity_id: str = Field(..., alias="_id")
    created_date: datetime

# ------------------------------------------------------------------
# API Endpoints for the Support Module
# ------------------------------------------------------------------

@router.post("/", response_model=SupportActivity)
async def create_activity(
    activity: SupportActivityCreate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Create a new support activity record.
    If account_id is not provided, the current user's account_id is used.
    """
    if not activity.account_id:
        activity = activity.copy(update={"account_id": current_user.get("account_id")})
    try:
        new_activity = await create_activity_service(activity, db)
        return new_activity
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to create activity: {str(e)}")

@router.get("/", response_model=List[SupportActivity])
async def list_activities(
    account_id: str = Query(..., description="Account ID to filter activities"),
    activity_type: Optional[str] = Query(None, description="Filter by activity type, e.g. 'comment'"),
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Retrieve a paginated list of support activities for an account.
    You may filter by the 'type' field.
    """
    try:
        activities = await list_activities_service(account_id, activity_type, skip, limit, db)
        return activities
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to list activities: {str(e)}")

@router.get("/{activity_id}", response_model=SupportActivity)
async def get_activity(
    activity_id: str = Path(..., description="Support activity ID"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Retrieve a single support activity record by its ID.
    """
    try:
        activity = await get_activity_service(activity_id, db)
        if not activity:
            raise HTTPException(status_code=404, detail="Activity not found")
        return activity
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to retrieve activity: {str(e)}")

@router.put("/{activity_id}", response_model=SupportActivity)
async def update_activity(
    activity_id: str,
    activity_update: SupportActivityUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Update an existing support activity.
    """
    try:
        updated = await update_activity_service(activity_id, activity_update, db)
        if not updated:
            raise HTTPException(status_code=404, detail="Activity not found")
        return updated
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to update activity: {str(e)}")

@router.delete("/{activity_id}", response_model=SupportActivity)
async def delete_activity(
    activity_id: str = Path(..., description="Support activity ID"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Delete a support activity record.
    """
    try:
        deleted = await delete_activity_service(activity_id, db)
        if not deleted:
            raise HTTPException(status_code=404, detail="Activity not found")
        return deleted
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to delete activity: {str(e)}")

@router.get("/dashboard/{account_id}", response_model=Dict[str, Any])
async def support_dashboard(
    account_id: str = Path(..., description="Account ID for support dashboard metrics"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Return aggregated support metrics for the account:
      - Count of support comments/notes
      - Count of upcoming meetings
      - (Trial info is handled in subscriptions)
    """
    try:
        dashboard = await get_support_dashboard_service(account_id, db)
        return dashboard
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Dashboard error: {str(e)}")

@router.post("/pipeline", response_model=SupportActivity)
async def update_pipeline_status(
    account_id: str = Body(..., embed=True, description="Account ID for pipeline update"),
    new_status: str = Body(..., embed=True, description="New sales pipeline status (e.g. 'trial', 'live paid')"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Update the sales pipeline status for an account.
    This endpoint updates the account record and logs the change as a support activity.
    """
    try:
        activity = await update_pipeline_status_service(account_id, new_status, db)
        return activity
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Pipeline update failed: {str(e)}")
