from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from datetime import datetime
from urllib.parse import quote


class EmailService:
    @staticmethod
    def _send(template, subject, context, to_email):
        """Send an HTML email using a template."""
        try:
            html_message = render_to_string(template, context)
            plain_message = strip_tags(html_message)
            send_mail(
                subject,
                plain_message,
                settings.DEFAULT_FROM_EMAIL,
                [to_email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
        except Exception as e:
            print(f"Error sending email: {e}")
            return False

    @staticmethod
    def _build_urls(appointment, business):
        site = settings.SITE_URL.rstrip('/')
        edit_url = f'{site}/appointment/edit/{appointment.edit_token}/'
        ics_url = f'{site}/appointment/{appointment.edit_token}/ics/'

        start_dt = datetime.combine(appointment.date, appointment.start_time)
        end_dt = datetime.combine(appointment.date, appointment.end_time)
        fmt = '%Y%m%dT%H%M%S'

        details_parts = [f'Cita en {business.name} - {appointment.appointment_type.name}']
        if appointment.resource:
            details_parts.append(f'Profesional: {appointment.resource.name}')
        details = '\n'.join(details_parts)

        google_url = (
            f'https://calendar.google.com/calendar/render?action=TEMPLATE'
            f'&text={quote(appointment.appointment_type.name)}'
            f'&dates={start_dt.strftime(fmt)}/{end_dt.strftime(fmt)}'
            f'&details={quote(details)}'
            f'&location={quote(business.address or "")}'
            f'&ctz={quote(business.timezone or "America/Santiago")}'
        )

        return edit_url, ics_url, google_url

    @staticmethod
    def send_appointment_confirmation(appointment, business):
        """Envía email de confirmación de cita al cliente."""
        subject = f'Confirmación de tu cita en {business.name}'
        edit_url, ics_url, google_url = EmailService._build_urls(appointment, business)
        context = {
            'appointment': appointment,
            'business': business,
            'edit_url': edit_url,
            'ics_url': ics_url,
            'google_calendar_url': google_url,
        }
        return EmailService._send('booking/emails/appointment_confirmation.html', subject, context, appointment.email)

    @staticmethod
    def send_appointment_cancellation(appointment, business):
        """Envía email de cancelación de cita al cliente."""
        subject = f'Cita cancelada en {business.name}'
        context = {'appointment': appointment, 'business': business}
        return EmailService._send('booking/emails/appointment_cancelled.html', subject, context, appointment.email)

    @staticmethod
    def send_owner_notification(appointment, business):
        """Notifica al dueño del negocio que alguien agendó una cita."""
        subject = f'Nueva cita: {appointment.full_name} - {appointment.appointment_type.name}'
        context = {'appointment': appointment, 'business': business}
        return EmailService._send('booking/emails/owner_notification.html', subject, context, business.user.email)

    @staticmethod
    def send_appointment_reminder(appointment, business, hours_before=24):
        """Envía recordatorio de cita al cliente."""
        subject = f'Recordatorio: Tu cita en {business.name} es pronto'
        context = {
            'appointment': appointment,
            'business': business,
            'hours_before': hours_before,
        }
        return EmailService._send('booking/emails/appointment_reminder.html', subject, context, appointment.email)