from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required
from sqlalchemy import or_, select

from web_application import bcrypt, db
from web_application.admin.kullanici.forms import (
    KullaniciDuzenlemeFormu,
    KullaniciEklemeFormu,
)
from web_application.models import Kullanici

ad_kullanici = Blueprint(
    "ad_kullanici",
    __name__,
    template_folder="templates",
    static_folder="static",
    url_prefix="/admin/kullanicilar",
)


# @ad_kullanici.app_errorhandler(404)
# def error_404(error):
#     return render_template("/errors/404.html"), 404


@ad_kullanici.before_request
def check_admin_role():
    if not current_user.is_authenticated:
        flash(
            "Sayfayı görüntüleyebilmek için giriş yapın.",
            "danger",
        )
        return redirect(url_for("kullanici.giris"))
    if current_user.seviye not in ["Admin", "Super Admin"]:
        flash(
            "Bu sayfaya giriş yetkiniz bulunmamaktadır. Lütfen giriş yapın ya da yetkiniz dahilinde bir sayfaya gidin.",
            "danger",
        )

        return redirect(url_for("ana.index"))


@ad_kullanici.route("/")
@ad_kullanici.route("/index")
@login_required
def kullanici_listesi():
    sql = (
        select(Kullanici)
        .where(Kullanici.durum != 9)
        .order_by(Kullanici.olusturma_ts.asc())
    )
    kullanicilar = db.session.execute(sql).scalars().all()
    data = {
        "title": "Kullanıcılar",
        "subtitle": "Sistemdeki kullanıcılar",
        "kullanicilar": kullanicilar,
    }
    return render_template("kullanici/list.html", **data)


@ad_kullanici.route("/ekle", methods=["GET", "POST"])
@login_required
def kullanici_ekle():
    form = KullaniciEklemeFormu()
    if request.method == "POST":
        if form.validate_on_submit():
            sql = select(Kullanici).where(
                or_(
                    Kullanici.eposta == form.eposta.data,
                    Kullanici.telefon == form.telefon.data,
                )
            )
            mevcut_kullanici = db.session.execute(sql).scalars().first()
            if not mevcut_kullanici:
                yeni_kullanici = Kullanici(
                    ad_soyad=form.ad_soyad.data,
                    eposta=form.eposta.data,
                    telefon=form.telefon.data,
                    parola=bcrypt.generate_password_hash(form.parola.data),
                    rol_num=form.rol_num.data,
                )
                try:
                    db.session.add(yeni_kullanici)
                    db.session.commit()
                    flash("Kullanıcı başarıyla oluşturuldu!", "success")
                    return redirect(url_for("ad_kullanici.kullanici_listesi"))
                except Exception as e:
                    db.session.rollback()
                    flash(f"Hata oluştu: {str(e)}", "danger")
            else:
                flash("Telefon ya da e-posta zaten kullanılıyor.", "danger")
        else:
            flash(f"{form.ad_soyad.data} adlı kullanıcı eklenemedi", "danger")
    data = {
        "title": "Kullanıcı Ekle",
        "subtitle": "Sistem için yeni bir kullanıcı ekleyin.",
        "form": form,
    }
    return render_template("kullanici/form.html", **data)


@ad_kullanici.route("/duzenle/<int:kullanici_id>", methods=["GET", "POST"])
@login_required
def kullanici_duzenle(kullanici_id):
    sql = select(Kullanici).where(Kullanici.id == kullanici_id)
    kullanici = db.session.execute(sql).scalars().first()
    form = KullaniciDuzenlemeFormu(obj=kullanici)  # Formu mevcut verilerle doldur

    if form.validate_on_submit():
        kullanici.ad_soyad = form.ad_soyad.data
        kullanici.eposta = form.eposta.data
        kullanici.telefon = form.telefon.data
        kullanici.rol_num = form.rol_num.data

        if form.parola.data:
            kullanici.parola = bcrypt.generate_password_hash(form.parola.data)

        try:
            db.session.commit()
            flash("Kullanıcı güncellendi.", "info")
        except Exception as _:
            db.session.rollback()
            flash("Güncelleme sırasında bir hata oluştu.", "danger")
        return redirect(url_for("ad_kullanici.kullanici_listesi"))
    data = {
        "title": "Kullanıcı Düzenle",
        "subtitle": "Sistem için yeni bir kullanıcı düzenleyin.",
        "form": form,
    }
    return render_template("kullanici/form_edit.html", **data)


@ad_kullanici.route("/sil/<int:kullanici_id>")
@login_required
def kullanici_sil(kullanici_id):

    sql = select(Kullanici).where(Kullanici.id == kullanici_id)
    kullanici = db.session.execute(sql).scalars().first()
    try:
        kullanici.durum = 9
        db.session.commit()
        flash("Kullanıcı silindi.", "warning")
    except Exception as _:
        db.session.rollback()
        flash("Silme işlemi başarısız.", "danger")
    return redirect(url_for("ad_kullanici.kullanici_listesi"))
