from django.contrib.auth.views import PasswordResetView
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings

class CustomPasswordResetView(PasswordResetView):
    """Custom password reset view that ensures HTML emails are sent properly."""
    
    def send_mail(self, subject_template_name, email_template_name,
                 context, from_email, to_email, html_email_template_name=None):
        """Override send_mail to ensure HTML content is properly sent."""
        subject = render_to_string(subject_template_name, context)
        subject = ''.join(subject.splitlines())  # Remove newlines
        
        # Render the plain text version first
        plain_message = render_to_string(email_template_name, context)
        
        # Add the reset_url to the context for our custom template
        if 'reset_url' not in context and 'uid' in context and 'token' in context:
            protocol = 'https' if self.request.is_secure() else 'http'
            domain = self.request.get_host()
            context['reset_url'] = f"{protocol}://{domain}/reset/{context['uid']}/{context['token']}/"
        
        # Create the email message
        email = EmailMultiAlternatives(
            subject=subject,
            body=plain_message,
            from_email=from_email,
            to=[to_email]
        )
        
        # Use our custom HTML template instead of the default one
        html_message = render_to_string('email/password_reset.html', context)
        email.attach_alternative(html_message, 'text/html')
        
        # Send the email
        email.send(fail_silently=False)
