from typing import List
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status,BackgroundTasks,Query
from datetime import date

#db
from src.company_management.utils import store_image
from src.constants import TicketPriorityEnum
from src.core.database import get_db
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import Optional

#external services
from src.external.email import transporter
#models
from src.models.company import Company
from src.models.company_user import User


#schemas
from .schemas import (
    AddCompanyUser,
    CompanyIpAddressSchema,
    DeleteCompanyUser,
    SettingsNotificationsSchema,
    ThemeSchema,
    TicketUSerSchema,
    UpdateCompanyUser,
    UpdatedCompanyUserResponse,
    UpdateTicketUSerSchema
    
)

#global schemas
from src.schemas.compnay_user import CurrentCompanyUser

#global deps
from src.common.dependencies import get_current_company_user

#auth utils
from src.auth.utils import pwd_context

#global utils
from src.common.utils import add_delete_update_company_user_access_check,generate_password

#services

from .service import CompanyManagement
from fastapi.staticfiles import StaticFiles


company_management_router = APIRouter(prefix="/company/management", tags=["company management"])

# import os

# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# app.mount("/uploads", StaticFiles(directory=os.path.join(BASE_DIR, "uploads")), name="uploads")

@company_management_router.post("/add-user/")
async def add_user(user:AddCompanyUser,db: AsyncSession = Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):

    try:
        
        has_permission = add_delete_update_company_user_access_check(currentCompanyUser,action="add")

        if not has_permission:

            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You do not have permission to add a user."
            )
        
        result = await CompanyManagement.add_user_to_company(
            user_info= user,
            company_id= currentCompanyUser.company_id,
            db = db                                            
            )
        return result

    except HTTPException as e:
        raise e
    

@company_management_router.delete("/delete-user/")
async def delete_user(user:DeleteCompanyUser,db: AsyncSession = Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):
    
    try:
        
        has_permission = add_delete_update_company_user_access_check(currentCompanyUser,action="delete")

        if not has_permission:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You do not have permission to delete a user."
            )
        result = await CompanyManagement.delete_user(user_id = user.user_id,company_id = currentCompanyUser.company_id,db =db)
        return result
    except Exception as e:
        raise e

@company_management_router.patch("/update-user/")
async def update_user(user: UpdateCompanyUser,db: AsyncSession = Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):

    try:

        has_permission = add_delete_update_company_user_access_check(currentCompanyUser, action="update")

        if not has_permission:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You do not have permission to update a user."
            )
        
        result = await CompanyManagement.update_user(user_info=user,
                        company_id = currentCompanyUser.company_id,
                        db= db)
        return result
    
    except HTTPException as e:
        raise e


@company_management_router.get("/company-users/")
async def get_users(db: AsyncSession = Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):

    try:
        if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != "it":

            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Unauthorized only admin from IT department have acess please contact IT admin."
            )
        
        result = await CompanyManagement.get_company_users(company_id=currentCompanyUser.company_id,db=db)
        
        return result
    except HTTPException as e:
        raise e



@company_management_router.post("/user/activate-deactivate/")
async def company_user_activate_deactivate(
    user_id: str = Query(..., description="company IT admin user ID"),
    db: AsyncSession = Depends(get_db),
    currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):

    try:
        if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != "it":

            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Unauthorized only admin from IT department have acess please contact IT admin."
            )
        
         
        company_id = currentCompanyUser.company_id
        result = await CompanyManagement.company_user_activate_deactivate(company_id=company_id,user_id=user_id,db=db)
        
        return result
    except HTTPException as e:
        raise e


