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 { ArrowLeft, Users, Mail, Phone, MessageSquare, Calendar } from "lucide-react";
import { LeadsExportButton } from "@/components/dashboard/LeadsExportButton";
import { PLAN_LIMITS } from "@/lib/usage";

export default async function LeadsPage({ 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 }, include: { config: true } });
  if (!bot) notFound();

  const sub = await prisma.subscription.findUnique({ where: { userId }, select: { plan: true } });
  const plan = (sub?.plan ?? "FREE") as keyof typeof PLAN_LIMITS;
  const canExport = PLAN_LIMITS[plan]?.export ?? false;

  const leads = await prisma.lead.findMany({
    where: { botId },
    orderBy: { capturedAt: "desc" },
    include: { conversation: { select: { id: true, _count: { select: { messages: true } } } } },
  });

  return (
    <div className="p-8 bg-dots min-h-full">
      {/* Header */}
      <div className="flex items-center justify-between mb-6 animate-fade-up">
        <div className="flex items-center gap-4">
          <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-black text-white">Leaduri capturate</h1>
            <p className="text-slate-500 text-sm mt-0.5">{bot.name} — {leads.length} leaduri totale</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          {leads.length > 0 && <LeadsExportButton leads={leads} botName={bot.name} canExport={canExport} />}
        </div>
      </div>

      {/* Lead capture disabled warning */}
      {!bot.config?.leadCaptureEnabled && (
        <div className="rounded-2xl border border-amber-500/25 p-4 mb-5 flex items-center justify-between animate-fade-up"
          style={{ animationDelay: "60ms", background: "rgba(245,158,11,0.06)" }}>
          <div>
            <p className="text-sm font-semibold text-amber-300">Capturarea leadurilor nu este activata</p>
            <p className="text-xs text-amber-500/80 mt-0.5">Activeaza din Configurare pentru a colecta automat date de contact de la vizitatori.</p>
          </div>
          <Link href={`/bots/${botId}/configure`}
            className="text-xs bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500/30 text-amber-300 px-4 py-2 rounded-xl transition-all font-semibold shrink-0 ml-4">
            Activeaza →
          </Link>
        </div>
      )}

      {/* Stats row */}
      {leads.length > 0 && (
        <div className="grid grid-cols-3 gap-3 mb-5 animate-fade-up" style={{ animationDelay: "100ms" }}>
          {[
            { label: "Total leaduri", value: leads.length, color: "pink" },
            { label: "Cu email", value: leads.filter(l => l.email).length, color: "indigo" },
            { label: "Cu telefon", value: leads.filter(l => l.phone).length, color: "violet" },
          ].map(({ label, value, color }) => (
            <div key={label} className="rounded-2xl border border-white/[0.07] p-4" style={{ background: "var(--bg-card)" }}>
              <p className={`text-2xl font-black text-${color}-400`}>{value}</p>
              <p className="text-xs text-slate-500 mt-1">{label}</p>
            </div>
          ))}
        </div>
      )}

      {/* Table */}
      <div className="rounded-2xl border border-white/[0.07] overflow-hidden animate-fade-up" style={{ animationDelay: "140ms", background: "var(--bg-card)" }}>
        {leads.length === 0 ? (
          <div className="py-20 text-center">
            <div className="w-14 h-14 bg-pink-500/10 border border-pink-500/20 rounded-2xl flex items-center justify-center mx-auto mb-4 animate-float">
              <Users className="w-7 h-7 text-pink-400" />
            </div>
            <p className="text-white font-semibold mb-1">Niciun lead capturat inca</p>
            <p className="text-slate-500 text-sm mb-5">Activeaza capturarea si clientii isi vor lasa datele inainte de chat.</p>
            <Link href={`/bots/${botId}/configure`}
              className="inline-flex items-center gap-2 bg-gradient-to-r from-indigo-600 to-violet-600 text-white px-5 py-2.5 rounded-xl text-sm font-bold shadow-lg shadow-indigo-500/25">
              Activeaza capturare leaduri
            </Link>
          </div>
        ) : (
          <>
            <div className="grid grid-cols-[2fr_1.5fr_1fr_1fr_80px] px-5 py-3 border-b border-white/[0.05] text-xs font-semibold text-slate-600 uppercase tracking-wider"
              style={{ background: "rgba(255,255,255,0.01)" }}>
              <div>Contact</div>
              <div>Email</div>
              <div>Telefon</div>
              <div>Conversatie</div>
              <div>Data</div>
            </div>

            <div className="divide-y divide-white/[0.04]">
              {leads.map((lead, i) => (
                <div key={lead.id}
                  className="grid grid-cols-[2fr_1.5fr_1fr_1fr_80px] px-5 py-3.5 items-center hover:bg-white/[0.02] transition-colors animate-fade-up"
                  style={{ animationDelay: `${180 + i * 30}ms` }}>

                  {/* Name */}
                  <div className="flex items-center gap-2.5">
                    <div className="w-7 h-7 rounded-full bg-pink-500/15 border border-pink-500/20 flex items-center justify-center shrink-0 text-xs font-bold text-pink-400">
                      {lead.name?.[0]?.toUpperCase() ?? lead.email?.[0]?.toUpperCase() ?? "?"}
                    </div>
                    <span className="text-sm font-medium text-white">{lead.name ?? <span className="text-slate-600">—</span>}</span>
                  </div>

                  {/* Email */}
                  <div>
                    {lead.email ? (
                      <a href={`mailto:${lead.email}`}
                        className="flex items-center gap-1.5 text-xs text-indigo-400 hover:text-indigo-300 transition-colors group max-w-fit">
                        <Mail className="w-3 h-3 shrink-0" />
                        <span className="truncate max-w-[150px]">{lead.email}</span>
                      </a>
                    ) : <span className="text-slate-700 text-sm">—</span>}
                  </div>

                  {/* Phone */}
                  <div>
                    {lead.phone ? (
                      <a href={`tel:${lead.phone}`}
                        className="flex items-center gap-1.5 text-xs text-violet-400 hover:text-violet-300 transition-colors">
                        <Phone className="w-3 h-3 shrink-0" />
                        {lead.phone}
                      </a>
                    ) : <span className="text-slate-700 text-sm">—</span>}
                  </div>

                  {/* Conversation link */}
                  <div>
                    <Link href={`/bots/${botId}/conversations/${lead.conversationId}`}
                      className="flex items-center gap-1.5 text-xs text-blue-400 hover:text-blue-300 transition-colors">
                      <MessageSquare className="w-3 h-3 shrink-0" />
                      {lead.conversation._count.messages} mesaje
                    </Link>
                  </div>

                  {/* Date */}
                  <div className="flex items-center gap-1 text-xs text-slate-600">
                    <Calendar className="w-3 h-3 shrink-0" />
                    {new Date(lead.capturedAt).toLocaleDateString("ro-RO", { day: "numeric", month: "short" })}
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
}
