from django.contrib import admin
from django import forms
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from django.template.loader import render_to_string
from django.urls import path
from django.shortcuts import render
from .models import InvitationCode
import logging

logger = logging.getLogger(__name__)


class EmailForm(forms.Form):
    email = forms.EmailField(label='Email del invitado')


@admin.register(InvitationCode)
class InvitationCodeAdmin(admin.ModelAdmin):
    list_display = ['code', 'created_at', 'expires_at', 'is_used', 'used_by']
    list_filter = ['is_used', 'created_at']
    search_fields = ['code']
    readonly_fields = ['code', 'created_at']
    actions = ['create_invitations', 'send_invitation_emails']

    def get_urls(self):
        urls = super().get_urls()
        urls.insert(0, path('send_invitation/', self.admin_site.admin_view(self.send_invitation_view), name='send_invitation'))
        return urls

    def create_invitations(self, request, queryset):
        for _ in range(5):
            InvitationCode.create_invitation(created_by=request.user)
        self.message_user(request, 'Se crearon 5 códigos de invitación.')
    create_invitations.short_description = 'Crear 5 códigos de invitación'

    def send_invitation_emails(self, request, queryset):
        logger.info(f"Iniciando envio de invitacion, query={queryset}")
        if 'apply' in request.POST:
            form = EmailForm(request.POST)
            logger.info(f"Form data: {request.POST}")
            if form.is_valid():
                email = form.cleaned_data['email']
                logger.info(f"Email valido: {email}")
                invitation = InvitationCode.create_invitation(created_by=request.user)
                logger.info(f"Created invitation code: {invitation.code}")
                signup_url = f"https://jugaralpadel.es/accounts/signup/?code={invitation.code}"
                logger.info(f"Signup URL: {signup_url}")
                context = {'invitation_code': invitation.code, 'signup_url': signup_url}
                html_content = render_to_string('emails/invitacion.html', context)
                texto = f'Has recibido una invitación para registrarte en Jugar al Pádel Entre Amigos.\n\nTu código de invitación: {invitation.code}\n\nEnlace: {signup_url}\n\nEste código caduca en 24 horas.'
                from_email = settings.DEFAULT_FROM_EMAIL
                msg = EmailMultiAlternatives(
                    'Invitación a Jugar al Pádel',
                    texto,
                    from_email,
                    [email]
                )
                msg.attach_alternative(html_content, "text/html")
                msg.send()
                logger.info(f"Email enviado a {email}")
                self.message_user(request, f'Invitación enviada a {email}.')
                return None
            else:
                logger.info(f"Form errors: {form.errors}")
        else:
            form = EmailForm()
            logger.info("Mostrando formulario de invitacion")
        return render(request, 'admin/send_invitation.html', {
            'items': queryset,
            'form': form,
            'title': 'Enviar invitación por email'
        })
    send_invitation_emails.short_description = 'Enviar invitación por email'

    def send_invitation_view(self, request):
        return self.send_invitation_emails(request, InvitationCode.objects.none())

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        qs = qs.select_related('used_by', 'created_by')
        return qs