"use client";

import { useEffect, useState } from "react";

interface EngagementStats {
  totalLogs: number;
  totalMedicines: number;
  totalVaccinations: number;
  totalGrowth: number;
  totalMemories: number;
  totalChatSessions: number;
  logsByDay: { date: string; count: number }[];
  topFeatures: { name: string; count: number }[];
}

export default function AdminAnalytics() {
  const [stats, setStats] = useState<EngagementStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchAnalytics();
  }, []);

  const fetchAnalytics = async () => {
    try {
      const res = await fetch("/api/admin/analytics", { credentials: "include" });
      const data = await res.json();
      setStats(data);
    } catch (err) {
      console.error("Failed to fetch analytics:", err);
    }
    setLoading(false);
  };

  if (loading || !stats) {
    return <div className="p-6 text-white">Loading...</div>;
  }

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Analytics</h1>
        <p className="text-gray-400">Feature usage and engagement</p>
      </div>

      {/* Usage Overview */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        <StatCard label="Activity Logs" value={stats.totalLogs} icon="📝" />
        <StatCard label="Medicines" value={stats.totalMedicines} icon="💊" />
        <StatCard label="Vaccinations" value={stats.totalVaccinations} icon="💉" />
        <StatCard label="Growth" value={stats.totalGrowth} icon="📏" />
        <StatCard label="Memories" value={stats.totalMemories} icon="📸" />
        <StatCard label="Chat Sessions" value={stats.totalChatSessions} icon="💬" />
      </div>

      {/* Activity Chart */}
      <div className="bg-gray-800 p-6 rounded-xl">
        <h3 className="text-lg font-semibold mb-4">Daily Activity (Last 30 days)</h3>
        <div className="h-48 flex items-end gap-1">
          {stats.logsByDay.slice(-30).map((d, i) => (
            <div key={i} className="flex-1 flex flex-col items-center gap-1">
              <div
                className="w-full bg-rose-500 rounded-t"
                style={{
                  height: `${Math.min((d.count / Math.max(...stats.logsByDay.map(l => l.count), 1)) * 100, 100)}%`,
                  minHeight: d.count > 0 ? "4px" : "0"
                }}
              />
              <div className="text-[8px] text-gray-500">{d.date?.slice(5) || ""}</div>
            </div>
          ))}
        </div>
        {stats.logsByDay.length === 0 && (
          <div className="h-48 flex items-center justify-center text-gray-500">
            No activity data yet
          </div>
        )}
      </div>

      {/* Feature Breakdown */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-lg font-semibold mb-4">Top Features</h3>
          <div className="space-y-3">
            {stats.topFeatures.map((feature, i) => (
              <div key={i} className="flex justify-between items-center">
                <span>{feature.name}</span>
                <span className="font-bold text-rose-400">{feature.count}</span>
              </div>
            ))}
            {stats.topFeatures.length === 0 && (
              <div className="text-gray-500">No data yet</div>
            )}
          </div>
        </div>

        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-lg font-semibold mb-4">Engagement Summary</h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-gray-400">Avg Logs per Family</span>
              <span className="font-bold">
                {stats.totalLogs > 0 ? (stats.totalLogs / 1).toFixed(1) : "0"}
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-400">Avg Children per Family</span>
              <span className="font-bold">1.0</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-400">Chat Adoption</span>
              <span className="font-bold text-emerald-400">
                {stats.totalChatSessions > 0 ? "Active" : "None"}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ label, value, icon }: { label: string; value: number; icon: string }) {
  return (
    <div className="bg-gray-800 p-4 rounded-xl">
      <div className="text-2xl mb-1">{icon}</div>
      <div className="text-xl font-bold">{value}</div>
      <div className="text-xs text-gray-400">{label}</div>
    </div>
  );
}