# @company_management_router.post("/user/update_theme/")
# async def company_user_theme(theme:ThemeSchema,db:AsyncSession=Depends(get_db),currentCompanyUser:CurrentCompanyUser=Depends(get_current_company_user)):
#     try:
#         if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != "it":
#             raise HTTPException(
#                 status_code=status.HTTP_403_FORBIDDEN,
#                 detail="Unauthorized only admin from IT department have access please contact IT admin."
#             )
#         result= await CompanyManagement.set_company_theme(
#         theme=theme,
#         company_id=currentCompanyUser.company_id,
#         db=db
#         )
#         return result
#     except HTTPException as e:
#         raise e
# @company_management_router.get("/user/user_theme/")
# async def get_company_user_theme(db:AsyncSession=Depends(get_db),currentCompanyUser:CurrentCompanyUser=Depends(get_current_company_user)):
#     try:
#         if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != "it":
#             raise HTTPException(
#                 status_code=status.HTTP_403_FORBIDDEN,
#                 detail="Unauthorized only admin from IT department have access please contact IT admin."
#             )
#         result= await CompanyManagement.get_company_theme(
#         company_id=currentCompanyUser.company_id,
#             db=db
#             )
#         return result
#     except HTTPException as e:
#             raise e
# @company_management_router.post("/ipaddress/add/")
# async def set_company_ip_addresses(ipaddress:CompanyIpAddressSchema,db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):
#     try:
#         if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != "it":
#             raise HTTPException(
#                 status_code=status.HTTP_403_FORBIDDEN,
#                 detail="Unauthorized only admin from IT department have access please contact IT admin."
#             )
#         #print(ipaddress)
#         result=await CompanyManagement.set_company_ipaddress(currentCompanyUser.company_id,ipaddress.allowed_ipaddress,db)
#         return result
#     except HTTPException as e:
#         raise e
    
# @company_management_router.delete("/ipaddress/delete")
# async def delete_company_ip_addresses(ipaddress:CompanyIpAddressSchema,db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):
#     try:
#         if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != "it":
#             raise HTTPException(
#                 status_code=status.HTTP_403_FORBIDDEN,
#                 detail="Unauthorized only admin from IT department have access please contact IT admin."
#             )
#         #print(ipaddress)
#         result=await CompanyManagement.delete_company_ipaddress(currentCompanyUser.company_id,ipaddress.allowed_ipaddress,db)
#         return result
#     except HTTPException as e:
#         raise e
# @company_management_router.get("/ipaddress/")
# async def get_company_ip_addresses(db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):
#         try:
#             print(currentCompanyUser.role)
#             if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != "it":
#                 raise HTTPException(
#                     status_code=status.HTTP_403_FORBIDDEN,
#                     detail="Unauthorized only admin from IT department have access please contact IT admin."
#                 )
#             #print(ipaddress)
#             result=await CompanyManagement.get_company_ipaddress(currentCompanyUser.company_id,db)
#             return result
#         except HTTPException as e:
#             raise e


@company_management_router.post("/tickets/")
async def ticketcreation(
       issue_type: str = Form(...),
    title: str = Form(...),
    description: str = Form(...),
    priority: TicketPriorityEnum = Form(...),files: List[UploadFile] = File([]),db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):
          
          
         
          try:
              if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != 'it':
                  raise HTTPException(
                      status_code=status.HTTP_403_FORBIDDEN,
                      detail="Unauthorized only admin from IT department have access please contact IT admin."
                      )
              ticket_obj = TicketUSerSchema(issue_type=issue_type,title=title,description=description,priority=priority)  # parse JSON string to object
              
    # Now ticket_obj is a Pydantic object
              file_location=await store_image(files,currentCompanyUser.company_name)
              print(file_location)
              result=await CompanyManagement.create_ticket(ticket_obj,file_location,currentCompanyUser.company_id,currentCompanyUser.user_id,db)
              return result
          except HTTPException as e:
              raise e
@company_management_router.get("/tickets/")
async def get_ticket(
    page:int= Query(1,ge=1,description='page number'),
    limit:int= Query(10,ge=1,description='limit of tickets per page'),
    issue_type: Optional[str] = Query(None),
    title: Optional[str] = Query(None),
    priority:Optional[TicketPriorityEnum]=Query(None),
    
    db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):
    '''
    <h1>get  tickets of current company </h1>
      <h2>args:</h2>
            <br>
            <p><b>page(int)</b>:<br></p>
            <br>
                <p><i>page number</i><br><br></p>
                <p><b>limit(int)</b>:<br><br></p>
                <p><i>limit of tickets per page</i><br><br></p>
                <!--
            db(AsyncSession):session object used to connect to database
            currentCompanyUser(CurrentCompanyUser):current logged in user information
            -->
   <h2> Response</h2>

    <p><b>returns dictionary containing list of tickets</b>
    '''
    try:
        if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != 'it':
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Unauthorized only admin from IT department have access please contact IT admin."
                )
        result=await CompanyManagement.get_ticket(page,limit,title=title,issuetype=issue_type,priority=priority,company_id=currentCompanyUser.company_id,db=db)
        return result
    except HTTPException as e:
        raise e
