from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from openpyxl import load_workbook
from datetime import datetime
from collections import Counter
import uuid
import json

app = Flask(__name__)
CORS(app)

EXCEL_FILE = "RegistrationsTable.xlsx"

latest_registration_id = None


@app.route("/")
def home():
    return send_from_directory(".", "register.html")


@app.route("/api/register", methods=["POST"])
def register():
    data = request.json

    workbook = load_workbook(EXCEL_FILE)
    sheet = workbook.active

    timestamp = datetime.now()
    visit_month = timestamp.strftime("%Y-%m")
    visit_week = timestamp.strftime("%Y-W%U")

    sheet.append([
        str(uuid.uuid4()),
        timestamp.strftime("%Y-%m-%d %H:%M:%S"),
        visit_week,
        visit_month,
        data.get("userId", ""),
        data.get("name", ""),
        data.get("userProfile", ""),
        data.get("visitReason", ""),
        data.get("space", ""),
        "no"
    ])

    workbook.save(EXCEL_FILE)

    return jsonify({
        "success": True,
        "message": "Registration saved"
    })


@app.route("/api/latest", methods=["GET"])
def latest_registration():
    workbook = load_workbook(EXCEL_FILE)
    sheet = workbook.active

    for row in range(sheet.max_row, 1, -1):
        notified = sheet.cell(row, 10).value

        if notified == "no":
            registration_id = sheet.cell(row, 1).value
            name = sheet.cell(row, 6).value
            profile = sheet.cell(row, 7).value

            sheet.cell(row, 10).value = "yes"
            workbook.save(EXCEL_FILE)

            return jsonify({
                "new_registration": True,
                "registration_id": registration_id,
                "name": name,
                "profile": profile
            })

    return jsonify({
        "new_registration": False
    })


