import Link from "next/link";
import {notFound, redirect} from "next/navigation";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {Button} from "@/components/ui/button";
import {Plus} from "lucide-react";

export default async function BookingsPage({params}: {params: Promise<{tenantSlug: string; locale: string}>}) {
  const {tenantSlug, locale} = await params;
  const session = await auth();
  if (!session?.user?.id) redirect(`/${locale}/auth/sign-in`);

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) notFound();

  const db = getTenantDb(tenant.id);
  const bookings = await db.booking.findMany({
    include: {
      vehicle: {include: {brand: true}},
      customerProfile: {include: {user: {select: {firstName: true, lastName: true, email: true}}}}
    },
    orderBy: {createdAt: "desc"}
  });

  const statusColors: Record<string, string> = {
    PENDING_APPROVAL: "bg-yellow-100 text-yellow-700",
    CONFIRMED: "bg-blue-100 text-blue-700",
    ACTIVE: "bg-green-100 text-green-700",
    COMPLETED: "bg-slate-100 text-slate-600",
    CANCELLED: "bg-red-100 text-red-700"
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Bookings</h1>
          <p className="mt-1 text-slate-500">{bookings.length} bookings</p>
        </div>
        <Link href={`/${locale}/company/${tenantSlug}/bookings/new`}>
          <Button className="gap-2"><Plus className="h-4 w-4" />New Booking</Button>
        </Link>
      </div>
      <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="px-3 py-3 text-left font-semibold">Booking #</th>
              <th className="px-3 py-3 text-left font-semibold">Customer</th>
              <th className="px-3 py-3 text-left font-semibold">Vehicle</th>
              <th className="px-3 py-3 text-left font-semibold">Dates</th>
              <th className="px-3 py-3 text-left font-semibold">Status</th>
              <th className="px-3 py-3 text-left font-semibold">Total</th>
              <th className="px-3 py-3 text-left font-semibold">Actions</th>
            </tr>
          </thead>
          <tbody>
            {bookings.map((b) => (
              <tr key={b.id} className="border-b border-slate-100 hover:bg-slate-50">
                <td className="px-3 py-3 font-mono text-xs text-blue-600">
                  <Link href={`/${locale}/company/${tenantSlug}/bookings/${b.id}`} className="hover:underline">{b.bookingNumber}</Link>
                </td>
                <td className="px-3 py-3">{b.customerProfile.user.firstName ? `${b.customerProfile.user.firstName} ${b.customerProfile.user.lastName || ""}` : b.customerProfile.user.email}</td>
                <td className="px-3 py-3">{b.vehicle.brand.name} {b.vehicle.name}</td>
                <td className="px-3 py-3 text-xs">{new Date(b.pickupAt).toLocaleDateString()} → {new Date(b.dropoffAt).toLocaleDateString()}</td>
                <td className="px-3 py-3"><span className={`rounded-full px-2 py-0.5 text-xs font-medium ${statusColors[b.status] || "bg-slate-100"}`}>{b.status.replace(/_/g, " ")}</span></td>
                <td className="px-3 py-3 font-semibold">{tenant.currency} {Number(b.totalAmount)}</td>
                <td className="px-3 py-3">
                  <Link href={`/${locale}/company/${tenantSlug}/bookings/${b.id}`}>
                    <button className="rounded-lg border border-slate-200 px-2.5 py-1 text-xs font-medium hover:bg-slate-50">View</button>
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
