"""
Email service for billing notifications
"""
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
import logging

logger = logging.getLogger(__name__)


class BillingEmailService:
    """Service for sending billing-related emails"""
    
    @staticmethod
    def send_payment_confirmation_email(payment, account):
        """
        Send email when user submits manual payment for approval
        """
        subject = f'Payment Confirmation Received - Invoice #{payment.invoice.invoice_number}'
        
        context = {
            'account_name': account.name,
            'invoice_number': payment.invoice.invoice_number,
            'amount': payment.amount,
            'currency': payment.currency,
            'payment_method': payment.get_payment_method_display(),
            'manual_reference': payment.manual_reference,
            'created_at': payment.created_at,
        }
        
        # Plain text message
        message = f"""
Hi {account.name},

We have received your payment confirmation for Invoice #{payment.invoice.invoice_number}.

Payment Details:
- Amount: {payment.currency} {payment.amount}
- Payment Method: {payment.get_payment_method_display()}
- Reference: {payment.manual_reference}
- Submitted: {payment.created_at.strftime('%Y-%m-%d %H:%M')}

Your payment is currently under review. You will receive another email once it has been approved.

Thank you,
The Igny8 Team
        """
        
        try:
            send_mail(
                subject=subject,
                message=message.strip(),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[account.billing_email or account.owner.email],
                fail_silently=False,
            )
            logger.info(f'Payment confirmation email sent for Payment {payment.id}')
        except Exception as e:
            logger.error(f'Failed to send payment confirmation email: {str(e)}')
    
    @staticmethod
    def send_payment_approved_email(payment, account, subscription):
        """
        Send email when payment is approved and account activated
        """
        subject = f'Payment Approved - Account Activated'
        
        context = {
            'account_name': account.name,
            'invoice_number': payment.invoice.invoice_number,
            'amount': payment.amount,
            'currency': payment.currency,
            'plan_name': subscription.plan.name if subscription else 'N/A',
            'approved_at': payment.approved_at,
        }
        
        message = f"""
Hi {account.name},

Great news! Your payment has been approved and your account is now active.

Payment Details:
- Invoice: #{payment.invoice.invoice_number}
- Amount: {payment.currency} {payment.amount}
- Plan: {subscription.plan.name if subscription else 'N/A'}
- Approved: {payment.approved_at.strftime('%Y-%m-%d %H:%M')}

You can now access all features of your plan. Log in to get started!

Dashboard: {settings.FRONTEND_URL}/dashboard

Thank you,
The Igny8 Team
        """
        
        try:
            send_mail(
                subject=subject,
                message=message.strip(),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[account.billing_email or account.owner.email],
                fail_silently=False,
            )
            logger.info(f'Payment approved email sent for Payment {payment.id}')
        except Exception as e:
            logger.error(f'Failed to send payment approved email: {str(e)}')
    
    @staticmethod
    def send_payment_rejected_email(payment, account, reason):
        """
        Send email when payment is rejected
        """
        subject = f'Payment Declined - Action Required'
        
        message = f"""
Hi {account.name},

Unfortunately, we were unable to approve your payment for Invoice #{payment.invoice.invoice_number}.

Reason: {reason}

Payment Details:
- Invoice: #{payment.invoice.invoice_number}
- Amount: {payment.currency} {payment.amount}
- Reference: {payment.manual_reference}

You can retry your payment by logging into your account:
{settings.FRONTEND_URL}/billing

If you have questions, please contact our support team.

Thank you,
The Igny8 Team
        """
        
        try:
            send_mail(
                subject=subject,
                message=message.strip(),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[account.billing_email or account.owner.email],
                fail_silently=False,
            )
            logger.info(f'Payment rejected email sent for Payment {payment.id}')
        except Exception as e:
            logger.error(f'Failed to send payment rejected email: {str(e)}')
    
    @staticmethod
    def send_refund_notification(user, payment, refund_amount, reason):
        """
        Send email when refund is processed
        """
        subject = f'Refund Processed - Invoice #{payment.invoice.invoice_number}'
        
        message = f"""
Hi {user.first_name or user.email},

Your refund has been processed successfully.

Refund Details:
- Invoice: #{payment.invoice.invoice_number}
- Original Amount: {payment.currency} {payment.amount}
- Refund Amount: {payment.currency} {refund_amount}
- Reason: {reason}
- Processed: {payment.refunded_at.strftime('%Y-%m-%d %H:%M')}

The refund will appear in your original payment method within 5-10 business days.

If you have any questions, please contact our support team.

Thank you,
The Igny8 Team
        """
        
        try:
            send_mail(
                subject=subject,
                message=message.strip(),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                fail_silently=False,
            )
            logger.info(f'Refund notification email sent for Payment {payment.id}')
        except Exception as e:
            logger.error(f'Failed to send refund notification email: {str(e)}')
    
    @staticmethod
    def send_subscription_renewal_notice(subscription, days_until_renewal):
        """
        Send email reminder before subscription renewal
        """
        subject = f'Subscription Renewal Reminder - {days_until_renewal} Days'
        
        account = subscription.account
        user = account.owner
        
        message = f"""
Hi {account.name},

Your subscription will be renewed in {days_until_renewal} days.

Subscription Details:
- Plan: {subscription.plan.name}
- Renewal Date: {subscription.current_period_end.strftime('%Y-%m-%d')}
- Amount: {subscription.plan.currency} {subscription.plan.price}

Your payment method will be charged automatically on the renewal date.

To manage your subscription or update payment details:
{settings.FRONTEND_URL}/billing/subscription

Thank you,
The Igny8 Team
        """
        
        try:
            send_mail(
                subject=subject,
                message=message.strip(),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[account.billing_email or user.email],
                fail_silently=False,
            )
            logger.info(f'Renewal notice sent for Subscription {subscription.id}')
        except Exception as e:
            logger.error(f'Failed to send renewal notice: {str(e)}')

