"""Service for sending emails using Resend."""

import base64
from pathlib import Path
from typing import Optional
import logging

import resend
from jinja2 import Environment, FileSystemLoader

from app.config import settings
from app.models.application import Application
from app.models.waitlist import Waitlist

# Initialize Resend
resend.api_key = settings.resend_key

# Setup Jinja2 environment for email templates
template_dir = Path(__file__).parent.parent.parent / "templates" / "emails"
env = Environment(loader=FileSystemLoader(str(template_dir)))

logger = logging.getLogger(__name__)

SENDER_NAME = "Proconnect Open University"


class EmailService:
    """Service for sending emails via Resend."""

    @staticmethod
    def send_email(
        to: str | list[str],
        subject: str,
        html_content: str,
        from_email: Optional[str] = None,
        from_name: Optional[str] = None,
        attachments: Optional[list] = None,
    ) -> dict:
        """Send an email using Resend."""
        # Check if Resend API key is configured
        if not settings.resend_key:
            return {
                "success": False,
                "error": "Resend API key not configured. Email will not be sent."
            }
        
        if isinstance(to, str):
            to = [to]
        
        params = {
            "from": f"{from_name or SENDER_NAME} <{from_email or settings.mail_from_address}>",
            "to": to,
            "subject": subject,
            "html": html_content,
        }
        
        if attachments:
            params["attachments"] = attachments
        
        try:
            email = resend.Emails.send(params)
            import logging
            logger = logging.getLogger(__name__)
            logger.info(f"Email sent successfully to {to}. Resend ID: {email.get('id')}")
            return {"success": True, "id": email.get("id")}
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to send email to {to}: {str(e)}", exc_info=True)
            return {"success": False, "error": str(e)}

    @staticmethod
    def send_confirmation_email(application: Application) -> dict:
        """Send application confirmation email."""
        try:
            template = env.get_template("application_confirmation.html")
            html_content = template.render(
                application=application,
                application_id=application.application_id,
            )
        except Exception as template_error:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to load email template: {str(template_error)}")
            # Fallback to simple HTML email if template fails
            html_content = f"""
            <html>
            <body>
                <h2>Application Received - {application.application_id}</h2>
                <p>Dear {application.first_name} {application.last_name},</p>
                <p>Thank you for submitting your application to Proconnect Open University.</p>
                <p>Your application ID is: <strong>{application.application_id}</strong></p>
                <p>Our admissions team will review your application and contact you via email with the outcome shortly.</p>
                <p>Best regards,<br>Proconnect Open University</p>
            </body>
            </html>
            """
        
        return EmailService.send_email(
            to=application.email,
            subject=f"Application Received - {application.application_id}",
            html_content=html_content,
        )

    @staticmethod
    def send_admission_email(
        application: Application,
        pdf_path: Optional[str] = None,
        pdf_attachments: Optional[list] = None,
        temporary_password: Optional[str] = None,
        login_url: Optional[str] = None,
    ) -> dict:
        """Send admission letter email with PDF attachment (path, or pre-built attachments with base64 content)."""
        template = env.get_template("admission_letter.html")
        html_content = template.render(
            application=application,
            matric_number=application.matric_number,
            temporary_password=temporary_password or "",
            login_url=login_url or "",
        )
        attachments = pdf_attachments
        if attachments is None and pdf_path and Path(pdf_path).exists():
            with open(pdf_path, "rb") as f:
                pdf_content = f.read()
                attachments = [
                    {
                        "filename": f"admission_letter_{application.application_id}.pdf",
                        "content": pdf_content,
                    }
                ]
        if attachments and not isinstance(attachments[0].get("content"), str):
            attachments = [
                {
                    "filename": a["filename"],
                    "content": base64.b64encode(a["content"]).decode("utf-8")
                    if isinstance(a["content"], bytes)
                    else a["content"],
                }
                for a in attachments
            ]
        return EmailService.send_email(
            to=application.email,
            subject=f"Congratulations! Admission Offer - {application.matric_number}",
            html_content=html_content,
            attachments=attachments,
        )

    @staticmethod
    def send_rejection_email(application: Application, pdf_path: Optional[str] = None) -> dict:
        """Send rejection letter email with PDF attachment."""
        template = env.get_template("rejection_letter.html")
        html_content = template.render(
            application=application,
            rejection_note=application.rejection_note,
        )
        
        attachments = None
        if pdf_path and Path(pdf_path).exists():
            with open(pdf_path, "rb") as f:
                pdf_content = f.read()
                attachments = [
                    {
                        "filename": f"rejection_letter_{application.application_id}.pdf",
                        "content": pdf_content,
                    }
                ]
        
        return EmailService.send_email(
            to=application.email,
            subject=f"Application Update - {application.application_id}",
            html_content=html_content,
            attachments=attachments,
        )

    @staticmethod
    def send_waitlist_confirmation_email(waitlist_entry: Waitlist) -> dict:
        """Send confirmation email when someone joins the waitlist."""
        try:
            template = env.get_template("waitlist_confirmation.html")
            html_content = template.render(
                full_name=waitlist_entry.full_name,
                email=waitlist_entry.email,
            )
        except Exception as template_error:
            logger.error(f"Failed to load waitlist confirmation template: {str(template_error)}")
            # Fallback to simple HTML email if template fails
            html_content = f"""
            <html>
            <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                <div style="background: #10b981; color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
                    <h1>Proconnect Open University</h1>
                </div>
                <div style="background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px;">
                    <p>Dear {waitlist_entry.full_name},</p>
                    <p>Welcome to the Proconnect Open University waitlist! We are thrilled to have you as a 
                    prospective student in our mission to provide affordable, technology-driven education in Nigeria.</p>
                    <p>Your interest in our <strong>BSc Programmes</strong> has been successfully recorded. 
                    We will notify you via this email ({waitlist_entry.email}) as soon as the admission window officially opens.</p>
                    <p>In the meantime, feel free to visit our website to learn more about our courses and flexible payment plans.</p>
                    <div style="text-align: center; margin: 30px 0;">
                        <a href="https://proconnect-edu.online" 
                           style="background: #10b981; color: white; padding: 15px 30px; 
                                  text-decoration: none; border-radius: 8px; font-weight: bold;">
                            Visit Website
                        </a>
                    </div>
                    <p style="font-style: italic;">Best regards,</p>
                    <p>Admissions Office<br>Proconnect Open University</p>
                </div>
            </body>
            </html>
            """
        
        return EmailService.send_email(
            to=waitlist_entry.email,
            subject="Welcome to Proconnect Open University Waitlist!",
            html_content=html_content,
        )

    @staticmethod
    def send_waitlist_invitation_email(waitlist_entry: Waitlist) -> dict:
        """Send admission invitation email to a waitlist entry. Apply link includes ref=waitlist_id for prefill."""
        apply_url = f"{settings.frontend_base_url.rstrip('/')}/apply?ref={waitlist_entry.id}"
        try:
            template = env.get_template("waitlist_invitation.html")
            html_content = template.render(
                full_name=waitlist_entry.full_name,
                email=waitlist_entry.email,
                apply_url=apply_url,
            )
        except Exception as template_error:
            logger.error(f"Failed to load waitlist invitation template: {str(template_error)}")
            # Fallback to simple HTML email if template fails
            html_content = f"""
            <html>
            <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                <div style="background: #10b981; color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
                    <h1>Proconnect Open University</h1>
                    <p>Admission Window Now Open</p>
                </div>
                <div style="background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px;">
                    <h2>Dear {waitlist_entry.full_name},</h2>
                    <p>Thank you for joining our waitlist! We are thrilled to announce that the admission cycle 
                    for the new academic session is now <strong>OFFICIALLY OPEN</strong>.</p>
                    <p>Complete your application today for our affordable, world-class BSc programs. 
                    <strong>No JAMB is required for admission.</strong></p>
                    <div style="text-align: center; margin: 30px 0;">
                        <a href="{apply_url}" 
                           style="background: #10b981; color: white; padding: 15px 30px; 
                                  text-decoration: none; border-radius: 8px; font-weight: bold;">
                            Start Your Application Now
                        </a>
                    </div>
                    <p>Monthly Tuition: <strong>₦8,500</strong> - No hidden fees!</p>
                    <p>Best regards,<br><strong>Proconnect Open University</strong><br>Admissions Team</p>
                </div>
            </body>
            </html>
            """
        
        return EmailService.send_email(
            to=waitlist_entry.email,
            subject="Admission Window Now Open - Proconnect Open University",
            html_content=html_content,
        )

    @staticmethod
    def send_waitlist_followup_email(waitlist_entry: Waitlist, followup_count: int = 1) -> dict:
        """Send follow-up reminder email to a waitlist entry. Apply link includes ref=waitlist_id for prefill."""
        apply_url = f"{settings.frontend_base_url.rstrip('/')}/apply?ref={waitlist_entry.id}"
        try:
            template = env.get_template("waitlist_followup.html")
            html_content = template.render(
                full_name=waitlist_entry.full_name,
                email=waitlist_entry.email,
                followup_count=followup_count,
                apply_url=apply_url,
            )
        except Exception as template_error:
            logger.error(f"Failed to load waitlist follow-up template: {str(template_error)}")
            # Fallback to simple HTML email if template fails
            html_content = f"""
            <html>
            <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                <div style="background: #f59e0b; color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
                    <h1>Proconnect Open University</h1>
                    <p>Friendly Reminder</p>
                </div>
                <div style="background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px;">
                    <h2>Dear {waitlist_entry.full_name},</h2>
                    <p>We noticed you haven't started your application yet. Your interest in Proconnect Open University 
                    means a lot to us, and we'd love to see you in our next cohort!</p>
                    <div style="background: #fef3c7; padding: 15px; border-left: 4px solid #f59e0b; margin: 20px 0;">
                        <strong>Don't Miss Out!</strong><br>
                        Your spot on our waitlist is still reserved. Secure your place today!
                    </div>
                    <p><strong>This is Follow-up #{followup_count}</strong></p>
                    <div style="text-align: center; margin: 30px 0;">
                        <a href="{apply_url}" 
                           style="background: #dc2626; color: white; padding: 15px 30px; 
                                  text-decoration: none; border-radius: 8px; font-weight: bold;">
                            Complete Your Application Now
                        </a>
                    </div>
                    <p>Need help? Contact us at +234 808 462 9437</p>
                    <p>Best regards,<br><strong>Proconnect Open University</strong><br>Admissions Team</p>
                </div>
            </body>
            </html>
            """
        
        return EmailService.send_email(
            to=waitlist_entry.email,
            subject="Reminder: Your Spot is Still Available - Proconnect Open University",
            html_content=html_content,
        )

    @staticmethod
    def send_agency_onboarding_email(
        contact_person: str,
        agency_name: str,
        partner_email: str,
        discovery_booking_url: str,
        booking_deadline_date: str,
    ) -> dict:
        """Send agency onboarding email with discovery session booking link."""
        from datetime import datetime
        current_date = datetime.utcnow().strftime("%B %d, %Y")
        try:
            template = env.get_template("agency_onboarding.html")
            html_content = template.render(
                contact_person=contact_person,
                agency_name=agency_name,
                partner_email=partner_email,
                discovery_booking_url=discovery_booking_url,
                booking_deadline_date=booking_deadline_date,
                current_date=current_date,
            )
        except Exception as template_error:
            logger.error(f"Failed to load agency onboarding template: {str(template_error)}")
            html_content = f"""
            <html>
            <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                <h2>Application Received - {agency_name}</h2>
                <p>Dear {contact_person},</p>
                <p>Congratulations! Your agency has been successfully registered in our National Licensed Agency Network.</p>
                <p>Book your mandatory Discovery Session within 48 hours: <a href="{discovery_booking_url}">Book Discovery Session</a></p>
                <p>Best regards,<br>Proconnect Open University</p>
            </body>
            </html>
            """
        return EmailService.send_email(
            to=partner_email,
            subject="Application Received - Book Your Discovery Session | Proconnect Open University",
            html_content=html_content,
        )

    @staticmethod
    def send_discovery_session_booked_email(
        *,
        partner_name: str,
        partner_email: str,
        contact_person: str,
        scheduled_date: str,
        scheduled_time: str,
        calendar_link: str,
        admin_email: str = "info@proconnect-edu.online",
    ) -> list:
        """
        Send discovery session confirmation to both the partner and admin.
        Advises recipients to set a reminder on Google Calendar.
        Returns list of send results.
        """
        if not calendar_link:
            logger.warning("Discovery session booked but no calendar link; skipping emails.")
            return []

        try:
            template = env.get_template("discovery_session_booked.html")
        except Exception as template_error:
            logger.error("Failed to load discovery_session_booked template: %s", template_error)
            return []

        results = []

        # Partner email
        partner_html = template.render(
            greeting=f"Dear {contact_person},",
            intro=f"Your Discovery Session for <strong>{partner_name}</strong> has been confirmed. See the details below and add the event to your calendar with a reminder.",
            partner_name=partner_name,
            scheduled_date=scheduled_date,
            scheduled_time=scheduled_time,
            calendar_link=calendar_link,
        )
        r1 = EmailService.send_email(
            to=partner_email,
            subject=f"Discovery Session Confirmed - {scheduled_date} at {scheduled_time} | POU",
            html_content=partner_html,
        )
        results.append({"to": partner_email, "result": r1})

        # Admin email
        admin_html = template.render(
            greeting="Partners Team,",
            intro=f"A new Discovery Session has been booked by <strong>{partner_name}</strong>. Please add a reminder to your calendar and join the session at the scheduled time.",
            partner_name=partner_name,
            scheduled_date=scheduled_date,
            scheduled_time=scheduled_time,
            calendar_link=calendar_link,
        )
        r2 = EmailService.send_email(
            to=admin_email,
            subject=f"New Discovery Session Booked - {partner_name} | {scheduled_date} {scheduled_time}",
            html_content=admin_html,
        )
        results.append({"to": admin_email, "result": r2})

        return results
