import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { notFound } from "next/navigation";
import Link from "next/link";
import { MessageSquare, Users, TrendingUp, Clock, ArrowLeft, Calendar, Lock } from "lucide-react";
import { PLAN_LIMITS } from "@/lib/usage";

export default async function BotAnalyticsPage({ params }: { params: Promise<{ botId: string }> }) {
  const session = await getServerSession(authOptions);
  const userId = (session?.user as any)?.id as string;
  const { botId } = await params;

  const bot = await prisma.bot.findFirst({ where: { id: botId, userId } });
  if (!bot) notFound();

  // Plan check
  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="flex items-center gap-4 mb-8">
          <Link href={`/bots/${botId}`} className="text-slate-600 hover:text-slate-300 transition-colors">
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <h1 className="text-2xl font-bold text-white">Statistici</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 [totalConversations, totalMessages, last30Messages, totalLeads, totalBookings] = await Promise.all([
    prisma.conversation.count({ where: { botId } }),
    prisma.message.count({ where: { conversation: { botId } } }),
    prisma.message.count({ where: { conversation: { botId }, createdAt: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } } }),
    prisma.lead.count({ where: { botId } }),
    prisma.booking.count({ where: { botId } }),
  ]);

  // Last 7 days
  const last7 = await Promise.all(
    Array.from({ length: 7 }).map(async (_, i) => {
      const day = new Date();
      day.setDate(day.getDate() - (6 - i));
      const start = new Date(new Date(day).setHours(0, 0, 0, 0));
      const end = new Date(new Date(day).setHours(23, 59, 59, 999));
      const count = await prisma.message.count({
        where: { conversation: { botId }, createdAt: { gte: start, lte: end } },
      });
      return { label: start.toLocaleDateString("ro-RO", { weekday: "short" }), count };
    })
  );

  const maxCount = Math.max(...last7.map(d => d.count), 1);

  const recentConvs = await prisma.conversation.findMany({
    where: { botId },
    orderBy: { lastMessageAt: "desc" },
    take: 8,
    include: { _count: { select: { messages: true } }, lead: { select: { name: true } } },
  });

  return (
    <div className="p-8 max-w-4xl mx-auto">
      <div className="flex items-center gap-4 mb-8">
        <Link href={`/bots/${botId}`} className="text-slate-600 hover:text-slate-300 transition-colors">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-white">Statistici</h1>
          <p className="text-slate-500 text-sm mt-0.5">{bot.name}</p>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
        {[
          { label: "Conversatii", value: totalConversations, icon: Users, color: "indigo" },
          { label: "Total mesaje", value: totalMessages, icon: MessageSquare, color: "violet" },
          { label: "Mesaje (30 zile)", value: last30Messages, icon: TrendingUp, color: "cyan" },
          { label: "Leaduri", value: totalLeads, icon: Users, color: "pink" },
          { label: "Rezervari", value: totalBookings, icon: Calendar, color: "emerald" },
          { label: "Medie msg/conv", value: totalConversations > 0 ? (totalMessages / totalConversations).toFixed(1) : "0", icon: Clock, color: "amber" },
        ].slice(0, 5).map(({ label, value, icon: Icon, color }) => (
          <div key={label} className="bg-white/[0.03] border border-white/[0.07] rounded-2xl p-4">
            <div className={`w-8 h-8 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-xl font-bold text-white">{value}</p>
            <p className="text-xs text-slate-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      {/* Bar chart */}
      <div className="bg-white/[0.03] border border-white/[0.07] rounded-2xl p-6 mb-5">
        <h2 className="font-semibold text-white text-sm mb-6">Mesaje pe zi — ultimele 7 zile</h2>
        <div className="flex items-end gap-3 h-36">
          {last7.map((day, i) => (
            <div key={i} className="flex-1 flex flex-col items-center gap-2">
              <span className="text-xs text-slate-600">{day.count > 0 ? day.count : ""}</span>
              <div className="w-full relative rounded-t-lg overflow-hidden" style={{ height: "96px", backgroundColor: "rgba(255,255,255,0.04)" }}>
                <div
                  className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-indigo-600 to-violet-500 rounded-t-lg transition-all"
                  style={{ height: `${Math.max((day.count / maxCount) * 100, day.count > 0 ? 4 : 0)}%` }}
                />
              </div>
              <span className="text-xs text-slate-500 capitalize">{day.label}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Recent conversations */}
      <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">Conversatii recente</h2>
        </div>
        {recentConvs.length === 0 ? (
          <div className="py-10 text-center text-slate-500 text-sm">
            Nicio conversatie inca. Activeaza botul si instaleaza-l pe site.
          </div>
        ) : (
          <div className="divide-y divide-white/[0.04]">
            {recentConvs.map((conv) => (
              <Link key={conv.id} href={`/bots/${botId}/conversations/${conv.id}`}
                className="flex items-center justify-between px-5 py-3.5 hover:bg-white/[0.02] transition-colors">
                <div>
                  <p className="text-sm font-medium text-white">
                    {conv.lead?.name ?? `Sesiune ${conv.sessionId.slice(0, 8)}...`}
                  </p>
                  <p className="text-xs text-slate-500">
                    {new Date(conv.startedAt).toLocaleDateString("ro-RO", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" })}
                  </p>
                </div>
                <div className="flex items-center gap-3">
                  <span className="text-xs text-slate-600">{conv._count.messages} mesaje</span>
                  <span className={`text-xs px-2.5 py-1 rounded-full border font-medium ${conv.channel === "WIDGET" ? "bg-blue-500/10 text-blue-400 border-blue-500/20" : "bg-green-500/10 text-green-400 border-green-500/20"}`}>
                    {conv.channel === "WIDGET" ? "Site" : "WhatsApp"}
                  </span>
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
