import io
import logging
import matplotlib.pyplot as plt

from datetime import datetime
from typing import Any, Dict, List, Tuple, Optional

from src.core.config import settings
from src.services.stats_service import generate_statistics

logger = logging.getLogger(__name__)

# Use a non-interactive backend for matplotlib
import matplotlib
matplotlib.use("Agg")

def create_pie_chart(labels: List[str], sizes: List[int], title: str, small: bool = False) -> Optional[bytes]:
    if not sizes or sum(sizes) == 0:
        return None

    # Custom styling to match the premium look
    plt.style.use("dark_background")
    figsize = (4, 4) if small else (6, 5)
    fig, ax = plt.subplots(figsize=figsize, facecolor="#011627")
    ax.set_facecolor("#011627")

    colors = ["#49a6e8", "#81D4FA", "#1E88E5", "#0277BD", "#275877", "#B3E5FC"]

    def make_autopct(values):
        def my_autopct(pct):
            total = sum(values)
            val = int(round(pct * total / 100.0))
            return f"{val}"
        return my_autopct

    patches, texts, autotexts = ax.pie(
        sizes,
        labels=[str(l)[:15] for l in labels],
        autopct=make_autopct(sizes),
        startangle=90,
        colors=colors[: len(labels)],
        textprops={"color": "white", "fontsize": 9},
        labeldistance=1.05,
    )
    plt.setp(autotexts, size=10, weight="bold")
    ax.axis("equal")

    ax.set_title(title, color="white", fontsize=11, pad=5, fontweight="bold")

    buf = io.BytesIO()
    plt.savefig(buf, format="png", bbox_inches="tight", facecolor="#011627", dpi=120)
    plt.close(fig)
    buf.seek(0)
    return buf.read()

def build_email_grid(items: List[Dict[str, Any]], cols: int) -> str:
    if not items:
        return "<p style='text-align:center; color:#ffffff !important;'>Keine Daten vorhanden</p>"

    col_width = int(100 / cols)
    html = '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin: 0 auto;">'
    for i in range(0, len(items), cols):
        html += "<tr>"
        row_items = items[i : i + cols]
        for item in row_items:
            html += f'<td width="{col_width}%" align="center" valign="top" style="padding: 10px 5px;">'
            html += f'<div style="font-weight: bold; font-size: 11px; color: #49a6e8 !important; text-transform: uppercase; margin-bottom: 4px;">{item["label"]}</div>'
            html += f'<div style="font-size: 26px; font-weight: bold; color: #ffffff !important;">{item["value"]}</div>'
            html += "</td>"

        for _ in range(cols - len(row_items)):
            html += f'<td width="{col_width}%"></td>'
        html += "</tr>"
    html += "</table>"
    return html

