"""Email service for sending post approval emails."""
import smtplib
import secrets
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from typing import Optional, Dict, Any
from datetime import datetime, timezone
from uuid import UUID
from loguru import logger

from src.config import settings


async def generate_token(post_id: UUID, action: str, expires_hours: int = 72) -> str:
    """Generate a unique token for email action and persist it to the database."""
    from src.database.client import db
    token = secrets.token_urlsafe(32)
    await db.create_email_token(token, post_id, action, expires_hours)
    return token


async def validate_token(token: str) -> Optional[Dict[str, Any]]:
    """Validate and return token data if valid (checks DB)."""
    from src.database.client import db
    token_data = await db.get_email_token(token)
    if not token_data:
        return None

    if token_data.get("used"):
        return None

    expires_at_raw = token_data.get("expires_at")
    if expires_at_raw:
        if isinstance(expires_at_raw, str):
            expires_at = datetime.fromisoformat(expires_at_raw.replace("Z", "+00:00"))
        else:
            expires_at = expires_at_raw
        if not expires_at.tzinfo:
            expires_at = expires_at.replace(tzinfo=timezone.utc)
        if datetime.now(timezone.utc) > expires_at:
            return None

    return token_data


async def mark_token_used(token: str) -> None:
    """Mark a token as used in the database."""
    from src.database.client import db
    await db.mark_email_token_used(token)


def send_email(to_email: str, subject: str, html_content: str) -> bool:
    """Send an email using SMTP."""
    if not settings.smtp_host or not settings.smtp_user:
        logger.warning("SMTP not configured, skipping email send")
        return False

    try:
        msg = MIMEMultipart("alternative")
        msg["Subject"] = subject
        msg["From"] = f"{settings.smtp_from_name} <{settings.smtp_user}>"
        msg["To"] = to_email

        html_part = MIMEText(html_content, "html")
        msg.attach(html_part)

        with smtplib.SMTP(settings.smtp_host, settings.smtp_port) as server:
            server.starttls()
            server.login(settings.smtp_user, settings.smtp_password)
            server.sendmail(settings.smtp_user, to_email, msg.as_string())

        logger.info(f"Email sent to {to_email}: {subject}")
        return True
    except Exception as e:
        logger.error(f"Failed to send email to {to_email}: {e}")
        return False


def send_email_with_attachment(
    to_email: str,
    subject: str,
    html_content: str,
    attachment_bytes: bytes,
    attachment_filename: str,
) -> bool:
    """Send an email with a file attachment (e.g. PDF)."""
    if not settings.smtp_host or not settings.smtp_user:
        logger.warning("SMTP not configured, skipping email send")
        return False

    try:
        msg = MIMEMultipart("mixed")
        msg["Subject"] = subject
        msg["From"] = f"{settings.smtp_from_name} <{settings.smtp_user}>"
        msg["To"] = to_email

        # HTML body
        alt_part = MIMEMultipart("alternative")
        alt_part.attach(MIMEText(html_content, "html"))
        msg.attach(alt_part)

        # Attachment
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment_bytes)
        encoders.encode_base64(part)
        part.add_header("Content-Disposition", f'attachment; filename="{attachment_filename}"')
        msg.attach(part)

        with smtplib.SMTP(settings.smtp_host, settings.smtp_port) as server:
            server.starttls()
            server.login(settings.smtp_user, settings.smtp_password)
            server.sendmail(settings.smtp_user, to_email, msg.as_string())

        logger.info(f"Email with attachment sent to {to_email}: {subject}")
        return True
    except Exception as e:
        logger.error(f"Failed to send email with attachment to {to_email}: {e}")
        return False


