# datainsightx/visualize.py

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from jinja2 import Template

def visualize_overview(df, output_html="datainsightx_report.html"):
    """
    Creates an interactive, colorful HTML dashboard showing:
    - Dataset summary
    - Missing values
    - Numeric distributions
    - Categorical distributions
    """

    # 🧮 Basic summary metrics
    total_rows = len(df)
    total_cols = len(df.columns)
    total_missing = int(df.isnull().sum().sum())
    total_duplicates = int(df.duplicated().sum())

    summary_html = f"""
    <table style='width:50%; margin:auto; border-collapse: collapse;'>
        <tr><th style='background:#007BFF;color:white;'>Metric</th><th style='background:#007BFF;color:white;'>Value</th></tr>
        <tr><td>Total Rows</td><td>{total_rows}</td></tr>
        <tr><td>Total Columns</td><td>{total_cols}</td></tr>
        <tr><td>Total Missing Values</td><td>{total_missing}</td></tr>
        <tr><td>Duplicate Rows</td><td>{total_duplicates}</td></tr>
    </table>
    """

    # 🎨 Apply a nice Plotly theme
    template_style = "plotly_dark"

    # 1️⃣ Missing Values Chart
    missing = df.isnull().sum()
    missing = missing[missing > 0]
    if len(missing) > 0:
        fig_missing = px.bar(
            x=missing.index,
            y=missing.values,
            title="🧩 Missing Values per Column",
            labels={"x": "Column", "y": "Missing Count"},
            template=template_style,
            color=missing.values,
            color_continuous_scale="reds"
        )
    else:
        fig_missing = go.Figure()
        fig_missing.add_annotation(text="✅ No Missing Values", showarrow=False)

    # 2️⃣ Numeric Distributions
    numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
    numeric_html = ""
    for col in numeric_cols:
        fig = px.histogram(df, x=col, nbins=20, title=f"💰 Distribution of {col}",
                           template=template_style, color_discrete_sequence=["#00CC96"])
        fig.update_traces(opacity=0.8)
        numeric_html += fig.to_html(full_html=False, include_plotlyjs=False)

    # 3️⃣ Categorical Distributions
    cat_cols = df.select_dtypes(include=['object', 'category']).columns
    cat_html = ""
    for col in cat_cols:
        freq = df[col].value_counts().reset_index()
        freq.columns = [col, "count"]
        fig = px.bar(freq.head(10), x=col, y="count", title=f"🏷️ Top Categories in {col}",
                     template=template_style, color="count", color_continuous_scale="Blues")
        cat_html += fig.to_html(full_html=False, include_plotlyjs=False)

    # 🧱 Combine all sections into one HTML page using Jinja2
    html_template = Template("""
    <html>
    <head>
        <title>DataInsightX Report</title>
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
        <style>
            body { font-family: 'Segoe UI', sans-serif; margin: 20px; background-color: #0d1117; color: white; }
            h1, h2 { text-align: center; }
            hr { border: 1px solid #333; margin: 30px 0; }
            table, th, td { border: 1px solid #555; padding: 8px; text-align: center; }
            th { background-color: #007BFF; color: white; }
        </style>
    </head>
    <body>
        <h1>📊 DataInsightX Report</h1>
        <h2>Dataset Summary</h2>
        {{ summary_html | safe }}
        <hr>

        <h2>🧩 Missing Values</h2>
        {{ fig_missing | safe }}
        <hr>

        <h2>💰 Numeric Distributions</h2>
        {{ numeric_html | safe }}
        <hr>

        <h2>🏷️ Categorical Distributions</h2>
        {{ cat_html | safe }}
        <hr>

        <p style="text-align:center;color:#888;">Generated by DataInsightX</p>
    </body>
    </html>
    """)

    final_html = html_template.render(
        summary_html=summary_html,
        fig_missing=fig_missing.to_html(full_html=False, include_plotlyjs=False),
        numeric_html=numeric_html,
        cat_html=cat_html
    )

    with open(output_html, "w", encoding="utf-8") as f:
        f.write(final_html)

    print(f"✅ Beautiful dashboard generated: {output_html}")
    return output_html
