"""Jinja2 HTML email templates for notification emails."""

from __future__ import annotations

from jinja2 import Environment, BaseLoader

_COMMON_STYLES = """
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 0; background: #f5f5f5; }
  .container { max-width: 600px; margin: 20px auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
  .header { background: #1e293b; color: #ffffff; padding: 24px; }
  .header h1 { margin: 0; font-size: 20px; }
  .header .subtitle { color: #94a3b8; font-size: 14px; margin-top: 4px; }
  .content { padding: 24px; }
  .doc-badge { display: inline-block; background: #3b82f6; color: white; padding: 4px 12px; border-radius: 4px; font-weight: 600; font-size: 14px; }
  .footer { padding: 16px 24px; background: #f8fafc; border-top: 1px solid #e2e8f0; font-size: 12px; color: #94a3b8; }
"""

# --- 1. Change notification: sent when a watched column changes during sync ---
_CHANGE_NOTIFICATION_HTML = """\
<!DOCTYPE html>
<html>
<head>
<style>
""" + _COMMON_STYLES + """
  .changes { margin: 16px 0; }
  .change-row { border-left: 3px solid #3b82f6; padding: 8px 12px; margin: 8px 0; background: #f8fafc; border-radius: 0 4px 4px 0; }
  .change-row.added { border-left-color: #22c55e; }
  .change-row.removed { border-left-color: #ef4444; }
  .change-label { font-size: 12px; color: #64748b; text-transform: uppercase; }
  .change-value { font-size: 14px; margin-top: 2px; }
  .old-value { color: #ef4444; text-decoration: line-through; }
  .new-value { color: #22c55e; font-weight: 600; }
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>V3Q.AI — Status Update</h1>
    <div class="subtitle">Order status change detected</div>
  </div>
  <div class="content">
    <p>A change was detected for document <span class="doc-badge">{{ doc_number }}</span></p>
    {% if source_system %}<p style="color: #64748b; font-size: 13px;">Source: {{ source_system }}</p>{% endif %}

    <div class="changes">
    {% for change in changes %}
      <div class="change-row {{ change.change_type }}">
        <div class="change-label">{{ change.column_name }}</div>
        <div class="change-value">
          {% if change.change_type == 'changed' %}
            <span class="old-value">{{ change.old_value or '(empty)' }}</span>
            &rarr; <span class="new-value">{{ change.new_value or '(empty)' }}</span>
          {% elif change.change_type == 'added' %}
            <span class="new-value">{{ change.new_value }}</span> (new)
          {% elif change.change_type == 'removed' %}
            <span class="old-value">{{ change.old_value }}</span> (removed)
          {% endif %}
        </div>
      </div>
    {% endfor %}
    </div>

    {% if stage_label %}
    <p style="margin-top: 16px;">Current stage: <strong>{{ stage_label }}</strong></p>
    {% endif %}
  </div>
  <div class="footer">
    This notification was sent by V3Q.AI. You are subscribed to updates for document {{ doc_number }}.
  </div>
</div>
</body>
</html>
"""

