"use client";

import { useEffect, useState } from "react";
import Link from "next/link";

import { BACKEND } from "../config";

type AnalyticsData = {
  ok: boolean;
  period_days: number;
  summary: {
    total_comments: number;
    total_analyses: number;
    analyzed_percentage: number;
    sentiment_distribution: Record<string, number>;
    platform_distribution: Record<string, number>;
  };
  timeseries: {
    comments: Array<{ date: string; count: number }>;
    sentiment: Array<{ date: string; positive: number; negative: number; neutral: number }>;
    platform: Array<{ date: string; instagram: number; facebook: number }>;
  };
};

type KPIData = {
  ok: boolean;
  aggregate: {
    totals: {
      analyses: number;
      toxic: number;
      purchase_signal: number;
      needs_context: number;
    };
    sentiment: Record<string, number>;
    intent: Record<string, number>;
    emotion: Record<string, number>;
    language: Record<string, number>;
    topics: Record<string, number>;
    last_analysis_at: string | null;
  };
};

export default function AnalyticsPage() {
  const [analyticsData, setAnalyticsData] = useState<AnalyticsData | null>(null);
  const [kpiData, setKpiData] = useState<KPIData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [days, setDays] = useState(30);

  useEffect(() => {
    loadData();
  }, [days]);

  // Refetch when user returns to this tab (e.g. after analyzing on dashboard)
  useEffect(() => {
    const onFocus = () => loadData();
    window.addEventListener("focus", onFocus);
    return () => window.removeEventListener("focus", onFocus);
  }, [days]);

  async function loadData() {
    setLoading(true);
    setError(null);
    try {
      const [analyticsRes, kpiRes] = await Promise.all([
        fetch(`${BACKEND}/analytics/overview?days=${days}`, { credentials: "include" }),
        fetch(`${BACKEND}/ai/global/kpis`, { credentials: "include" }),
      ]);

      const analytics = await analyticsRes.json();
      const kpis = await kpiRes.json();

      if (analytics.ok) {
        setAnalyticsData(analytics);
      } else {
        setError("Failed to load analytics data");
      }

      if (kpis.ok) {
        setKpiData(kpis);
      }
    } catch (err) {
      setError("Failed to load data. Check backend connection.");
    } finally {
      setLoading(false);
    }
  }

  function formatNumber(num: number): string {
    return new Intl.NumberFormat().format(num);
  }

  function formatPercentage(num: number): string {
    return `${num.toFixed(1)}%`;
  }

  function getSentimentColor(sentiment: string): string {
    switch (sentiment.toLowerCase()) {
      case "positive":
        return "text-green-400";
      case "negative":
        return "text-red-400";
      case "neutral":
        return "text-gray-400";
      default:
        return "text-white/60";
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-black via-gray-900 to-black p-4 sm:p-8">
      <div className="mx-auto max-w-7xl">
        {/* Header */}
        <div className="mb-8 flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-white">Global Analytics</h1>
            <p className="mt-2 text-sm text-white/60">Track sentiment, engagement, and trends across all posts</p>
          </div>
          <div className="flex gap-3">
            <Link
              href="/toxicity"
              className="rounded-xl border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10"
            >
              Toxicity Review
            </Link>
            <Link
              href="/settings"
              className="rounded-xl border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10"
            >
              Settings
            </Link>
            <Link
              href="/help"
              className="rounded-xl border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10"
            >
              Help
            </Link>
            <Link
              href="/"
              className="rounded-xl border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10"
            >
              ← Back to Dashboard
            </Link>
          </div>
        </div>

        {/* Period Selector & Refresh */}
        <div className="mb-6 flex flex-wrap items-center gap-4">
          <label className="text-sm text-white/60">Time Period:</label>
          <select
            value={days}
            onChange={(e) => setDays(Number(e.target.value))}
            className="rounded-lg border border-white/15 bg-black/40 px-3 py-2 text-sm text-white outline-none focus:border-white/30"
          >
            <option value={7}>Last 7 days</option>
            <option value={30}>Last 30 days</option>
            <option value={90}>Last 90 days</option>
            <option value={180}>Last 6 months</option>
            <option value={365}>Last year</option>
          </select>
          <button
            type="button"
            onClick={() => loadData()}
            disabled={loading}
            className="rounded-lg border border-white/20 bg-white/10 px-4 py-2 text-sm font-medium text-white hover:bg-white/20 disabled:opacity-50"
          >
            {loading ? "Loading…" : "Refresh"}
          </button>
          {!loading && (analyticsData || kpiData) && (
            <span className="text-xs text-white/40">Data refreshes when you return to this tab</span>
          )}
        </div>

        {error && (
          <div className="mb-6 rounded-xl border border-red-500/30 bg-red-500/10 p-4 text-sm text-red-200">
            {error}
          </div>
        )}

        {loading ? (
          <div className="text-center text-white/60">Loading analytics...</div>
        ) : (
          <>
            {/* KPI Cards */}
            {kpiData && (
              <div className="mb-8 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <div className="text-sm text-white/60">Total Analyses</div>
                  <div className="mt-2 text-3xl font-bold text-white">
                    {formatNumber(kpiData.aggregate.totals.analyses)}
                  </div>
                </div>
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <div className="text-sm text-white/60">Toxic Comments</div>
                  <div className="mt-2 text-3xl font-bold text-red-400">
                    {formatNumber(kpiData.aggregate.totals.toxic)}
                  </div>
                </div>
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <div className="text-sm text-white/60">Purchase Signals</div>
                  <div className="mt-2 text-3xl font-bold text-green-400">
                    {formatNumber(kpiData.aggregate.totals.purchase_signal)}
                  </div>
                </div>
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <div className="text-sm text-white/60">Needs Context</div>
                  <div className="mt-2 text-3xl font-bold text-yellow-400">
                    {formatNumber(kpiData.aggregate.totals.needs_context)}
                  </div>
                </div>
              </div>
            )}

            {/* Summary Stats */}
            {analyticsData && (
              <div className="mb-8 grid grid-cols-1 gap-4 sm:grid-cols-3">
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <div className="text-sm text-white/60">Total Comments</div>
                  <div className="mt-2 text-3xl font-bold text-white">
                    {formatNumber(analyticsData.summary.total_comments)}
                  </div>
                  <div className="mt-1 text-xs text-white/40">
                    {formatNumber(analyticsData.summary.total_analyses)} analyzed (
                    {formatPercentage(analyticsData.summary.analyzed_percentage)})
                  </div>
                </div>
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <div className="text-sm text-white/60">Platform Distribution</div>
                  <div className="mt-3 space-y-2">
                    {Object.entries(analyticsData.summary.platform_distribution).map(([platform, count]) => (
                      <div key={platform} className="flex items-center justify-between">
                        <span className="text-sm capitalize text-white/70">{platform}</span>
                        <span className="text-sm font-semibold text-white">{formatNumber(count)}</span>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <div className="text-sm text-white/60">Sentiment Distribution</div>
                  <div className="mt-3 space-y-2">
                    {Object.entries(analyticsData.summary.sentiment_distribution).map(([sentiment, count]) => (
                      <div key={sentiment} className="flex items-center justify-between">
                        <span className={`text-sm capitalize ${getSentimentColor(sentiment)}`}>
                          {sentiment}
                        </span>
                        <span className="text-sm font-semibold text-white">{formatNumber(count)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* Charts Section */}
            {analyticsData && (
              <div className="space-y-8">
                {/* Comments Over Time */}
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <h2 className="mb-4 text-xl font-semibold text-white">Comments Over Time</h2>
                  {analyticsData.timeseries.comments.length === 0 ? (
                    <div className="flex h-64 items-center justify-center text-white/60">
                      No comment data available for the selected period
                    </div>
                  ) : (
                    <div className="h-64 overflow-x-auto">
                      <div className="flex h-full items-end gap-1">
                        {analyticsData.timeseries.comments.map((item, idx) => {
                          const maxCount = Math.max(...analyticsData.timeseries.comments.map((c) => c.count), 1);
                          const chartHeightPx = 200;
                          const heightPx =
                            item.count > 0
                              ? Math.max(4, Math.round((item.count / maxCount) * chartHeightPx))
                              : 2;
                          return (
                            <div key={idx} className="flex h-full flex-1 flex-col items-center justify-end">
                              <div
                                className="w-full rounded-t bg-blue-500/60 transition-all hover:bg-blue-500/80"
                                style={{ height: `${heightPx}px`, minHeight: "2px" }}
                                title={`${item.date}: ${item.count} comments`}
                              />
                              {idx % Math.ceil(analyticsData.timeseries.comments.length / 10) === 0 && (
                                <div className="mt-2 shrink-0 text-xs text-white/40">
                                  {new Date(item.date).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>

                {/* Sentiment Over Time */}
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <h2 className="mb-4 text-xl font-semibold text-white">Sentiment Over Time</h2>
                  {analyticsData.timeseries.sentiment.length === 0 ? (
                    <div className="flex h-64 items-center justify-center text-white/60">
                      No sentiment data available. Analyze comments first to see sentiment trends.
                    </div>
                  ) : (
                    <div className="h-64 overflow-x-auto">
                      <div className="flex h-full items-end gap-1">
                        {analyticsData.timeseries.sentiment.map((item, idx) => {
                          const maxCount = Math.max(
                            ...analyticsData.timeseries.sentiment.map((s) => s.positive + s.negative + s.neutral),
                            1
                          );
                          const stackHeightPx = 180;
                          const positivePx =
                            item.positive > 0
                              ? Math.max(2, Math.round((item.positive / maxCount) * stackHeightPx))
                              : 2;
                          const neutralPx =
                            item.neutral > 0
                              ? Math.max(2, Math.round((item.neutral / maxCount) * stackHeightPx))
                              : 2;
                          const negativePx =
                            item.negative > 0
                              ? Math.max(2, Math.round((item.negative / maxCount) * stackHeightPx))
                              : 2;
                          return (
                            <div key={idx} className="flex h-full flex-1 flex-col items-center justify-end gap-0.5">
                              <div className="flex w-full flex-1 flex-col justify-end gap-0.5 min-h-0">
                                <div
                                  className="w-full rounded bg-green-500/60"
                                  style={{ height: `${positivePx}px`, minHeight: "2px" }}
                                  title={`${item.date}: ${item.positive} positive`}
                                />
                                <div
                                  className="w-full rounded bg-gray-500/60"
                                  style={{ height: `${neutralPx}px`, minHeight: "2px" }}
                                  title={`${item.date}: ${item.neutral} neutral`}
                                />
                                <div
                                  className="w-full rounded bg-red-500/60"
                                  style={{ height: `${negativePx}px`, minHeight: "2px" }}
                                  title={`${item.date}: ${item.negative} negative`}
                                />
                              </div>
                              {idx % Math.ceil(analyticsData.timeseries.sentiment.length / 10) === 0 && (
                                <div className="mt-2 shrink-0 text-xs text-white/40">
                                  {new Date(item.date).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                  <div className="mt-4 flex gap-4 text-xs text-white/60">
                    <div className="flex items-center gap-2">
                      <div className="h-3 w-3 rounded bg-green-500/60" />
                      <span>Positive</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="h-3 w-3 rounded bg-gray-500/60" />
                      <span>Neutral</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="h-3 w-3 rounded bg-red-500/60" />
                      <span>Negative</span>
                    </div>
                  </div>
                </div>

                {/* Platform Distribution Over Time */}
                <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                  <h2 className="mb-4 text-xl font-semibold text-white">Platform Distribution Over Time</h2>
                  {analyticsData.timeseries.platform.length === 0 ? (
                    <div className="flex h-64 items-center justify-center text-white/60">
                      No platform data available for the selected period
                    </div>
                  ) : (
                    <div className="h-64 overflow-x-auto">
                      <div className="flex h-full items-end gap-1">
                        {analyticsData.timeseries.platform.map((item, idx) => {
                          const maxCount = Math.max(
                            ...analyticsData.timeseries.platform.map((p) => p.instagram + p.facebook),
                            1
                          );
                          const stackHeightPx = 180;
                          const instagramPx =
                            item.instagram > 0
                              ? Math.max(2, Math.round((item.instagram / maxCount) * stackHeightPx))
                              : 2;
                          const facebookPx =
                            item.facebook > 0
                              ? Math.max(2, Math.round((item.facebook / maxCount) * stackHeightPx))
                              : 2;
                          return (
                            <div key={idx} className="flex h-full flex-1 flex-col items-center justify-end gap-0.5">
                              <div className="flex w-full flex-1 flex-col justify-end gap-0.5 min-h-0">
                                <div
                                  className="w-full rounded bg-purple-500/60"
                                  style={{ height: `${instagramPx}px`, minHeight: "2px" }}
                                  title={`${item.date}: ${item.instagram} Instagram`}
                                />
                                <div
                                  className="w-full rounded bg-blue-500/60"
                                  style={{ height: `${facebookPx}px`, minHeight: "2px" }}
                                  title={`${item.date}: ${item.facebook} Facebook`}
                                />
                              </div>
                              {idx % Math.ceil(analyticsData.timeseries.platform.length / 10) === 0 && (
                                <div className="mt-2 shrink-0 text-xs text-white/40">
                                  {new Date(item.date).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                  <div className="mt-4 flex gap-4 text-xs text-white/60">
                    <div className="flex items-center gap-2">
                      <div className="h-3 w-3 rounded bg-purple-500/60" />
                      <span>Instagram</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="h-3 w-3 rounded bg-blue-500/60" />
                      <span>Facebook</span>
                    </div>
                  </div>
                </div>

                {/* Top Topics */}
                {kpiData && Object.keys(kpiData.aggregate.topics).length > 0 && (
                  <div className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6">
                    <h2 className="mb-4 text-xl font-semibold text-white">Top Topics</h2>
                    <div className="flex flex-wrap gap-2">
                      {Object.entries(kpiData.aggregate.topics)
                        .sort(([, a], [, b]) => b - a)
                        .slice(0, 20)
                        .map(([topic, count]) => (
                          <div
                            key={topic}
                            className="rounded-lg border border-white/15 bg-white/5 px-3 py-1.5 text-sm"
                          >
                            <span className="text-white/70">{topic}</span>
                            <span className="ml-2 text-white/40">({formatNumber(count)})</span>
                          </div>
                        ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