@app.route("/dashboard")
def dashboard():
    workbook = load_workbook(EXCEL_FILE)
    sheet = workbook.active

    rows = list(sheet.iter_rows(min_row=2, values_only=True))
    total_visits = len(rows)

    visit_weeks = [row[2] for row in rows if row[2]]
    visit_months = [row[3] for row in rows if row[3]]
    profiles = [row[6] for row in rows if row[6]]
    reasons = [row[7] for row in rows if row[7]]

    current_week = max(visit_weeks) if visit_weeks else "No data"
    current_month = max(visit_months) if visit_months else "No data"

    weekly_visits = visit_weeks.count(current_week) if visit_weeks else 0
    monthly_visits = visit_months.count(current_month) if visit_months else 0
    main_reason = Counter(reasons).most_common(1)[0][0] if reasons else "No data"

    week_counts = dict(sorted(Counter(visit_weeks).items()))
    profile_counts = dict(Counter(profiles))
    reason_counts = dict(Counter(reasons))

    monthly_identifiers = [
        row[4] if row[4] else row[5]
        for row in rows
        if row[3] == current_month and (row[4] or row[5])
    ]

    visitor_counts = Counter(monthly_identifiers).most_common(3)

    visitors_html = ""
    medals = ["🥇", "🥈", "🥉"]

    if visitor_counts:
        for i, (visitor, count) in enumerate(visitor_counts):
            visitors_html += f"""
                <div class="visitor-row">
                    <span>{medals[i]} {visitor}</span>
                    <strong>{count} visits</strong>
                </div>
            """
    else:
        visitors_html = """
            <p class="empty-state">No visitor data available yet.</p>
        """

    return f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="refresh" content="15">
        <title>Space Dashboard</title>

        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

        <style>
            :root {{
                --blue: #0039a6;
                --dark-blue: #001f5c;
                --light-blue: #eef4ff;
                --text: #1f2937;
                --muted: #6b7280;
                --border: #d1d5db;
                --white: #ffffff;
            }}

            * {{
                box-sizing: border-box;
            }}

            body {{
                margin: 0;
                font-family: Arial, Helvetica, sans-serif;
                background: #f8fafc;
                color: var(--text);
                padding: 32px;
            }}

            .container {{
                max-width: 1100px;
                margin: 0 auto;
            }}

            .header {{
                margin-bottom: 32px;
            }}

            .brand-line {{
                width: 48px;
                height: 4px;
                background: var(--blue);
                border-radius: 999px;
                margin-bottom: 18px;
            }}

            h1 {{
                color: var(--dark-blue);
                margin: 0;
                font-size: 2rem;
            }}

            .subtitle {{
                color: var(--muted);
                margin-top: 10px;
            }}

            .grid {{
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
                gap: 18px;
            }}

            .card {{
                background: var(--white);
                border: 1px solid var(--border);
                border-radius: 18px;
                padding: 22px;
                box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
            }}

            .card h2 {{
                margin: 0 0 8px;
                font-size: 0.9rem;
                color: var(--muted);
                font-weight: 600;
            }}

            .metric {{
                font-size: 2rem;
                font-weight: 800;
                color: var(--dark-blue);
            }}

            .charts {{
                margin-top: 18px;
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
                gap: 18px;
            }}

            .chart-card {{
                height: 360px;
            }}

            canvas {{
                margin-top: 12px;
            }}

            .visitor-row {{
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16px 0;
                border-bottom: 1px solid #e5e7eb;
                font-size: 1rem;
            }}

            .visitor-row:last-child {{
                border-bottom: none;
            }}

            .visitor-row strong {{
                color: var(--dark-blue);
            }}

            .empty-state {{
                color: var(--muted);
                margin-top: 24px;
            }}

            .footer {{
                margin-top: 28px;
                color: var(--muted);
                font-size: 0.8rem;
            }}
        </style>
    </head>

    <body>
        <main class="container">
            <section class="header">
                <div class="brand-line"></div>
                <h1>Space Dashboard</h1>
                <p class="subtitle">Live overview based on registration data.</p>
            </section>

            <section class="grid">
                <div class="card">
                    <h2>Weekly visits</h2>
                    <div class="metric">{weekly_visits}</div>
                </div>

                <div class="card">
                    <h2>Monthly visits</h2>
                    <div class="metric">{monthly_visits}</div>
                </div>

                <div class="card">
                    <h2>Main visit reason</h2>
                    <div class="metric" style="font-size:1.3rem;">{main_reason}</div>
                </div>

                <div class="card">
                    <h2>Total visits</h2>
                    <div class="metric">{total_visits}</div>
                </div>
            </section>

            <section class="charts">
                <div class="card chart-card">
                    <h2>Visits by week</h2>
                    <canvas id="weeklyChart"></canvas>
                </div>

                <div class="card chart-card">
                    <h2>Visits by profile</h2>
                    <canvas id="profileChart"></canvas>
                </div>

                <div class="card chart-card">
                    <h2>Visit reasons</h2>
                    <canvas id="reasonChart"></canvas>
                </div>

                <div class="card chart-card">
                    <h2>Top 3 frequent visitors this month</h2>
                    {visitors_html}
                </div>
            </section>

            <p class="footer">
                Data is read from RegistrationsTable.xlsx. Dashboard refreshes every 15 seconds.
            </p>
        </main>

        <script>
            const weekLabels = {json.dumps(list(week_counts.keys()))};
            const weekData = {json.dumps(list(week_counts.values()))};

            const profileLabels = {json.dumps(list(profile_counts.keys()))};
            const profileData = {json.dumps(list(profile_counts.values()))};

            const reasonLabels = {json.dumps(list(reason_counts.keys()))};
            const reasonData = {json.dumps(list(reason_counts.values()))};

            new Chart(document.getElementById("weeklyChart"), {{
                type: "line",
                data: {{
                    labels: weekLabels,
                    datasets: [{{
                        label: "Visits",
                        data: weekData,
                        borderWidth: 3,
                        tension: 0.35
                    }}]
                }},
                options: {{
                    responsive: true,
                    maintainAspectRatio: false
                }}
            }});

            new Chart(document.getElementById("profileChart"), {{
                type: "doughnut",
                data: {{
                    labels: profileLabels,
                    datasets: [{{
                        data: profileData
                    }}]
                }},
                options: {{
                    responsive: true,
                    maintainAspectRatio: false
                }}
            }});

            new Chart(document.getElementById("reasonChart"), {{
                type: "bar",
                data: {{
                    labels: reasonLabels,
                    datasets: [{{
                        label: "Visits",
                        data: reasonData,
                        borderWidth: 1
                    }}]
                }},
                options: {{
                    responsive: true,
                    maintainAspectRatio: false
                }}
            }});
        </script>
    </body>
    </html>
    """


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)