import re

from flask import render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from sqlalchemy.exc import IntegrityError


from extensions import db
from models import User
from . import bp

@bp.get("/register")
def register_form():
    if current_user.is_authenticated: 
        return redirect(url_for("playlist.home"))
    return render_template("auth/register.html")


@bp.post("/register")
def register():
    username = request.form.get("username", "").strip()
    email = request.form.get("email", "").strip().lower()
    password = request.form.get("password", "").strip()
    confirm = request.form.get("confirm", "").strip()

    if not all([username,email,password, confirm]):
        flash("Fill in every field!", "error")
        return redirect(url_for("auth.register_form"))
    
    email_regex = r"^[\w\.-]+@[\w\.-]+\.\w+$"
    if not re.match(email_regex, email):
        flash("invalid email address!", "error")
        return redirect(url_for("auth.register"))
    
    if password != confirm:
        flash("invalid password", "error")
        return redirect(url_for("auth.register_form"))
    
    if not re.search(r"[A-Z]", password):
        flash("invalid password", "error")
        return redirect(url_for("auth.register"))
    
    if not re.search(r"[a-z]", password):
        flash("invalid password", "error")
        return redirect(url_for("register"))
    
    if not re.search(r"\d", password):
        flash("invalid password", "error")
        return redirect(url_for("auth.register"))
    
    exiting_user = User.query.filter_by(email=email).first()

    if exiting_user:
        flash("User already exits!", "error")
        return redirect(url_for("auth.register"))

    user = User(username=username, email=email)

    try: 
        user.set_password(password)
    except  ValueError as e:
        flash(str(e), "error")
        return redirect(url_for("auth.register_form"))
    
    try: 
        db.session.add(user)
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        flash("Username or email already registerd", "error")
        return redirect(url_for("auth.register_form"))
    
    flash("Account has been created!", "success")
    return redirect(url_for("auth.login_form"))


@bp.get("/login")
def login_form():
    if current_user.is_authenticated:
        return redirect(url_for("playlist.home"))
    return render_template("auth/login.html")


@bp.post("/login")
def login():
    email = request.form.get("email", "").strip().lower()
    password = request.form.get("password", "")

    user = User.query.filter_by(email=email).first()

    if not user or not user.check_password(password):
        flash("wrong email or password", "error")
        return redirect(url_for("auth.login_form"))
    
    login_user(user)

    next_page = request.args.get("next")
    return redirect(next_page or url_for("playlist.home"))


@bp.get("/logout")
def logout():
    logout_user()
    flash("You are now logged out!", "error")
    return redirect(url_for("auth.login_form"))
