import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { BarChart2, MessageSquare, Users, TrendingUp, CalendarCheck, Lock } from "lucide-react";
import { PLAN_LIMITS } from "@/lib/usage";

export default async function AnalyticsPage() {
  const session = await getServerSession(authOptions);
  const userId = (session?.user as any)?.id as string;

  // Plan check — analytics requires STARTER or above
  const sub = await prisma.subscription.findUnique({ where: { userId }, select: { plan: true } });
  const plan = (sub?.plan ?? "FREE") as keyof typeof PLAN_LIMITS;
  if (!PLAN_LIMITS[plan]?.analytics) {
    return (
      <div className="p-8 max-w-4xl mx-auto">
        <div className="mb-8">
          <h1 className="text-2xl font-bold text-white">Statistici globale</h1>
        </div>
        <div className="rounded-2xl border border-indigo-500/20 p-14 text-center" style={{ background: "linear-gradient(135deg, rgba(99,102,241,0.06), rgba(139,92,246,0.06))" }}>
          <div className="w-16 h-16 rounded-2xl bg-indigo-500/10 border border-indigo-500/20 flex items-center justify-center mx-auto mb-5">
            <Lock className="w-7 h-7 text-indigo-400" />
          </div>
          <h2 className="text-xl font-bold text-white mb-2">Statistici disponibile din planul Starter</h2>
          <p className="text-slate-400 text-sm mb-1">Urmareste conversatiile, mesajele si leadurile in timp real.</p>
          <p className="text-slate-500 text-xs mb-7">Planul tau curent: <span className="text-white font-semibold">{plan}</span></p>
          <Link href="/billing"
            className="inline-flex items-center gap-2 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 text-white px-7 py-3 rounded-xl text-sm font-bold transition-all shadow-lg shadow-indigo-500/20">
            Upgrade la Starter →
          </Link>
        </div>
      </div>
    );
  }

  const bots = await prisma.bot.findMany({
    where: { userId },
    include: { _count: { select: { conversations: true, leads: true, bookings: true } } },
  });

  const botStats = await Promise.all(
    bots.map(async (bot) => {
      const [messages, last7] = await Promise.all([
        prisma.message.count({ where: { conversation: { botId: bot.id } } }),
        prisma.message.count({ where: { conversation: { botId: bot.id }, createdAt: { gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) } } }),
      ]);
      return { ...bot, messages, last7 };
    })
  );

  const totalMessages = botStats.reduce((a, b) => a + b.messages, 0);
  const totalConvs = botStats.reduce((a, b) => a + b._count.conversations, 0);
  const totalLeads = botStats.reduce((a, b) => a + b._count.leads, 0);
  const totalBookings = botStats.reduce((a, b) => a + b._count.bookings, 0);

  return (
    <div className="p-8">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-white">Statistici globale</h1>
        <p className="text-slate-500 mt-1 text-sm">Performanta tuturor chatbotilor tai.</p>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        {[
          { label: "Total mesaje", value: totalMessages, icon: MessageSquare, color: "indigo" },
          { label: "Total conversatii", value: totalConvs, icon: BarChart2, color: "violet" },
          { label: "Leaduri capturate", value: totalLeads, icon: Users, color: "pink" },
          { label: "Rezervari", value: totalBookings, icon: CalendarCheck, color: "emerald" },
        ].map(({ label, value, icon: Icon, color }) => (
          <div key={label} className="bg-white/[0.03] border border-white/[0.07] rounded-2xl p-5">
            <div className={`w-9 h-9 rounded-xl bg-${color}-500/10 border border-${color}-500/20 flex items-center justify-center mb-3`}>
              <Icon className={`w-4 h-4 text-${color}-400`} />
            </div>
            <p className="text-2xl font-bold text-white">{value.toLocaleString()}</p>
            <p className="text-xs text-slate-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      <div className="bg-white/[0.03] border border-white/[0.07] rounded-2xl overflow-hidden">
        <div className="px-5 py-4 border-b border-white/[0.06]">
          <h2 className="font-semibold text-white text-sm">Performanta per chatbot</h2>
        </div>
        {botStats.length === 0 ? (
          <div className="py-12 text-center text-slate-500 text-sm">
            Niciun chatbot inca. Creeaza primul pentru a vedea statistici.
          </div>
        ) : (
          <div className="divide-y divide-white/[0.04]">
            {botStats.map((bot) => (
              <div key={bot.id} className="flex items-center justify-between px-5 py-4">
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 bg-indigo-500/10 border border-indigo-500/20 rounded-xl flex items-center justify-center text-base">🤖</div>
                  <div>
                    <p className="text-sm font-medium text-white">{bot.name}</p>
                    <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                      bot.status === "ACTIVE" ? "bg-emerald-500/10 text-emerald-400" : "bg-white/[0.05] text-slate-500"
                    }`}>
                      {bot.status === "ACTIVE" ? "● Activ" : "○ Draft"}
                    </span>
                  </div>
                </div>
                <div className="flex items-center gap-6 text-right">
                  <div>
                    <p className="text-sm font-semibold text-white">{bot.messages.toLocaleString()}</p>
                    <p className="text-xs text-slate-500">mesaje</p>
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-white">{bot._count.conversations}</p>
                    <p className="text-xs text-slate-500">conversatii</p>
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-pink-400">{bot._count.leads}</p>
                    <p className="text-xs text-slate-500">leaduri</p>
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-emerald-400">{bot._count.bookings}</p>
                    <p className="text-xs text-slate-500">rezervari</p>
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-indigo-400">+{bot.last7}</p>
                    <p className="text-xs text-slate-500">7 zile</p>
                  </div>
                  <Link href={`/bots/${bot.id}/analytics`} className="text-xs text-indigo-400 hover:text-indigo-300 font-medium transition-colors">
                    Detalii →
                  </Link>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
