from flask import Blueprint, render_template, redirect, url_for, flash, request, current_app
from flask_login import current_user
from werkzeug.utils import secure_filename
from cpm_assessment import db, bcrypt
from cpm_assessment.decorators import active_user_required
from cpm_assessment.forms import UpdateProfileForm, ChangePasswordForm, ConsultantProfileForm
import os
import secrets

profile_bp = Blueprint('profile', __name__)

def save_logo(form_logo):
    """Save uploaded logo file and return filename"""
    if form_logo:
        random_hex = secrets.token_hex(8)
        _, f_ext = os.path.splitext(form_logo.filename)
        logo_fn = random_hex + f_ext
        logo_path = os.path.join(current_app.root_path, 'static', 'logos', logo_fn)
        
        # Create logos directory if it doesn't exist
        os.makedirs(os.path.dirname(logo_path), exist_ok=True)
        
        form_logo.save(logo_path)
        return logo_fn
    return None

@profile_bp.route('/profile')
@active_user_required
def view_profile():
    return render_template('profile/view.html', user=current_user)

@profile_bp.route('/profile/edit', methods=['GET', 'POST'])
@active_user_required
def edit_profile():
    form = UpdateProfileForm(obj=current_user)
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.email = form.email.data
        current_user.mobile_number = form.mobile_number.data
        db.session.commit()
        flash('Your profile has been updated.', 'success')
        return redirect(url_for('profile.view_profile'))
    return render_template('profile/edit.html', form=form)

@profile_bp.route('/consultant/profile', methods=['GET', 'POST'])
@active_user_required
def consultant_profile():
    if current_user.role != 'consultant':
        flash('Access denied. This page is for consultants only.', 'danger')
        return redirect(url_for('profile.view_profile'))
    
    form = ConsultantProfileForm()
    
    # Pre-populate form with existing data
    if request.method == 'GET':
        form.registration_number.data = current_user.registration_number
        form.contact_details.data = current_user.contact_details
    
    if form.validate_on_submit():
        current_user.registration_number = form.registration_number.data
        current_user.contact_details = form.contact_details.data
        
        # Handle logo upload
        if form.logo.data:
            # Delete old logo if exists
            if current_user.logo_filename:
                old_logo_path = os.path.join(current_app.root_path, 'static', 'logos', current_user.logo_filename)
                if os.path.exists(old_logo_path):
                    os.remove(old_logo_path)
            
            # Save new logo
            logo_filename = save_logo(form.logo.data)
            current_user.logo_filename = logo_filename
        
        db.session.commit()
        flash('Your consultant profile has been updated successfully!', 'success')
        return redirect(url_for('profile.consultant_profile'))
    
    return render_template('profile/consultant_profile.html', form=form, user=current_user)

@profile_bp.route('/change-password', methods=['GET', 'POST'])
@active_user_required
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if bcrypt.check_password_hash(current_user.password, form.old_password.data):
            hashed_password = bcrypt.generate_password_hash(form.new_password.data).decode('utf-8')
            current_user.password = hashed_password
            db.session.commit()
            try:
                from app.utils import send_email
                html_admin = render_template(
                    'email/password_change_notification.html',
                    recipient_name="Admin",
                    username=current_user.username,
                    email=current_user.email,
                    changed_at=""
                )
                send_email(['admin@vrwellness.in', 'swarunimh@gmail.com'], f'Password Changed: {current_user.username}', html_admin)
            except Exception as e:
                # Silent fail; UI feedback still shows success for password change
                print(f"Failed to notify admin about password change: {e}")
            flash('Your password has been updated.', 'success')
            return redirect(url_for('profile.view_profile'))
        else:
            flash('Incorrect old password.', 'danger')
    return render_template('profile/change_password.html', form=form)
