""" Events management routes """
import uuid
from typing import Any, Optional
from datetime import datetime

from sqlmodel import select
from fastapi import APIRouter, Depends, HTTPException

from app import crud
from app.api.deps import (
    CurrentUser,
    SessionDep,
    get_current_active_superuser,
)

from app.models import (
    Event,
    EventCreate,
    EventUpdate,
    EventOut,
    EventsOut,
    TipusEvent,
)
from app.models import Message

router = APIRouter()

@router.get("/my_events", response_model=EventsOut)
def read_my_events(session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100) -> Any:
    """
    Get all events for the current user's account.
    """
    events, count = crud.event.get_events_by_account(session=session, account_id=current_user.id, skip=skip, limit=limit)

    
    return EventsOut(data=events, count=count)

@router.get("/all", response_model=EventsOut, dependencies=[Depends(get_current_active_superuser)])
def read_all_events(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
    """
    Get all events (admin only).
    """
    events, count = crud.event.get_all_events(
        session=session, 
        skip=skip, 
        limit=limit
    )
    
    return EventsOut(data=events, count=count)

@router.get("/events/{event_id}", response_model=EventOut)
def get_event(
    *,
    event_id: uuid.UUID,
    session: SessionDep,
    current_user: CurrentUser
) -> EventOut:
    """
    Get event by id
    """
    event = crud.event.get_event_by_id_out(session=session, event_id=event_id)
    if not event:
        raise HTTPException(status_code=404, detail="Event not found")
    return event

@router.post("/", response_model=EventOut)
def create_event(
    *,
    session: SessionDep,
    event_in: EventCreate,
    current_user: CurrentUser
) -> EventOut:
    """
    Create new event.
    """
    event = crud.event.create_event(
        session=session,
        obj_in=event_in,
        account_id=current_user.id
    )
    return event

@router.patch("/{event_id}", response_model=EventOut)
def update_event(session: SessionDep, event_id: uuid.UUID, event_in: EventUpdate, current_user: CurrentUser) -> Any:
    """
    Update an event.
    """
    event = crud.event.get_event_by_id(session=session, event_id=event_id)
    
    if not event:
        raise HTTPException(status_code=404, detail="Event not found")

    
    updated_event = crud.event.update_event(
        session=session, 
        event=event, 
        event_in=event_in
    )
    
    return updated_event

@router.delete("/{event_id}")
def delete_event(session: SessionDep, event_id: uuid.UUID, current_user: CurrentUser) -> Message:
    """
    Delete event
    """
    event = crud.event.get_event_by_id(session=session, event_id=event_id)
    
    if not event:
        raise HTTPException(status_code=404, detail="Event not found")
    
    # Verificar que el evento pertenece a la cuenta del usuario o es admin
    if event.account_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(
            status_code=403, 
            detail="You don't have permission to delete this event"
        )
    
    crud.event.delete_event(session=session, event=event)
    
    return Message(text="Event deleted successfully", type="success")

@router.get("/filter", response_model=EventsOut)
def filter_events(
    *,
    session: SessionDep,
    current_user: CurrentUser,
    has_espai_propi: Optional[bool] = None,
    min_invitats: Optional[int] = None,
    max_invitats: Optional[int] = None,
    min_pressupost: Optional[float] = None,
    max_pressupost: Optional[float] = None,
    days_until: Optional[int] = None,
    tipus: Optional[TipusEvent] = None,
    skip: int = 0,
    limit: int = 100
) -> Any:
    """
    Get all events with filters.
    """
    events, count = crud.event.filter_events(
        session=session,
        account_id=current_user.id,
        has_espai_propi=has_espai_propi,
        min_invitats=min_invitats,
        max_invitats=max_invitats,
        min_pressupost=min_pressupost,
        max_pressupost=max_pressupost,
        days_until=days_until,
        tipus=tipus,
        skip=skip,
        limit=limit
    )
    
    return EventsOut(data=events, count=count)

@router.get("/filter/me", response_model=EventsOut)
def filter_my_events(
    *,
    session: SessionDep,
    current_user: CurrentUser,
    has_espai_propi: Optional[bool] = None,
    min_invitats: Optional[int] = None,
    max_invitats: Optional[int] = None,
    min_pressupost: Optional[float] = None,
    max_pressupost: Optional[float] = None,
    days_until: Optional[int] = None,
    tipus: Optional[TipusEvent] = None,
    skip: int = 0,
    limit: int = 100
) -> Any:
    """
    Get all events belonging to the current user with filters.
    """
    events, count = crud.event.filter_events(
        session=session,
        account_id=current_user.id,
        has_espai_propi=has_espai_propi,
        min_invitats=min_invitats,
        max_invitats=max_invitats,
        min_pressupost=min_pressupost,
        max_pressupost=max_pressupost,
        days_until=days_until,
        tipus=tipus,
        skip=skip,
        limit=limit,
        only_mine=True
    )
    
    return EventsOut(data=events, count=count)

@router.get("/by_account/{account_id}", response_model=EventsOut)
def get_events_by_account_id(
    *,
    account_id: uuid.UUID,
    session: SessionDep,
    skip: int = 0,
    limit: int = 100
) -> EventsOut:
    """
    Get all events for a specific account by ID
    """
    events, count = crud.event.get_events_by_account(
        session=session,
        account_id=account_id,
        skip=skip,
        limit=limit
    )
    
    return EventsOut(data=events, count=count) 