"use client";

import { useEffect, useState } from "react";
import { Select } from "@/components/ui";
import Link from "next/link";

interface Stats {
  overview: {
    totalFamilies: number;
    totalUsers: number;
    totalChildren: number;
    proFamilies: number;
    freeFamilies: number;
    mrr: number;
    avgRevenuePerUser: number;
    activeSessions: number;
    loginsLast24h: number;
    failedLoginsLast24h: number;
  };
  conversions: {
    freeToPro: number;
    conversionRate: number;
  };
  growth: {
    familiesByDay: { date: string; count: number }[];
    usersByDay: { date: string; count: number }[];
  };
  childrenByAge: { ageGroup: string; count: number }[];
}

export default function AdminDashboard() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState("30");

  useEffect(() => {
    fetchStats();
  }, [period]);

  const fetchStats = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/stats?period=${period}`, { credentials: "include" });
      const data = await res.json();
      setStats(data);
    } catch (err) {
      console.error("Failed to fetch stats:", err);
    }
    setLoading(false);
  };

  if (loading || !stats) {
    return (
      <div className="p-6 space-y-6 animate-pulse">
        <div className="h-8 bg-gray-800 rounded w-48" />
        <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-4">
          {[1, 2, 3, 4, 5, 6].map(i => <div key={i} className="h-28 bg-gray-800 rounded-xl" />)}
        </div>
      </div>
    );
  }

  const { overview, conversions, growth, childrenByAge } = stats;

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">Dashboard</h1>
          <p className="text-gray-400">Platform overview and analytics</p>
        </div>
        <Select value={period} onChange={(e) => setPeriod(e.target.value)}>
          <option value="7">Last 7 days</option>
          <option value="30">Last 30 days</option>
          <option value="90">Last 90 days</option>
        </Select>
      </div>

      {/* Primary Stat Cards */}
      <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-4">
        <StatCard label="Families" value={overview.totalFamilies} icon="🏠" color="rose" href="/admin/families" />
        <StatCard label="Users" value={overview.totalUsers} icon="👥" color="blue" href="/admin/users" />
        <StatCard label="Children" value={overview.totalChildren} icon="👶" color="amber" href="/admin/children" />
        <StatCard label="MRR" value={`$${overview.mrr.toFixed(2)}`} icon="💰" color="emerald" href="/admin/revenue" />
        <StatCard
          label="Active Sessions"
          value={overview.activeSessions}
          icon="🟢"
          color="emerald"
          href="/admin/activity"
        />
        <StatCard
          label="Failed Logins 24h"
          value={overview.failedLoginsLast24h}
          icon="⚠️"
          color={overview.failedLoginsLast24h > 0 ? "rose" : "gray"}
          href="/admin/activity"
        />
      </div>

      {/* Revenue & Conversions */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-sm font-semibold text-gray-400 mb-4">REVENUE OVERVIEW</h3>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <div className="text-2xl font-bold text-emerald-400">${overview.mrr.toFixed(2)}</div>
              <div className="text-gray-400 text-sm">Monthly Recurring</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-rose-400">{overview.proFamilies}</div>
              <div className="text-gray-400 text-sm">Pro Families</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-gray-500">{overview.freeFamilies}</div>
              <div className="text-gray-400 text-sm">Free Families</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-amber-400">${overview.avgRevenuePerUser}</div>
              <div className="text-gray-400 text-sm">Avg per Family</div>
            </div>
          </div>
        </div>

        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-sm font-semibold text-gray-400 mb-4">CONVERSION & ACTIVITY</h3>
          <div className="grid grid-cols-2 gap-4">
            <div className="flex flex-col items-center justify-center bg-gray-700 rounded-xl p-4">
              <div className="text-3xl font-bold text-rose-400">{conversions.conversionRate}%</div>
              <div className="text-gray-400 text-sm text-center mt-1">Pro Adoption Rate</div>
            </div>
            <div className="space-y-3">
              <div>
                <div className="text-xl font-bold text-blue-400">{overview.loginsLast24h}</div>
                <div className="text-gray-400 text-xs">Logins (24h)</div>
              </div>
              <div>
                <div className={`text-xl font-bold ${overview.failedLoginsLast24h > 0 ? "text-rose-400" : "text-gray-500"}`}>
                  {overview.failedLoginsLast24h}
                </div>
                <div className="text-gray-400 text-xs">Failed (24h)</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Growth Charts */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <ChartCard title="New Families" data={growth.familiesByDay} icon="📈" color="rose" />
        <ChartCard title="New Users" data={growth.usersByDay} icon="👥" color="blue" />
      </div>

      {/* Children by Age */}
      {childrenByAge.length > 0 && (
        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-sm font-semibold text-gray-400 mb-4">CHILDREN BY AGE GROUP</h3>
          <div className="flex flex-wrap gap-3">
            {childrenByAge.map((item) => (
              <div key={item.ageGroup} className="bg-gray-700 px-5 py-3 rounded-xl text-center">
                <div className="text-2xl font-bold text-amber-400">{item.count}</div>
                <div className="text-xs text-gray-400 mt-0.5">{item.ageGroup}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Quick Links */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        {[
          { label: "View All Families", href: "/admin/families", icon: "🏠" },
          { label: "Manage Users", href: "/admin/users", icon: "👥" },
          { label: "Activity Log", href: "/admin/activity", icon: "🔍" },
          { label: "Support Tickets", href: "/admin/support", icon: "🎫" },
        ].map(({ label, href, icon }) => (
          <Link
            key={href}
            href={href}
            className="bg-gray-800 hover:bg-gray-700 p-4 rounded-xl flex items-center gap-3 transition-colors group"
          >
            <span className="text-xl">{icon}</span>
            <span className="text-sm text-gray-400 group-hover:text-white transition-colors">{label}</span>
          </Link>
        ))}
      </div>
    </div>
  );
}

function StatCard({
  label,
  value,
  icon,
  color,
  href,
}: {
  label: string;
  value: number | string;
  icon: string;
  color: string;
  href?: string;
}) {
  const colorClasses: Record<string, string> = {
    rose: "text-rose-400",
    blue: "text-blue-400",
    amber: "text-amber-400",
    emerald: "text-emerald-400",
    gray: "text-gray-500",
  };

  const card = (
    <div className="bg-gray-800 p-5 rounded-xl hover:bg-gray-750 transition-colors h-full">
      <div className="text-xl mb-2">{icon}</div>
      <div className={`text-2xl font-bold ${colorClasses[color] || "text-white"}`}>{value}</div>
      <div className="text-gray-400 text-xs mt-1">{label}</div>
    </div>
  );

  if (href) {
    return <Link href={href} className="block">{card}</Link>;
  }
  return card;
}

function ChartCard({
  title,
  data,
  icon,
  color,
}: {
  title: string;
  data: { date: string; count: number }[];
  icon: string;
  color: "rose" | "blue";
}) {
  const maxCount = Math.max(...data.map((d) => d.count), 1);
  const barColor = color === "rose" ? "bg-rose-500" : "bg-blue-500";

  return (
    <div className="bg-gray-800 p-6 rounded-xl">
      <h3 className="text-sm font-semibold text-gray-400 mb-4">
        {icon} {title.toUpperCase()}
      </h3>
      <div className="h-36 flex items-end gap-1">
        {data.slice(-14).map((d, i) => (
          <div key={i} className="flex-1 flex flex-col items-center gap-1 group">
            <div className="relative w-full">
              {d.count > 0 && (
                <div className="absolute bottom-full mb-1 left-1/2 -translate-x-1/2 bg-gray-700 text-white text-xs px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 whitespace-nowrap pointer-events-none z-10">
                  {d.count}
                </div>
              )}
              <div
                className={`w-full ${barColor} rounded-t opacity-80`}
                style={{ height: `${(d.count / maxCount) * 100}%`, minHeight: d.count > 0 ? "4px" : "0" }}
              />
            </div>
            <div className="text-[7px] text-gray-600 truncate w-full text-center">
              {d.date?.slice(5) || ""}
            </div>
          </div>
        ))}
      </div>
      {data.length === 0 && (
        <div className="h-36 flex items-center justify-center text-gray-600 text-sm">
          No activity in this period
        </div>
      )}
    </div>
  );
}