def generate_email_stats(tn_data: List[Dict[str, Any]], gf_data: List[Dict[str, Any]], event_info: Dict[str, Any]) -> Tuple[str, Dict[str, bytes]]:
    """Generates the HTML body and inline charts for the stats email."""
    # Reuse the existing pure-Python stats logic
    stats = generate_statistics(tn_data, gf_data, event_info)
    
    inline_images = {}
    
    # Create Stamm Chart
    stamm_dist = stats.get("stamm_distribution", {})
    if stamm_dist:
        chart_bytes = create_pie_chart(
            list(stamm_dist.keys()),
            list(stamm_dist.values()),
            "Gruppen Verteilung",
            small=True
        )
        if chart_bytes:
            inline_images["chart_stamm"] = chart_bytes

    # Prepare data for grids
    diet_stats_list = [
        {"label": "Fleisch", "value": stats["diet_stats"].get("Meat", 0)},
        {"label": "Vegetarisch", "value": stats["diet_stats"].get("Vegetarian", 0)},
        {"label": "Vegan", "value": stats["diet_stats"].get("Vegan", 0)},
    ]
    
    ticket_stats_list = [{"label": k, "value": v} for k, v in stats.get("ticket_stats", {}).items()]

    diet_html = build_email_grid(diet_stats_list, cols=3)
    ticket_html = build_email_grid(ticket_stats_list, cols=2)

    event_id = event_info.get("list_id")
    event_url = f"{settings.frontend_url}/events/{event_id}"
    event_name = stats["event_title"]
    accent_blue = "#49a6e8"
    bg_dark = "#011627"
    
    # Health Info Summary
    has_health_data = len(stats["allergies"]) > 0 or len(stats["health_notes"]) > 0
    health_summary_html = ""
    if has_health_data:
        summary_text = []
        if stats["allergies"]:
            summary_text.append(f"<b>{len(stats['allergies'])}</b> Einträge zu Allergien/Unverträglichkeiten")
        if stats["health_notes"]:
            summary_text.append(f"<b>{len(stats['health_notes'])}</b> zusätzliche Gesundheitsinformationen")
        
        health_summary_html = f"""
        <div class="health-hint" style="border-left: 4px solid {accent_blue}; text-align: left;">
            <p style="margin-top: 0;">Es liegen wichtige Gesundheitsdaten vor:</p>
            <ul style="margin-bottom: 0; padding-left: 20px;">
                {"".join([f"<li>{txt}</li>" for txt in summary_text])}
            </ul>
        </div>
        """
    else:
        health_summary_html = "<p style='color: #81D4FA !important;'>Keine besonderen Gesundheitsdaten hinterlegt.</p>"

    html_body = f"""
    <!doctype html>
    <html>
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
          body, .container, .section, p, div, td, th, span {{ 
              font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 
              color: #ffffff !important; 
          }}
          body {{ margin: 0; padding: 0; background-color: {bg_dark} !important; }}
          .container {{ max-width: 600px; margin: 0 auto; background-color: {bg_dark} !important; }}
          .section {{ padding: 25px 20px; border-bottom: 1px solid #1a2e3e; text-align: center; }}
          
          .data-table {{ width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 14px; }}
          .data-table th {{ text-align: center; color: {accent_blue} !important; border-bottom: 1px solid #1a2e3e; padding: 10px 5px; }}
          .data-table td {{ padding: 10px 5px; border-bottom: 1px solid #0d2538; text-align: center; }}
          
          .health-hint {{ width: 100%; box-sizing: border-box; margin: 20px auto 0 auto; background: #1a2e3e !important; padding: 15px; border-radius: 8px; font-size: 14px; }}
          .health-hint li {{ margin-bottom: 5px; }}
          .btn {{ display: inline-block; padding: 12px 24px; background-color: {accent_blue} !important; color: #ffffff !important; text-decoration: none; border-radius: 6px; font-weight: bold; margin-top: 20px; }}
          h1, h2, h3 {{ margin-top: 0; margin-bottom: 15px; color: #ffffff !important; font-weight: 600; text-align: center; }}
        </style>
      </head>
      <body>
        <div class="container">
          <div class="section" style="background: linear-gradient(180deg, #02213a 0%, #011627 100%); padding-top: 40px; padding-bottom: 30px;">
            <h1 style="margin:0; font-size: 26px;">{event_name}</h1>
            <p style="color: {accent_blue} !important; margin: 5px 0 0 0; font-size: 14px;">Automatischer Report</p>
          </div>

          <div class="section">
            <table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td width="66%" align="center" valign="middle" style="padding: 10px 0;">
                  {"<img src='cid:chart_stamm' style='width: 100%; max-width: 360px; display: block; margin: 0 auto;'>" if "chart_stamm" in inline_images else ""}
                </td>
                <td width="34%" align="center" valign="middle" style="padding: 10px 0;">
                  <div style="margin-bottom: 25px;">
                    <div style="font-weight: bold; font-size: 11px; color: {accent_blue} !important; text-transform: uppercase; margin-bottom: 4px;">Teilnehmende</div>
                    <div style="font-size: 26px; font-weight: bold; color: #ffffff !important;">{stats['total_participants']}</div>
                  </div>
                  <div>
                    <div style="font-weight: bold; font-size: 11px; color: {accent_blue} !important; text-transform: uppercase; margin-bottom: 4px;">Leitungen</div>
                    <div style="font-size: 26px; font-weight: bold; color: #ffffff !important;">{stats['total_leaders']}</div>
                  </div>
                </td>
              </tr>
            </table>
          </div>

          <div class="section">
            <h3>Ernährungsweisen</h3>
            {diet_html}
          </div>

          <div class="section">
            <h3>ÖPNV Tickets</h3>
            {ticket_html}
          </div>

          <div class="section" style="border-bottom: none; padding-bottom: 40px;">
            <h3>Gesundheitsinformationen</h3>
            {health_summary_html}
            
            <div style="margin-top: 35px;">
                <p style="font-size: 13px; opacity: 0.8; margin-bottom: 15px;">Detaillierte Listen und personenbezogene Daten findest du sicher verschlüsselt in der Webapp.</p>
                <a href="{event_url}" class="btn">Zum Event Dashboard</a>
            </div>
          </div>

          <div style="text-align: center; padding: 20px; font-size: 11px; color: #59c4f4 !important; opacity: 0.7;">
            © {datetime.now().year} campflowToolbox
          </div>
        </div>
      </body>
    </html>
    """
    return html_body, inline_images
