from flask import Blueprint, render_template, session, request, redirect, url_for
from flask_login import login_required, current_user
import random
import string

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    return render_template('index.html')

@main_bp.route('/rules')
def rules():
    return render_template('rules.html') # Need to create this or just use a placeholder

@main_bp.route('/profile')
@login_required
def profile():
    from models import LinkCode, db
    from datetime import datetime, timedelta
    
    link_code = None
    if not current_user.minecraft_uuid:
        # Check for existing valid code
        existing_code = LinkCode.query.filter_by(user_id=current_user.id).first()
        
        if existing_code and existing_code.expires_at > datetime.utcnow():
            link_code = existing_code.code
        else:
            # Generate new code
            if existing_code:
                db.session.delete(existing_code)
                
            code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
            expires_at = datetime.utcnow() + timedelta(minutes=10)
            
            new_link_code = LinkCode(user_id=current_user.id, code=code, expires_at=expires_at)
            db.session.add(new_link_code)
            db.session.commit()
            link_code = code
            
    return render_template('user/profile.html', user=current_user, link_code=link_code)

@main_bp.route('/apply', methods=['GET', 'POST'])
@login_required
def apply():
    if request.method == 'POST':
        # Save application logic here
        pass
    return render_template('apply.html')

@main_bp.route('/tickets', methods=['GET', 'POST'])
@login_required
def tickets():
    from models import Ticket, TicketAssignment, db
    
    if request.method == 'POST':
        title = request.form.get('title')
        description = request.form.get('description')
        
        if title and description:
            ticket = Ticket(
                user_id=current_user.id,
                title=title,
                description=description
            )
            db.session.add(ticket)
            db.session.commit()
            
            # Automatically assign the creator to the ticket? 
            # Or just rely on creator field. The user said "multiple players... assigned".
            # Let's assign the creator as well so they show up in the "relevant" list easily if we query by assignment.
            # But usually creator is separate.
            # Let's just save it for now.
            
            # If we want to assign admins automatically, we could do it here.
            
            return redirect(url_for('main.tickets'))

    # List tickets relevant to the user:
    # 1. Tickets created by the user
    # 2. Tickets assigned to the user
    
    # Using a union or simple OR query
    # Since we have a separate TicketAssignment model, we can join.
    
    relevant_tickets = Ticket.query.outerjoin(TicketAssignment).filter(
        (Ticket.user_id == current_user.id) | (TicketAssignment.user_id == current_user.id)
    ).all()
    
    return render_template('tickets.html', tickets=relevant_tickets)

@main_bp.route('/tickets/<int:ticket_id>', methods=['GET', 'POST'])
@login_required
def ticket_detail(ticket_id):
    from models import Ticket, TicketComment, TicketAssignment, db
    
    ticket = Ticket.query.get_or_404(ticket_id)
    
    # Access Control
    is_creator = ticket.user_id == current_user.id
    is_assigned = TicketAssignment.query.filter_by(ticket_id=ticket.id, user_id=current_user.id).first() is not None
    is_admin = current_user.is_admin
    
    if not (is_creator or is_assigned or is_admin):
        return render_template('errors/403.html'), 403 # Or just redirect with flash
        
    if request.method == 'POST':
        action = request.form.get('action')
        
        if action == 'comment':
            content = request.form.get('content')
            is_hidden = request.form.get('is_hidden') == 'on'
            
            # Only admins can make hidden comments
            if is_hidden and not is_admin:
                is_hidden = False
                
            if content:
                comment = TicketComment(
                    ticket_id=ticket.id,
                    user_id=current_user.id,
                    content=content,
                    is_hidden=is_hidden
                )
                db.session.add(comment)
                db.session.commit()
                
        elif action == 'close':
            # Only creator or admin can close
            if not (is_creator or is_admin):
                return "Unauthorized", 403
                
            reason = request.form.get('reason')
            if reason:
                ticket.status = 'CLOSED'
                ticket.closing_reason = reason
                ticket.closed_by_id = current_user.id
                db.session.commit()
        
        elif action == 'toggle_hidden':
            if not is_admin:
                return "Unauthorized", 403
            
            comment_id = request.form.get('comment_id')
            comment = TicketComment.query.get(comment_id)
            if comment and comment.ticket_id == ticket.id:
                comment.is_hidden = not comment.is_hidden
                db.session.commit()
                
        return redirect(url_for('main.ticket_detail', ticket_id=ticket.id))
        
    return render_template('ticket_detail.html', ticket=ticket, is_admin=is_admin, is_creator=is_creator)

