from django.contrib import admin
from django.core.mail import send_mail
from django.contrib import messages

from django.contrib.auth.admin import UserAdmin

# Register your models here.

from reymotausers.models import ReyMotaUser
from reymotausers.forms import ReyMotaUserCreationForm, ReyMotaUserChangeForm


def enviar_email_prueba(modeladmin, request, queryset):
    for user in queryset:
        if user.email:
            send_mail(
                'Correo de Prueba',
                'Este es un correo de prueba desde el panel de administración.',
                'jugaralpadelentreamigos@gmail.com',  # Remitente
                [user.email],  # Destinatario
                fail_silently=False,
            )
            messages.success(request, f'Se ha enviado un correo de prueba a {user.email}')
        else:
            messages.warning(request, f'El usuario {user.username} no tiene un correo registrado.')


enviar_email_prueba.short_description = 'Enviar correo de prueba a usuario(s) seleccionado(s)'


class ReyMotaUserAdmin(UserAdmin):
    add_form = ReyMotaUserCreationForm
    form = ReyMotaUserChangeForm
    model = ReyMotaUser
    list_display = ("email", "nombre", "is_staff", "is_active", "foto")
    list_filter = ("email", "nombre", "is_staff", "is_active",)
    fieldsets = (
        (None, {"fields": ("email", "password")}),
        ("Personal", {"fields": ("nombre",)}),
        ("Permissions", {"fields": ("is_staff", "is_active", "groups",
                                    "user_permissions")}),
        ("Varios", {"fields": ("foto",)}),
    )
    add_fieldsets = (
        (
            None,
            {
                "classes": ("wide",),
                "fields": (
                    "email", "password1", "password2", "is_staff",
                    "is_active", "groups", "user_permissions"
                )
            }
        ),

        ("Personal", {"fields": ("nombre",)}),
        ("Varios", {"fields": ("foto",)}),
    )
    search_fields = ("email", "nombre",)
    ordering = ("email",)
    actions = [enviar_email_prueba]  # Añadir la acción a la lista de acciones


admin.site.register(ReyMotaUser, ReyMotaUserAdmin)