@company_management_router.patch("/tickets/")
async def  update_ticket(ticketid:str=Form(...),
        issue_type: Optional[str] = Form(None),
title: Optional[str] = Form(None),
description: Optional[str] = Form(None),
priority: Optional[TicketPriorityEnum] = Form(None),
files: Optional[List[UploadFile]] = File(None),db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):
    '''
        ticket  updated by company  
        parameters:
                ticketID (str) : it is the id of ticket to be updated compulsory
                Issue_Type (str) : it is the type of issue 
                Title (str) : it is the title of ticket
                Description (str) : it is the description of ticket
                priority (TicketPriorityEnum) : it is the priority of ticket
                files (List[UploadFile]) : it is the list of files to be uploaded
               <!-- db(AsyncSession):session object used to connect to database
                currentCompanyUser(CurrentCompanyUser):current logged in user information -->
        response:
                returns dictionary containing success message
                '''
    try:  
        if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != 'it':
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Unauthorized only admin from IT department have access please contact IT admin."
                )
        print("hello world1")
        ticket_obj = UpdateTicketUSerSchema(issue_type=issue_type,title=title,description=description,priority=priority)
        print(ticket_obj)
        valid_files = []
        if files:
            for file in files:
                print("hello world2")
                content = await file.read()
                await file.seek(0)
                if content and file.filename:
                    valid_files.append(file)

        if valid_files:
            file_location = await store_image(valid_files, currentCompanyUser.company_name)
        else:
            file_location = []
        result=await CompanyManagement.updateticket(ticketid=ticketid,ticket_obj=ticket_obj, file_location=file_location,db=db)
        return result
    except HTTPException as e:
        print(e)
        raise e

@company_management_router.post("/notification/settings/")
async def notificationsettings(transaction_alert:bool=Form(...),
    report_ready:bool=Form(...),
    system_update:bool=Form(...),
    weekly_summary:bool=Form(...),db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser = Depends(get_current_company_user)):
    '''
    update notification settings if in case of transaction alert, report ready, system update, weekly summary not avaliable  create
    notification settings for user
    parameters:
    transaction_alert (bool): it is the transaction alert notification settings
    report_ready (bool): it is the report ready notification settings
    system_update (bool): it is the system update notification settings
    weekly_summary (bool): it is the weekly summary notification settings
    <!-- db(AsyncSession):session object used to connect to database
    currentCompanyUser(CurrentCompanyUser):current logged in user information  -->
    response:
    returns dictionary containing notification settings
    '''
    try:
        if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != 'it':
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Unauthorized only admin from IT department have access please contact IT admin."
                )
        settings=SettingsNotificationsSchema(transaction_alert=transaction_alert,report_ready=report_ready,system_update=system_update,weekly_summary=weekly_summary)
        result=await CompanyManagement.notificationsSettings(settings,user_id=currentCompanyUser.user_id,db=db)
        print(result)
        return result
    
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500,  detail=str(e))
@company_management_router.get("/notification/settings/")
async def get_notificationsetting(db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser=Depends(get_current_company_user)):
    '''
    get notification settings for user
    parameters:
    db(AsyncSession):session object used to connect to database
    currentCompanyUser(CurrentCompanyUser):current logged in user information
    response:
    returns dictionary containing notification settings
    '''
    try:
        if currentCompanyUser.role.lower() != "admin" or currentCompanyUser.department.lower() != 'it':
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Unauthorized only admin from IT department have access please contact IT admin."
                )
        result=await CompanyManagement.get_notifications_Settings(user_id=currentCompanyUser.user_id,db=db)
        print(result)
        return result
    except HTTPException as e:
        raise e
    
                               
@company_management_router.get("/account/profile/")
async def Profile(db:AsyncSession=Depends(get_db),currentCompanyUser: CurrentCompanyUser=Depends(get_current_company_user)):
    try:
       
        result=await CompanyManagement.getUserdetails(user_id=currentCompanyUser.user_id,company_id=currentCompanyUser.company_id,db=db)
        print(result)
        return result
    except HTTPException as e:
        raise e
    