import os
from datetime import datetime
from fastapi import APIRouter, HTTPException, Depends, Request,Form,File,UploadFile
from typing import Optional
from app.db import database
from app.v1.models.platform.services import Workforce, WorkforceCreate, WorkforceUpdate, Workforces,WorkforceUpdateBase,CheckListSelect,AddonsSelect,SkillsListSelect,ServiceCategorySelect
from app.v1.models.saas.usersmodel import User  # Ensure you have a valid User model
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.services.platform import services as account_service  # Adjust path as needed
import json

# Import service functions
from ...services.platform.services import (
    get_users_service,
    update_account_service,
    delete_account_service,
    update_workforce_service,
    get_select_list,
    get_addonselect_list,
    get_skillsselect_list,
    get_servicecatselect_list
)


router = APIRouter()

@router.post("/", response_model=Workforce)
async def create_account(
    service_title: str = Form(...),
    service_id: str = Form(...),
    service_description: str = Form(...),
    capacity_jobs: int = Form(...),
    has_cost: int = Form(...),
    is_vehicle_focused: int = Form(...),
    skills: str = Form(...),
    addons: str = Form(...),
    checklist: str = Form(...),
    dynamicFields: str = Form(...),
    image: UploadFile = File(None),
    map_icon: UploadFile = File(None),    
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    # Create upload directory if not exists
    os.makedirs("public/services", exist_ok=True)
    print("POST CHECK LIST 383838383838")
    filenames = {}
    for file_type, upload_file in [("image", image), ("map_icon", map_icon)]:
        if upload_file and upload_file.filename:
            timestamp = int(datetime.now().timestamp())
            ext = upload_file.filename.split('.')[-1]
            filename = f"{file_type}-{timestamp}.{ext}"
            filepath = f"public/services/{filename}"
            
            # Save file
            with open(filepath, "wb") as buffer:
                content = await upload_file.read()
                buffer.write(content)
            
            filenames[file_type] = filename

    try:
        # Parse dynamicFields from JSON string to Python list
        parsed_dynamic_fields = json.loads(dynamicFields)
    except json.JSONDecodeError as e:
        raise HTTPException(status_code=400, detail=f"Invalid dynamicFields format: {e}")

        
    # Create account data
    account_data = {
        "service_id": service_id,
        "service_title": service_title,
        "service_description": service_description,
        "capacity_jobs": capacity_jobs,
        "has_cost": has_cost,
        "is_vehicle_focused": is_vehicle_focused,
        "skills": skills,
        "addons": addons,
        "checklist": checklist,
        "dynamicFields": parsed_dynamic_fields,  # Use parsed list
        **filenames
    }
    print("DYNAMICFIELDSDYNAMICFIELDSSSSSSSS25545555555");
    print(account_data);
    try:
        created_account = account_service.create_account_service(
            WorkforceCreate(**account_data), 
            db
        )
        return created_account
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))

@router.get("/getchecklist/{account_id}", response_model=CheckListSelect)
def get_users(
    account_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Returns a list of users for the given account.
    """
    print("getlist listlistlistlist 22200000555555")
    return get_select_list(account_id,db, current_user)

@router.get("/getskills/{account_id}", response_model=SkillsListSelect)
def get_users(
    account_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Returns a list of users for the given account.
    """
    print("getlist skillssss 22200000555555")
    return get_skillsselect_list(account_id,db, current_user)

@router.get("/getaddonlist/{account_id}", response_model=AddonsSelect)
def get_users(
    account_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Returns a list of users for the given account.
    """
    print("getlist listlistlistlist 22200000555555")
    return get_addonselect_list(account_id,db, current_user)

@router.get("/getservicecategorylist/{account_id}", response_model=ServiceCategorySelect)
def get_users(
    account_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Returns a list of users for the given account.
    """
    print("getlist listlistlistlist 22200000555555")
    return get_servicecatselect_list(account_id,db, current_user)

@router.get("/", response_model=Workforces)
def get_accounts(
    skip: int = 0, 
    limit: int = 10, 
    q: Optional[str] = None,
    account_type: Optional[str] = None,
    is_active: Optional[bool] = None,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):

    try:
        print("get_accountsget_accounts 35")
        result = account_service.get_accounts_service(skip, limit, q, account_type, is_active, db, current_user)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail="Internal server error")

@router.get("/{account_id}", response_model=WorkforceCreate)
def get_account(
    account_id: str, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):

    try:
        print("get_accountget_account 471440000")
        account = account_service.get_account_service(account_id, db)
        if account is None:
            raise HTTPException(status_code=404, detail="Workforce not found")
        return account
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Error retrieving workforce: {str(e)}")

@router.post("/{account_id}", response_model=Workforce)
async def update_account(
    account_id: str,
    service_id: str = Form(None),
    service_title: str = Form(None),
    service_description: str = Form(None),
    capacity_jobs: int = Form(None),
    has_cost: int = Form(None),
    is_vehicle_focused: int = Form(None),
    skills: str = Form(None),
    addons: str = Form(None),
    checklist: str = Form(None),
    image: UploadFile = File(None),
    map_icon: UploadFile = File(None),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    # File handling logic same as create endpoint
    # ...
    
    # Update logic
    update_data = {
        "service_id": service_id,
        "service_title": service_title,
        "service_description": service_description,
        "capacity_jobs": capacity_jobs,
        "has_cost": has_cost,
        "is_vehicle_focused": is_vehicle_focused,
        "skills": skills,
        "addons": addons,
        "checklist": checklist,
        **filenames
    }
    
    # Remove null values
    update_data = {k: v for k, v in update_data.items() if v is not None}
    
    try:
        updated_account = account_service.update_account_service(
            account_id,
            WorkforceUpdate(**update_data),
            current_user,
            db
        )
        return updated_account
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))

@router.delete("/{account_id}", response_model=Workforce)
def delete_account(
    account_id: str, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    print("delete_accountdelete_account 79")
    try:
        deleted_account = account_service.delete_account_service(account_id, db)
        if deleted_account is None:
            raise HTTPException(status_code=404, detail="Workforce not found")
        return deleted_account
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Error deleting workforce: {str(e)}")

@router.get("/list/{account_id}/", response_model=Workforces)
def get_users(
    account_id: str,
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    is_active: Optional[bool] = None,
    status: Optional[str] = None,
    service_id: Optional[int] = None,
    has_cost: Optional[str] = None,
    is_vehicle_focused: Optional[str] = None,
    created_date_from: Optional[str] = None,
    created_date_to: Optional[str] = None,
    sort_by: Optional[str] = None,          
    sort_order: Optional[str] = "asc",      
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    def parse_bool(val):
        if isinstance(val, str):
            return val.lower() == "true" if val else None
        return val

    return get_users_service(
        account_id, skip, limit, q, is_active, status, service_id,
        parse_bool(has_cost), parse_bool(is_vehicle_focused), created_date_from, created_date_to, sort_by, sort_order, db, current_user
    )


@router.put("/{account_id}", response_model=WorkforceUpdate)
async def update_workforce(
    account_id: str,
    role_update: WorkforceUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Update an existing role.
    """
    if current_user.get("roles", 0) != 1 and not current_user.get("is_account_admin", False):
        raise HTTPException(status_code=403, detail="Not authorized to update roles")
    try:
        print("account_idaccount_idaccount_idaccount_id11112222555")
        print(account_id)
        updated_role = await update_workforce_service(account_id, role_update, db)
        if not updated_role:
            raise HTTPException(status_code=404, detail="Workforce not found")
        return updated_role
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