# --- 2. Chain status overview: sent when user first subscribes ---
_CHAIN_STATUS_HTML = """\
<!DOCTYPE html>
<html>
<head>
<style>
""" + _COMMON_STYLES + """
  .timeline { margin: 20px 0; }
  .stage { display: flex; align-items: flex-start; margin-bottom: 0; }
  .stage-indicator { display: flex; flex-direction: column; align-items: center; margin-right: 12px; min-width: 28px; }
  .stage-dot { width: 16px; height: 16px; border-radius: 50%; border: 2px solid #e2e8f0; }
  .stage-dot.completed { background: #22c55e; border-color: #22c55e; }
  .stage-dot.current { background: #3b82f6; border-color: #3b82f6; }
  .stage-dot.upcoming { background: #ffffff; border-color: #cbd5e1; }
  .stage-line { width: 2px; height: 24px; background: #e2e8f0; }
  .stage-line.completed { background: #22c55e; }
  .stage-body { padding-bottom: 16px; }
  .stage-label { font-size: 14px; font-weight: 600; }
  .stage-label.completed { color: #22c55e; }
  .stage-label.current { color: #3b82f6; }
  .stage-label.upcoming { color: #94a3b8; }
  .stage-key { font-size: 11px; color: #94a3b8; }
  .stage-system { font-size: 11px; color: #64748b; background: #f1f5f9; padding: 1px 6px; border-radius: 3px; margin-left: 6px; }
  .chain-doc { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 12px; margin: 12px 0; }
  .chain-doc-title { font-size: 13px; font-weight: 600; color: #1e293b; }
  .chain-doc-meta { font-size: 12px; color: #64748b; margin-top: 4px; }
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>V3Q.AI — Subscription Confirmation</h1>
    <div class="subtitle">You are now tracking document {{ doc_number }}</div>
  </div>
  <div class="content">
    <p>You have subscribed to status updates for document <span class="doc-badge">{{ doc_number }}</span>.</p>
    <p style="color: #64748b; font-size: 13px;">You will receive an email each time the order status changes.</p>

    {% if stages %}
    <h3 style="font-size: 15px; margin-top: 24px; margin-bottom: 12px;">Order Progress</h3>
    <div class="timeline">
      {% for stage in stages %}
      <div class="stage">
        <div class="stage-indicator">
          <div class="stage-dot {{ stage.status }}"></div>
          {% if not loop.last %}<div class="stage-line {{ stage.status }}"></div>{% endif %}
        </div>
        <div class="stage-body">
          <div class="stage-label {{ stage.status }}">
            {{ stage.stage_label }}
            <span class="stage-system">{{ stage.source_system }}</span>
          </div>
          <div class="stage-key">{{ stage.stage_key }}</div>
        </div>
      </div>
      {% endfor %}
    </div>
    {% endif %}

    {% if chain_documents %}
    <h3 style="font-size: 15px; margin-top: 24px; margin-bottom: 12px;">Linked Documents</h3>
    {% for doc in chain_documents %}
    <div class="chain-doc">
      <div class="chain-doc-title">{{ doc.doc_type }} #{{ doc.doc_number }}</div>
      <div class="chain-doc-meta">
        {{ doc.source_system }}
        {% if doc.status %} &middot; Status: {{ doc.status }}{% endif %}
        {% if doc.doc_date %} &middot; {{ doc.doc_date }}{% endif %}
      </div>
    </div>
    {% endfor %}
    {% endif %}
  </div>
  <div class="footer">
    This notification was sent by V3Q.AI. You are subscribed to updates for document {{ doc_number }}.
  </div>
</div>
</body>
</html>
"""