async def send_approval_request_email(
    to_email: str,
    post_id: UUID,
    post_title: str,
    post_content: str,
    base_url: str,
    image_url: Optional[str] = None
) -> bool:
    """Send email to customer requesting approval of a post."""
    approve_token = await generate_token(post_id, "approve")
    reject_token = await generate_token(post_id, "reject")

    approve_url = f"{base_url}/api/email-action/{approve_token}"
    reject_url = f"{base_url}/api/email-action/{reject_token}"

    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
            .header {{ background: linear-gradient(135deg, #2d3838 0%, #1a2424 100%); color: white; padding: 24px; }}
            .header h1 {{ margin: 0; font-size: 20px; }}
            .content {{ padding: 24px; }}
            .post-preview {{ background: #f8f9fa; border-left: 4px solid #ffc700; padding: 16px; margin: 20px 0; border-radius: 0 8px 8px 0; white-space: pre-wrap; font-size: 14px; line-height: 1.6; color: #333; }}
            .buttons {{ display: flex; gap: 12px; margin-top: 24px; }}
            .btn {{ display: inline-block; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; text-align: center; }}
            .btn-approve {{ background: #22c55e; color: white; }}
            .btn-reject {{ background: #6b7280; color: white; }}
            .footer {{ padding: 16px 24px; background: #f8f9fa; font-size: 12px; color: #666; text-align: center; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Neuer LinkedIn Post zur Freigabe</h1>
            </div>
            <div class="content">
                <p>Hallo,</p>
                <p>Ein neuer LinkedIn Post wurde erstellt und wartet auf deine Freigabe:</p>

                <p><strong>{post_title}</strong></p>

                <div class="post-preview">{post_content}</div>

                {f'<img src="{image_url}" alt="Post-Bild" style="width: 100%; max-height: 400px; object-fit: cover; border-radius: 8px; margin: 16px 0;" />' if image_url else ''}

                <p>Bitte entscheide, ob der Post veröffentlicht werden soll:</p>

                <div class="buttons">
                    <a href="{approve_url}" class="btn btn-approve">Freigeben</a>
                    <a href="{reject_url}" class="btn btn-reject">Nochmal bearbeiten</a>
                </div>
            </div>
            <div class="footer">
                Diese Email wurde automatisch generiert. Die Links sind 72 Stunden gültig.
            </div>
        </div>
    </body>
    </html>
    """

    return send_email(
        to_email=to_email,
        subject=f"Post zur Freigabe: {post_title}",
        html_content=html_content
    )


def send_invitation_email(
    to_email: str,
    company_name: str,
    inviter_name: str,
    token: str,
    base_url: str
) -> bool:
    """Send invitation email to a new employee."""
    invite_url = f"{base_url}/invite/{token}"

    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
            .header {{ background: linear-gradient(135deg, #2d3838 0%, #1a2424 100%); color: white; padding: 24px; }}
            .header h1 {{ margin: 0; font-size: 20px; }}
            .content {{ padding: 24px; }}
            .company-badge {{ display: inline-block; padding: 8px 16px; border-radius: 20px; background: #ffc700; color: #1a2424; font-weight: 600; margin: 16px 0; }}
            .btn {{ display: inline-block; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; background: #ffc700; color: #1a2424; margin-top: 16px; }}
            .footer {{ padding: 16px 24px; background: #f8f9fa; font-size: 12px; color: #666; text-align: center; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Du wurdest eingeladen!</h1>
            </div>
            <div class="content">
                <p>Hallo,</p>
                <p><strong>{inviter_name}</strong> hat dich eingeladen, dem Team beizutreten:</p>

                <p class="company-badge">{company_name}</p>

                <p>Als Teammitglied kannst du LinkedIn-Posts erstellen, die der Unternehmensstrategie entsprechen.</p>

                <a href="{invite_url}" class="btn">Einladung annehmen</a>

                <p style="margin-top: 24px; font-size: 14px; color: #666;">
                    Oder kopiere diesen Link in deinen Browser:<br>
                    <code style="font-size: 12px; color: #999;">{invite_url}</code>
                </p>
            </div>
            <div class="footer">
                Diese Einladung ist 7 Tage gueltig.
            </div>
        </div>
    </body>
    </html>
    """

    return send_email(
        to_email=to_email,
        subject=f"Einladung von {company_name}",
        html_content=html_content
    )


def send_email_verification(
    to_email: str,
    token: str,
    base_url: str
) -> bool:
    """Send email verification link."""
    verify_url = f"{base_url}/verify-email/{token}"

    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
            .header {{ background: linear-gradient(135deg, #2d3838 0%, #1a2424 100%); color: white; padding: 24px; }}
            .header h1 {{ margin: 0; font-size: 20px; }}
            .content {{ padding: 24px; }}
            .btn {{ display: inline-block; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; background: #ffc700; color: #1a2424; margin-top: 16px; }}
            .footer {{ padding: 16px 24px; background: #f8f9fa; font-size: 12px; color: #666; text-align: center; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>E-Mail bestaetigen</h1>
            </div>
            <div class="content">
                <p>Hallo,</p>
                <p>Bitte bestaetigen deine E-Mail-Adresse, um dein Konto zu aktivieren:</p>

                <a href="{verify_url}" class="btn">E-Mail bestaetigen</a>

                <p style="margin-top: 24px; font-size: 14px; color: #666;">
                    Oder kopiere diesen Link in deinen Browser:<br>
                    <code style="font-size: 12px; color: #999;">{verify_url}</code>
                </p>
            </div>
            <div class="footer">
                Dieser Link ist 24 Stunden gueltig. Falls du dich nicht registriert hast, ignoriere diese E-Mail.
            </div>
        </div>
    </body>
    </html>
    """

    return send_email(
        to_email=to_email,
        subject="E-Mail-Adresse bestaetigen",
        html_content=html_content
    )


def send_welcome_email(
    to_email: str,
    user_name: str,
    account_type: str,
    base_url: str
) -> bool:
    """Send welcome email after registration/onboarding completion."""
    login_url = f"{base_url}/login"

    if account_type == "company":
        account_type_text = "Unternehmens-Konto"
        next_steps = """
        <ul>
            <li>Lade deine Teammitglieder ein</li>
            <li>Verfeinere deine Unternehmensstrategie</li>
            <li>Beginne mit der Post-Erstellung</li>
        </ul>
        """
    elif account_type == "employee":
        account_type_text = "Mitarbeiter-Konto"
        next_steps = """
        <ul>
            <li>Recherchiere neue Topics</li>
            <li>Erstelle deinen ersten Post</li>
        </ul>
        """
    else:
        account_type_text = "Ghostwriter-Konto"
        next_steps = """
        <ul>
            <li>Recherchiere neue Topics</li>
            <li>Erstelle deinen ersten Post</li>
            <li>Passe deine Einstellungen an</li>
        </ul>
        """

    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
            .header {{ background: linear-gradient(135deg, #2d3838 0%, #1a2424 100%); color: white; padding: 24px; }}
            .header h1 {{ margin: 0; font-size: 20px; }}
            .content {{ padding: 24px; }}
            .account-badge {{ display: inline-block; padding: 8px 16px; border-radius: 20px; background: #22c55e; color: white; font-weight: 600; margin: 8px 0; }}
            .btn {{ display: inline-block; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; background: #ffc700; color: #1a2424; margin-top: 16px; }}
            .footer {{ padding: 16px 24px; background: #f8f9fa; font-size: 12px; color: #666; text-align: center; }}
            ul {{ padding-left: 20px; }}
            li {{ margin: 8px 0; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Willkommen bei LinkedIn Posts!</h1>
            </div>
            <div class="content">
                <p>Hallo {user_name},</p>
                <p>Dein Konto wurde erfolgreich eingerichtet!</p>

                <p class="account-badge">{account_type_text}</p>

                <p><strong>Naechste Schritte:</strong></p>
                {next_steps}

                <a href="{login_url}" class="btn">Zum Dashboard</a>
            </div>
            <div class="footer">
                Viel Erfolg mit deinen LinkedIn-Posts!
            </div>
        </div>
    </body>
    </html>
    """

    return send_email(
        to_email=to_email,
        subject="Willkommen bei LinkedIn Posts!",
        html_content=html_content
    )


def send_employee_removal_email(
    to_email: str,
    employee_name: str,
    company_name: str
) -> bool:
    """Send email to notify an employee they have been removed from the company."""
    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
            .header {{ background: linear-gradient(135deg, #dc2626 0%, #991b1b 100%); color: white; padding: 24px; }}
            .header h1 {{ margin: 0; font-size: 20px; }}
            .content {{ padding: 24px; }}
            .company-badge {{ display: inline-block; padding: 8px 16px; border-radius: 20px; background: #f3f4f6; color: #374151; font-weight: 600; margin: 16px 0; }}
            .footer {{ padding: 16px 24px; background: #f8f9fa; font-size: 12px; color: #666; text-align: center; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Konto entfernt</h1>
            </div>
            <div class="content">
                <p>Hallo {employee_name},</p>
                <p>dein Konto wurde aus dem Unternehmen entfernt:</p>

                <p class="company-badge">{company_name}</p>

                <p>Dein Zugang wurde deaktiviert und alle zugehoerigen Daten wurden geloescht.</p>

                <p>Falls du Fragen hast, wende dich bitte an deinen ehemaligen Arbeitgeber.</p>
            </div>
            <div class="footer">
                Diese E-Mail wurde automatisch generiert.
            </div>
        </div>
    </body>
    </html>
    """

    return send_email(
        to_email=to_email,
        subject=f"Dein Konto bei {company_name} wurde entfernt",
        html_content=html_content
    )


def send_company_approval_request_email(
    to_email: str,
    post_title: str,
    post_content: str,
    company_name: str,
    approve_url: str,
    reject_url: str,
    image_url: Optional[str] = None
) -> bool:
    """Send email to employee asking them to approve or reject a company-reviewed post."""
    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
            .header {{ background: linear-gradient(135deg, #2d3838 0%, #1a2424 100%); color: white; padding: 24px; }}
            .header h1 {{ margin: 0; font-size: 20px; }}
            .content {{ padding: 24px; }}
            .company-badge {{ display: inline-block; padding: 8px 16px; border-radius: 20px; background: #ffc700; color: #1a2424; font-weight: 600; margin: 8px 0; }}
            .post-preview {{ background: #f8f9fa; border-left: 4px solid #ffc700; padding: 16px; margin: 20px 0; border-radius: 0 8px 8px 0; white-space: pre-wrap; font-size: 14px; line-height: 1.6; color: #333; }}
            .buttons {{ display: flex; gap: 12px; margin-top: 24px; }}
            .btn {{ display: inline-block; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; text-align: center; }}
            .btn-approve {{ background: #22c55e; color: white; }}
            .btn-reject {{ background: #ef4444; color: white; }}
            .footer {{ padding: 16px 24px; background: #f8f9fa; font-size: 12px; color: #666; text-align: center; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Dein Post wartet auf deine Freigabe</h1>
            </div>
            <div class="content">
                <p>Hallo,</p>
                <p>Das Unternehmen <span class="company-badge">{company_name}</span> hat deinen Post bearbeitet und bittet um deine Freigabe:</p>

                <p><strong>{post_title}</strong></p>

                <div class="post-preview">{post_content}</div>

                {f'<img src="{image_url}" alt="Post-Bild" style="width: 100%; max-height: 400px; object-fit: cover; border-radius: 8px; margin: 16px 0;" />' if image_url else ''}

                <p>Bitte entscheide, ob der Post so veröffentlicht werden soll:</p>

                <div class="buttons">
                    <a href="{approve_url}" class="btn btn-approve">Freigeben</a>
                    <a href="{reject_url}" class="btn btn-reject">Ablehnen</a>
                </div>
            </div>
            <div class="footer">
                Diese Email wurde automatisch generiert. Die Links sind 72 Stunden gültig.
            </div>
        </div>
    </body>
    </html>
    """

    return send_email(
        to_email=to_email,
        subject=f"Freigabe erforderlich: {post_title}",
        html_content=html_content
    )


def send_company_review_notification_email(
    to_email: str,
    post_id: UUID,
    post_title: str,
    company_name: str,
    base_url: str
) -> bool:
    """Send email to employee notifying them the company has reviewed their post."""
    post_url = f"{base_url}/posts/{post_id}"

    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
            .header {{ background: linear-gradient(135deg, #2d3838 0%, #1a2424 100%); color: white; padding: 24px; }}
            .header h1 {{ margin: 0; font-size: 20px; }}
            .content {{ padding: 24px; }}
            .company-badge {{ display: inline-block; padding: 8px 16px; border-radius: 20px; background: #ffc700; color: #1a2424; font-weight: 600; margin: 16px 0; }}
            .btn {{ display: inline-block; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; background: #ffc700; color: #1a2424; margin-top: 16px; }}
            .footer {{ padding: 16px 24px; background: #f8f9fa; font-size: 12px; color: #666; text-align: center; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Dein Post wurde bearbeitet</h1>
            </div>
            <div class="content">
                <p>Hallo,</p>
                <p>Das Unternehmen <span class="company-badge">{company_name}</span> hat deinen Post in Bearbeitung genommen:</p>
                <p><strong>{post_title}</strong></p>
                <p>Der Post wurde in die Spalte "Bearbeitet" verschoben. Du kannst ihn in deinem Dashboard einsehen.</p>
                <a href="{post_url}" class="btn">Post ansehen</a>
            </div>
            <div class="footer">
                Diese Email wurde automatisch generiert.
            </div>
        </div>
    </body>
    </html>
    """

    return send_email(
        to_email=to_email,
        subject=f"Dein Post wurde bearbeitet: {post_title}",
        html_content=html_content
    )


def send_decision_notification_email(
    to_email: str,
    post_title: str,
    decision: str,  # "approved" or "rejected"
    base_url: str,
    post_id: UUID,
    image_url: Optional[str] = None
) -> bool:
    """Send email to creator notifying them of the customer's decision."""
    post_url = f"{base_url}/posts/{post_id}"

    if decision == "approved":
        decision_text = "freigegeben"
        decision_color = "#22c55e"
        action_text = "Der Post wurde in die Spalte 'Freigegeben' verschoben und kann nun im Kalender eingeplant werden."
    else:
        decision_text = "zur Überarbeitung zurückgeschickt"
        decision_color = "#f59e0b"
        action_text = "Der Post wurde zurück in die Spalte 'Vorschläge' verschoben. Bitte überarbeite ihn und sende ihn erneut zur Freigabe."

    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }}
            .container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
            .header {{ background: linear-gradient(135deg, #2d3838 0%, #1a2424 100%); color: white; padding: 24px; }}
            .header h1 {{ margin: 0; font-size: 20px; }}
            .content {{ padding: 24px; }}
            .decision {{ display: inline-block; padding: 8px 16px; border-radius: 20px; font-weight: 600; color: white; background: {decision_color}; margin: 16px 0; }}
            .btn {{ display: inline-block; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; background: #ffc700; color: #1a2424; margin-top: 16px; }}
            .footer {{ padding: 16px 24px; background: #f8f9fa; font-size: 12px; color: #666; text-align: center; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Entscheidung zu deinem Post</h1>
            </div>
            <div class="content">
                <p>Hallo,</p>
                <p>Der Kunde hat eine Entscheidung zu deinem Post getroffen:</p>

                <p><strong>{post_title}</strong></p>

                <p class="decision">{decision_text.upper()}</p>

                {f'<img src="{image_url}" alt="Post-Bild" style="width: 100%; max-height: 400px; object-fit: cover; border-radius: 8px; margin: 16px 0;" />' if image_url else ''}

                <p>{action_text}</p>

                <a href="{post_url}" class="btn">Post ansehen</a>
            </div>
            <div class="footer">
                Diese Email wurde automatisch generiert.
            </div>
        </div>
    </body>
    </html>
    """

    return send_email(
        to_email=to_email,
        subject=f"Post {decision_text}: {post_title}",
        html_content=html_content
    )
