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 { Calendar, Clock, Users, Phone, Mail, ArrowLeft, CalendarCheck, CheckCircle, XCircle, AlertCircle } from "lucide-react";
import { BookingActions } from "@/components/dashboard/BookingActions";

const STATUS_CONFIG: Record<string, { label: string; icon: typeof CheckCircle; cls: string }> = {
  PENDING:   { label: "In asteptare", icon: AlertCircle,  cls: "bg-amber-500/10 text-amber-400 border-amber-500/20" },
  CONFIRMED: { label: "Confirmat",    icon: CheckCircle,  cls: "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" },
  CANCELLED: { label: "Anulat",       icon: XCircle,      cls: "bg-red-500/10 text-red-400 border-red-500/20" },
};

export default async function BookingsPage({ 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();

  const bookings = await prisma.booking.findMany({
    where: { botId },
    orderBy: { createdAt: "desc" },
    include: { conversation: { select: { id: true } } },
  });

  const pending = bookings.filter(b => b.status === "PENDING").length;
  const confirmed = bookings.filter(b => b.status === "CONFIRMED").length;

  return (
    <div className="p-8 max-w-4xl mx-auto">
      {/* Header */}
      <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 className="flex-1">
          <h1 className="text-2xl font-bold text-white">Rezervari & Programari</h1>
          <p className="text-slate-500 text-sm mt-0.5">{bot.name} · {bookings.length} total</p>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        {[
          { label: "Total rezervari", value: bookings.length, icon: CalendarCheck, color: "indigo" },
          { label: "In asteptare", value: pending, icon: AlertCircle, color: "amber" },
          { label: "Confirmate", value: confirmed, icon: CheckCircle, color: "emerald" },
        ].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-2xl font-bold text-white">{value}</p>
            <p className="text-xs text-slate-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      {/* How bookings work info */}
      <div className="bg-indigo-500/8 border border-indigo-500/15 rounded-2xl p-4 mb-6">
        <p className="text-sm text-indigo-300 font-semibold mb-1">Cum se capteaza rezervarile?</p>
        <p className="text-xs text-indigo-400/80 leading-relaxed">
          Cand un client face o rezervare prin chat, botul detecteaza automat informatiile (data, ora, persoane, telefon)
          si le salveaza aici. Asigura-te ca instructiunile botului includ colectarea acestor date.
          Poti vedea conversatia completa pentru fiecare rezervare.
        </p>
      </div>

      {/* Bookings list */}
      {bookings.length === 0 ? (
        <div className="bg-white/[0.03] border border-white/[0.07] rounded-2xl py-16 text-center">
          <div className="w-14 h-14 bg-indigo-500/10 border border-indigo-500/20 rounded-2xl flex items-center justify-center mx-auto mb-4 text-2xl">
            📅
          </div>
          <p className="text-white font-semibold mb-1">Nicio rezervare inca</p>
          <p className="text-slate-500 text-sm max-w-xs mx-auto">
            Rezervarile facute prin chatbot vor aparea automat aici. Asigura-te ca botul este activ si instalat pe site.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {bookings.map((booking) => {
            const cfg = STATUS_CONFIG[booking.status] ?? STATUS_CONFIG.PENDING;
            const StatusIcon = cfg.icon;
            return (
              <div key={booking.id} className="bg-white/[0.03] border border-white/[0.07] hover:border-white/[0.12] rounded-2xl p-5 transition-all">
                <div className="flex items-start justify-between gap-4">
                  <div className="flex-1 grid grid-cols-2 md:grid-cols-4 gap-4">
                    {/* Name */}
                    <div>
                      <p className="text-xs text-slate-500 mb-1">Client</p>
                      <p className="text-sm font-semibold text-white">{booking.name ?? "—"}</p>
                      {booking.email && (
                        <div className="flex items-center gap-1 mt-1">
                          <Mail className="w-3 h-3 text-slate-600" />
                          <a href={`mailto:${booking.email}`} className="text-xs text-indigo-400 hover:text-indigo-300">{booking.email}</a>
                        </div>
                      )}
                      {booking.phone && (
                        <div className="flex items-center gap-1 mt-0.5">
                          <Phone className="w-3 h-3 text-slate-600" />
                          <a href={`tel:${booking.phone}`} className="text-xs text-slate-400">{booking.phone}</a>
                        </div>
                      )}
                    </div>

                    {/* Date & Time */}
                    <div>
                      <p className="text-xs text-slate-500 mb-1">Data & Ora</p>
                      {booking.date ? (
                        <div className="flex items-center gap-1.5">
                          <Calendar className="w-3.5 h-3.5 text-indigo-400" />
                          <span className="text-sm font-semibold text-white">{booking.date}</span>
                        </div>
                      ) : <p className="text-sm text-slate-600">—</p>}
                      {booking.time && (
                        <div className="flex items-center gap-1.5 mt-0.5">
                          <Clock className="w-3.5 h-3.5 text-slate-500" />
                          <span className="text-sm text-slate-300">{booking.time}</span>
                        </div>
                      )}
                    </div>

                    {/* Persons */}
                    <div>
                      <p className="text-xs text-slate-500 mb-1">Persoane</p>
                      {booking.persons ? (
                        <div className="flex items-center gap-1.5">
                          <Users className="w-3.5 h-3.5 text-slate-400" />
                          <span className="text-sm font-semibold text-white">{booking.persons} pers.</span>
                        </div>
                      ) : <p className="text-sm text-slate-600">—</p>}
                      {booking.notes && (
                        <p className="text-xs text-slate-500 mt-1 line-clamp-1">{booking.notes}</p>
                      )}
                    </div>

                    {/* Created */}
                    <div>
                      <p className="text-xs text-slate-500 mb-1">Primit la</p>
                      <p className="text-sm text-slate-400">
                        {new Date(booking.createdAt).toLocaleDateString("ro-RO", { day: "numeric", month: "short" })}
                      </p>
                      <p className="text-xs text-slate-600">
                        {new Date(booking.createdAt).toLocaleTimeString("ro-RO", { hour: "2-digit", minute: "2-digit" })}
                      </p>
                      {booking.conversation && (
                        <Link href={`/bots/${botId}/conversations/${booking.conversation.id}`}
                          className="text-xs text-indigo-400 hover:text-indigo-300 mt-1 block">
                          Vezi conversatia →
                        </Link>
                      )}
                    </div>
                  </div>

                  {/* Status + Actions */}
                  <div className="flex flex-col items-end gap-2 shrink-0">
                    <div className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-xs font-semibold ${cfg.cls}`}>
                      <StatusIcon className="w-3 h-3" />
                      {cfg.label}
                    </div>
                    <BookingActions bookingId={booking.id} status={booking.status} />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