# --- 3. Stage transition: sent when the order moves to a specific stage ---
_STAGE_TRANSITION_HTML = """\
<!DOCTYPE html>
<html>
<head>
<style>
""" + _COMMON_STYLES + """
  .stage-badge { display: inline-block; padding: 6px 16px; border-radius: 20px; font-weight: 700; font-size: 16px; }
  .stage-badge.completed { background: #dcfce7; color: #15803d; }
  .stage-badge.current { background: #dbeafe; color: #1d4ed8; }
  .arrow { color: #94a3b8; font-size: 20px; margin: 0 12px; }
  .transition-box { text-align: center; padding: 20px; background: #f8fafc; border-radius: 8px; margin: 20px 0; }
  .mini-timeline { display: flex; align-items: center; justify-content: center; margin-top: 20px; gap: 4px; }
  .mini-dot { width: 10px; height: 10px; border-radius: 50%; }
  .mini-dot.done { background: #22c55e; }
  .mini-dot.active { background: #3b82f6; }
  .mini-dot.pending { background: #e2e8f0; }
  .mini-line { width: 20px; height: 2px; }
  .mini-line.done { background: #22c55e; }
  .mini-line.pending { background: #e2e8f0; }
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>V3Q.AI — Stage Update</h1>
    <div class="subtitle">{{ doc_number }} has reached a new stage</div>
  </div>
  <div class="content">
    <p>Document <span class="doc-badge">{{ doc_number }}</span> has progressed to a new stage:</p>

    <div class="transition-box">
      {% if previous_stage %}
        <span class="stage-badge completed">{{ previous_stage }}</span>
        <span class="arrow">&rarr;</span>
      {% endif %}
      <span class="stage-badge current">{{ current_stage }}</span>
    </div>

    {% if source_system %}
    <p style="color: #64748b; font-size: 13px; text-align: center;">System: {{ source_system }}</p>
    {% endif %}

    {% if all_stages %}
    <div class="mini-timeline">
      {% for stage in all_stages %}
        {% if not loop.first %}
          <div class="mini-line {{ 'done' if stage.status in ['completed', 'current'] else 'pending' }}"></div>
        {% endif %}
        <div class="mini-dot {{ 'done' if stage.status == 'completed' else 'active' if stage.status == 'current' else 'pending' }}" title="{{ stage.stage_label }}"></div>
      {% endfor %}
    </div>
    <p style="text-align: center; font-size: 11px; color: #94a3b8; margin-top: 8px;">
      Step {{ current_step }} of {{ total_steps }}
    </p>
    {% endif %}
  </div>
  <div class="footer">
    This notification was sent by V3Q.AI. You are subscribed to updates for document {{ doc_number }}.
  </div>
</div>
</body>
</html>
"""

# --- 4. Test email ---
_TEST_EMAIL_HTML = """\
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 0; background: #f5f5f5; }
  .container { max-width: 600px; margin: 20px auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
  .header { background: #22c55e; color: #ffffff; padding: 24px; }
  .header h1 { margin: 0; font-size: 20px; }
  .content { padding: 24px; }
  .footer { padding: 16px 24px; background: #f8fafc; border-top: 1px solid #e2e8f0; font-size: 12px; color: #94a3b8; }
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>V3Q.AI — SMTP Test</h1>
  </div>
  <div class="content">
    <p>This is a test email from V3Q.AI notification system.</p>
    <p>If you received this, your SMTP configuration is working correctly.</p>
    <p style="color: #64748b; font-size: 13px;">Sent at: {{ timestamp }}</p>
  </div>
  <div class="footer">V3Q.AI Notification System</div>
</div>
</body>
</html>
"""

_env = Environment(loader=BaseLoader(), autoescape=True)


def render_change_notification(
    doc_number: str,
    changes: list[dict],
    source_system: str | None = None,
    stage_label: str | None = None,
) -> str:
    template = _env.from_string(_CHANGE_NOTIFICATION_HTML)
    return template.render(
        doc_number=doc_number,
        changes=changes,
        source_system=source_system,
        stage_label=stage_label,
    )


def render_chain_status(
    doc_number: str,
    stages: list[dict] | None = None,
    chain_documents: list[dict] | None = None,
) -> str:
    """Render the initial subscription confirmation email with chain overview."""
    template = _env.from_string(_CHAIN_STATUS_HTML)
    return template.render(
        doc_number=doc_number,
        stages=stages or [],
        chain_documents=chain_documents or [],
    )


def render_stage_transition(
    doc_number: str,
    current_stage: str,
    previous_stage: str | None = None,
    source_system: str | None = None,
    all_stages: list[dict] | None = None,
    current_step: int = 0,
    total_steps: int = 0,
) -> str:
    """Render email for when an order moves to a new stage in the chain."""
    template = _env.from_string(_STAGE_TRANSITION_HTML)
    return template.render(
        doc_number=doc_number,
        current_stage=current_stage,
        previous_stage=previous_stage,
        source_system=source_system,
        all_stages=all_stages or [],
        current_step=current_step,
        total_steps=total_steps,
    )


def render_test_email(timestamp: str) -> str:
    template = _env.from_string(_TEST_EMAIL_HTML)
    return template.render(timestamp=timestamp)
