import {notFound, redirect} from "next/navigation";
import Link from "next/link";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Button} from "@/components/ui/button";
import {ArrowLeft, Car, Calendar, User, DollarSign} from "lucide-react";
import {BookingStatusActions} from "./booking-status-actions";

type BookingDetailPageProps = {
  params: Promise<{tenantSlug: string; bookingId: string; locale: string}>;
};

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

export default async function BookingDetailPage({params}: BookingDetailPageProps) {
  const {tenantSlug, bookingId, 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 booking = await db.booking.findFirst({
    where: {id: bookingId},
    include: {
      vehicle: {include: {brand: true}},
      customerProfile: {include: {user: true}},
      pickupBranch: true,
      dropoffBranch: true
    }
  });

  if (!booking) notFound();

  const customerUser = booking.customerProfile.user;
  const customerName = customerUser.firstName
    ? `${customerUser.firstName} ${customerUser.lastName ?? ""}`
    : customerUser.email;

  return (
    <div className="space-y-6 max-w-4xl">
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <Link href={`/company/${tenantSlug}/bookings`}>
            <Button variant="ghost" size="sm">
              <ArrowLeft className="mr-1 h-4 w-4" />
              Bookings
            </Button>
          </Link>
          <div>
            <h1 className="text-xl font-bold text-slate-900">Booking Details</h1>
            <p className="font-mono text-sm text-slate-500">{booking.bookingNumber}</p>
          </div>
        </div>
        <span className={`rounded-full border px-3 py-1 text-sm font-medium ${statusColors[booking.status] ?? "bg-slate-100 text-slate-700 border-slate-200"}`}>
          {booking.status.replace(/_/g, " ")}
        </span>
      </div>

      <div className="grid gap-5 lg:grid-cols-2">
        {/* Customer */}
        <Card>
          <CardHeader><CardTitle className="flex items-center gap-2"><User className="h-4 w-4 text-blue-600" />Customer</CardTitle></CardHeader>
          <CardContent className="space-y-2 text-sm">
            <div className="flex justify-between"><span className="text-slate-500">Name</span><span className="font-medium">{customerName}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Email</span><span className="font-medium">{customerUser.email}</span></div>
            {customerUser.phone && <div className="flex justify-between"><span className="text-slate-500">Phone</span><span className="font-medium">{customerUser.phone}</span></div>}
            {booking.customerProfile.driverLicenseNumber && (
              <div className="flex justify-between"><span className="text-slate-500">License</span><span className="font-medium">{booking.customerProfile.driverLicenseNumber}</span></div>
            )}
          </CardContent>
        </Card>

        {/* Vehicle */}
        <Card>
          <CardHeader><CardTitle className="flex items-center gap-2"><Car className="h-4 w-4 text-blue-600" />Vehicle</CardTitle></CardHeader>
          <CardContent className="space-y-2 text-sm">
            <div className="flex justify-between"><span className="text-slate-500">Vehicle</span><span className="font-medium">{booking.vehicle.brand.name} {booking.vehicle.name}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Plate</span><span className="font-medium">{booking.vehicle.plateNumber}</span></div>
            <Link href={`/company/${tenantSlug}/fleet/${booking.vehicle.id}`} className="text-xs text-blue-600 hover:underline">
              View vehicle details →
            </Link>
          </CardContent>
        </Card>

        {/* Dates */}
        <Card>
          <CardHeader><CardTitle className="flex items-center gap-2"><Calendar className="h-4 w-4 text-blue-600" />Rental Dates</CardTitle></CardHeader>
          <CardContent className="space-y-2 text-sm">
            <div className="flex justify-between"><span className="text-slate-500">Pickup</span><span className="font-medium">{new Date(booking.pickupAt).toLocaleString()}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Return</span><span className="font-medium">{new Date(booking.dropoffAt).toLocaleString()}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Duration</span><span className="font-medium">{Number(booking.rentalDays)} day(s)</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Pickup Branch</span><span className="font-medium">{booking.pickupBranch.name}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Return Branch</span><span className="font-medium">{booking.dropoffBranch.name}</span></div>
          </CardContent>
        </Card>

        {/* Pricing */}
        <Card>
          <CardHeader><CardTitle className="flex items-center gap-2"><DollarSign className="h-4 w-4 text-blue-600" />Pricing</CardTitle></CardHeader>
          <CardContent className="space-y-2 text-sm">
            <div className="flex justify-between"><span className="text-slate-500">Daily Rate</span><span>${Number(booking.dailyRate).toFixed(2)}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Rental Days</span><span>{Number(booking.rentalDays)}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Subtotal</span><span>${Number(booking.subtotal).toFixed(2)}</span></div>
            {Number(booking.discountAmount) > 0 && <div className="flex justify-between"><span className="text-slate-500">Discount</span><span className="text-green-600">-${Number(booking.discountAmount).toFixed(2)}</span></div>}
            <div className="flex justify-between"><span className="text-slate-500">Deposit</span><span>${Number(booking.depositAmount).toFixed(2)}</span></div>
            <hr className="border-slate-100" />
            <div className="flex justify-between font-bold text-base"><span>Total</span><span>${Number(booking.totalAmount).toFixed(2)} {booking.currency}</span></div>
          </CardContent>
        </Card>
      </div>

      {/* Status Actions */}
      <BookingStatusActions
        bookingId={booking.id}
        currentStatus={booking.status}
        tenantSlug={tenantSlug}
      />

      {booking.notes && (
        <Card>
          <CardHeader><CardTitle>Notes</CardTitle></CardHeader>
          <CardContent><p className="text-sm text-slate-600">{booking.notes}</p></CardContent>
        </Card>
      )}
    </div>
  );
}
