from fastapi import APIRouter, Depends, HTTPException, Query
from app.db import database
from typing import Optional, List, Dict
from datetime import datetime
from app.v1.models.platform.schedules import Schedule, ScheduleCreate, ScheduleUpdate, Schedules,ScheduleAssignmentRequest,ScheduleSelectItem,ScheduleTravelStatusUpdateRequest, ScheduleWithTasksCreate, ShiftStatusCreate, ShiftStatusUpdate, ShiftStatusResponse, ShiftStatusList
from app.v1.services.platform import schedules as schedule_service

router = APIRouter()

@router.post("/", response_model=Schedule)
def create_schedule(schedule: ScheduleCreate, db: database.MongoDB = Depends(database.get_mongo_db)):
    print("create_schedulecreate_schedulecreate_schedule1010101010101010")
    return schedule_service.create_schedule_service(schedule, db)

# API for getting schedules list for select box with search by schedule name
@router.get("/search", response_model=List[ScheduleSelectItem])
def search_schedules_for_select(
    account_id: str = Query(..., description="Account ID"),
    q: Optional[str] = Query(None, description="Search keyword for schedule_name"),
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    return schedule_service.search_schedules_select_service(
        account_id=account_id,
        search_query=q,
        db=db
    )

@router.get("/{schedule_id}", response_model=Schedule)
def get_account(schedule_id: str, db: database.MongoDB = Depends(database.get_mongo_db)):
    schedule = schedule_service.get_schedule_service(schedule_id, db)    
    if not schedule:
        raise HTTPException(status_code=404, detail="Schedule not found")
    return schedule

@router.get("/list/{account_id}", response_model=Schedules)
def list_schedules(account_id: str, db: database.MongoDB = Depends(database.get_mongo_db)):
    return schedule_service.list_schedules_service(account_id, db)

@router.put("/{schedule_id}", response_model=Schedule)
def update_schedule(schedule_id: str, schedule_update: ScheduleUpdate, db: database.MongoDB = Depends(database.get_mongo_db)):
    updated = schedule_service.update_schedule_service(schedule_id, schedule_update, db)
    if not updated:
        raise HTTPException(status_code=404, detail="Schedule not found")
    return updated

@router.delete("/{schedule_id}", response_model=Schedule)
def delete_schedule(schedule_id: str, db: database.MongoDB = Depends(database.get_mongo_db)):
    deleted = schedule_service.delete_schedule_service(schedule_id, db)
    if not deleted:
        raise HTTPException(status_code=404, detail="Schedule not found")
    return deleted

@router.get("/", response_model=Schedules)
def list_schedules_with_query(
    account_id: str = Query(..., description="Account ID"),
    skip: int = Query(0, ge=0, description="Pagination start"),
    limit: int = Query(10, gt=0, le=100, description="Max number of items to return"),
    q: Optional[str] = Query(None, description="Optional search keyword"),
    status: Optional[str] = None,
    start_date_from: Optional[str] = None,
    start_date_to: Optional[str] = None,
    customer_id: Optional[str] = None,
    workforce_id: Optional[str] = None,
    trip_type: Optional[int] = None,
    fleet_id: Optional[str] = None,
    sort_by: Optional[str] = Query("created_date", description="Field to sort by"),
    order_by: Optional[int] = 1,  # 0 for ASC, 1 for DESC
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    print("Coming schedule 69696969696969696969696")
    return schedule_service.list_schedules_service(
        account_id=account_id,
        skip=skip,
        limit=limit,
        search_query=q,
        status=status,
        start_date_from=start_date_from,
        start_date_to=start_date_to,
        customer_id=customer_id,
        workforce_id=workforce_id,
        trip_type=trip_type,
        fleet_id=fleet_id,
        sort_by=sort_by,
        order_by=order_by,
        db=db
    )

@router.post("/assign")
async def assign_schedule(request: ScheduleAssignmentRequest, db: database.MongoDB = Depends(database.get_mongo_db)):
    success = schedule_service.assign_schedule_service(
        schedule_id=request.schedule_id,
        account_id=request.account_id,
        workforce_id=request.workforce_id,
        db=db
    )
    print('Schedule or Workforce not foundSchedule or Workforce not found')
    if not success:
        raise HTTPException(status_code=404, detail="Schedule or Workforce not found")

    return {"message": "Schedule assigned successfully"}

@router.post("/update-travel-status", response_model=Schedule)
def update_travel_status(
    request: ScheduleTravelStatusUpdateRequest,
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    updated = schedule_service.update_travel_status_service(
        schedule_id=request.schedule_id,
        travel_status=request.travel_status,
        db=db
    )
    if not updated:
        raise HTTPException(status_code=404, detail="Schedule not found")
    return updated

@router.post("/create-with-tasks", response_model=Schedule)
def create_schedule_with_tasks(payload: ScheduleWithTasksCreate, db: database.MongoDB = Depends(database.get_mongo_db)):
    print("151515151515151515151551ssss")
    return schedule_service.create_schedule_with_tasks_service(payload, db)

# ------------------- SHIFT STATUS CRUD -------------------
@router.post("/shift-status", response_model=ShiftStatusResponse)
def create_shift_status(request: ShiftStatusCreate, db: database.MongoDB = Depends(database.get_mongo_db)):
    result = schedule_service.create_shift_status_service(request, db)
    return result


@router.get("/shift-status/{shift_status_id}", response_model=ShiftStatusResponse)
def get_shift_status(shift_status_id: str, db: database.MongoDB = Depends(database.get_mongo_db)):
    result = schedule_service.get_shift_status_service(shift_status_id, db)
    if not result:
        raise HTTPException(status_code=404, detail="Shift status not found")
    return result


@router.get("/shift-status/list/{account_id}/{schedule_id}", response_model=ShiftStatusList)
def list_shift_statuses(account_id: str, schedule_id: str, db: database.MongoDB = Depends(database.get_mongo_db)):
    return schedule_service.list_shift_status_service(account_id, schedule_id, db)


@router.put("/shift-status/{shift_status_id}", response_model=ShiftStatusResponse)
def update_shift_status(shift_status_id: str, update: ShiftStatusUpdate, db: database.MongoDB = Depends(database.get_mongo_db)):
    updated = schedule_service.update_shift_status_service(shift_status_id, update, db)
    if not updated:
        raise HTTPException(status_code=404, detail="Shift status not found")
    return updated


@router.delete("/shift-status/{shift_status_id}")
def delete_shift_status(shift_status_id: str, db: database.MongoDB = Depends(database.get_mongo_db)):
    deleted = schedule_service.delete_shift_status_service(shift_status_id, db)
    if not deleted:
        raise HTTPException(status_code=404, detail="Shift status not found")
    return deleted

