import Link from "next/link";
import {notFound} from "next/navigation";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Badge} from "@/components/ui/badge";
import {Button} from "@/components/ui/button";
import {Car, Phone, MapPin, Calendar, Clock, AlertTriangle, CheckCircle, FileSignature, CalendarDays} from "lucide-react";

type MonitoringPageProps = {
  params: Promise<{tenantSlug: string}>;
};

export default async function MonitoringPage({params}: MonitoringPageProps) {
  const {tenantSlug} = await params;

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

  const db = getTenantDb(tenant.id);
  const now = new Date();

  // Vehicles currently rented
  const rentedVehicles = await db.booking.findMany({
    where: {status: {in: ["ACTIVE", "CONFIRMED"]}, dropoffAt: {gte: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)}},
    include: {
      vehicle: {include: {brand: true, model: true}},
      customerProfile: {include: {user: {select: {firstName: true, lastName: true, email: true, phone: true}}}},
      pickupBranch: {select: {name: true}},
      dropoffBranch: {select: {name: true}},
      invoices: {select: {status: true, paidAmount: true, totalAmount: true}, take: 1},
      contract: {select: {id: true, contractNumber: true}}
    },
    orderBy: {dropoffAt: "asc"}
  });

  // Fleet summary
  const fleetSummary = await db.vehicle.groupBy({
    by: ["status"],
    _count: {_all: true}
  });
  const fleetMap = Object.fromEntries(fleetSummary.map((f) => [f.status, f._count._all]));

  // Today's returns
  const todayEnd = new Date(now);
  todayEnd.setHours(23, 59, 59, 999);
  const todayStart = new Date(now);
  todayStart.setHours(0, 0, 0, 0);

  const todayReturns = rentedVehicles.filter((b) => {
    const d = new Date(b.dropoffAt);
    return d >= todayStart && d <= todayEnd;
  });

  // Overdue
  const overdue = rentedVehicles.filter((b) => new Date(b.dropoffAt) < now && b.status === "ACTIVE");

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Live Monitoring</h1>
          <p className="mt-1 text-slate-500">Real-time overview of rented vehicles — {tenant.name}</p>
        </div>
        <div className="flex gap-2">
          <Link href={`/company/${tenantSlug}/monitoring/calendar`}>
            <Button variant="outline" size="sm">
              <CalendarDays className="mr-2 h-4 w-4" />
              Calendar View
            </Button>
          </Link>
        </div>
      </div>

      {/* Fleet Status */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {[
          {label: "Rented", count: fleetMap["RENTED"] ?? 0, color: "text-blue-600 bg-blue-50", icon: Car},
          {label: "Available", count: fleetMap["AVAILABLE"] ?? 0, color: "text-green-600 bg-green-50", icon: CheckCircle},
          {label: "Maintenance", count: (fleetMap["MAINTENANCE"] ?? 0), color: "text-orange-600 bg-orange-50", icon: AlertTriangle},
          {label: "Overdue", count: overdue.length, color: "text-red-600 bg-red-50", icon: Clock}
        ].map(({label, count, color, icon: Icon}) => (
          <Card key={label}>
            <CardContent className="flex items-center gap-3 p-4">
              <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${color}`}>
                <Icon className="h-5 w-5" />
              </div>
              <div>
                <p className="text-2xl font-bold text-slate-900">{count}</p>
                <p className="text-xs text-slate-500">{label}</p>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Alerts */}
      {(overdue.length > 0 || todayReturns.length > 0) && (
        <div className="space-y-2">
          {overdue.length > 0 && (
            <div className="flex items-center gap-3 rounded-xl border border-red-200 bg-red-50 p-4">
              <AlertTriangle className="h-5 w-5 shrink-0 text-red-600" />
              <div>
                <p className="font-semibold text-red-700">{overdue.length} Overdue Vehicle{overdue.length > 1 ? "s" : ""}</p>
                <p className="text-sm text-red-600">These vehicles are past their return date</p>
              </div>
            </div>
          )}
          {todayReturns.length > 0 && (
            <div className="flex items-center gap-3 rounded-xl border border-orange-200 bg-orange-50 p-4">
              <Clock className="h-5 w-5 shrink-0 text-orange-600" />
              <div>
                <p className="font-semibold text-orange-700">{todayReturns.length} Vehicle{todayReturns.length > 1 ? "s" : ""} Due Today</p>
                <p className="text-sm text-orange-600">Expected to be returned today</p>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Active Rentals Table */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Car className="h-5 w-5 text-blue-600" />
            Currently Rented ({rentedVehicles.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {rentedVehicles.length === 0 ? (
            <div className="py-12 text-center">
              <Car className="mx-auto mb-3 h-10 w-10 text-slate-300" />
              <p className="text-slate-500">No active rentals at the moment</p>
            </div>
          ) : (
            <div className="space-y-4">
              {rentedVehicles.map((booking) => {
                const daysLeft = Math.ceil((new Date(booking.dropoffAt).getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
                const isOverdue = daysLeft < 0;
                const isDueToday = daysLeft === 0;
                const customerName = [booking.customerProfile.user.firstName, booking.customerProfile.user.lastName].filter(Boolean).join(" ") || booking.customerProfile.user.email;
                const invoice = booking.invoices[0];
                const paymentStatus = invoice ? (Number(invoice.paidAmount) >= Number(invoice.totalAmount) ? "PAID" : "PARTIAL") : "PENDING";

                return (
                  <div
                    key={booking.id}
                    className={`rounded-xl border p-4 transition ${
                      isOverdue
                        ? "border-red-200 bg-red-50"
                        : isDueToday
                        ? "border-orange-200 bg-orange-50"
                        : "border-slate-200 bg-white hover:border-slate-300"
                    }`}
                  >
                    <div className="flex flex-wrap items-start justify-between gap-4">
                      {/* Vehicle + Customer */}
                      <div className="flex gap-4">
                        <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-slate-100">
                          <Car className="h-6 w-6 text-slate-500" />
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <p className="font-semibold text-slate-900">{booking.vehicle.name}</p>
                            <span className="rounded bg-slate-100 px-1.5 py-0.5 font-mono text-xs text-slate-600">{booking.vehicle.plateNumber}</span>
                          </div>
                          <p className="mt-0.5 text-sm text-slate-600">{booking.vehicle.brand.name} — {booking.vehicle.category}</p>
                          <div className="mt-1.5 flex items-center gap-3 text-sm">
                            <span className="font-medium text-slate-900">{customerName}</span>
                            {booking.customerProfile.user.phone && (
                              <a href={`tel:${booking.customerProfile.user.phone}`} className="flex items-center gap-1 text-blue-600 hover:underline">
                                <Phone className="h-3 w-3" />
                                {booking.customerProfile.user.phone}
                              </a>
                            )}
                          </div>
                        </div>
                      </div>

                      {/* Dates & Status */}
                      <div className="flex flex-wrap items-center gap-4">
                        <div className="text-sm">
                          <div className="flex items-center gap-1.5 text-slate-600">
                            <MapPin className="h-3 w-3" />
                            <span>{booking.pickupBranch.name} → {booking.dropoffBranch.name}</span>
                          </div>
                          <div className="mt-1 flex items-center gap-1.5 text-slate-600">
                            <Calendar className="h-3 w-3" />
                            <span>{new Date(booking.pickupAt).toLocaleDateString()} → {new Date(booking.dropoffAt).toLocaleDateString()}</span>
                          </div>
                        </div>

                        <div className="text-center">
                          <p className={`text-lg font-bold ${isOverdue ? "text-red-600" : isDueToday ? "text-orange-600" : "text-green-600"}`}>
                            {isOverdue ? `${Math.abs(daysLeft)}d overdue` : isDueToday ? "Due Today" : `${daysLeft}d left`}
                          </p>
                          <p className="text-xs text-slate-400">remaining</p>
                        </div>

                        <div className="text-right">
                          <p className="font-semibold text-slate-900">
                            {tenant.currency} {Number(booking.totalAmount).toFixed(0)}
                          </p>
                          <Badge className={
                            paymentStatus === "PAID" ? "bg-green-100 text-green-700" :
                            paymentStatus === "PARTIAL" ? "bg-yellow-100 text-yellow-700" :
                            "bg-red-100 text-red-700"
                          }>
                            {paymentStatus}
                          </Badge>
                        </div>
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-slate-100 pt-3">
                      <Link href={`/company/${tenantSlug}/bookings/${booking.id}`}>
                        <Button size="sm" variant="outline">View Booking</Button>
                      </Link>
                      {booking.contract ? (
                        <Link href={`/company/${tenantSlug}/contracts/${booking.contract.id}`}>
                          <Button size="sm" variant="outline" className="border-blue-200 text-blue-600">
                            <FileSignature className="mr-1 h-3 w-3" />
                            Contract {booking.contract.contractNumber}
                          </Button>
                        </Link>
                      ) : (
                        <Link href={`/company/${tenantSlug}/contracts/new`}>
                          <Button size="sm" variant="outline" className="border-green-200 text-green-600">
                            <FileSignature className="mr-1 h-3 w-3" />
                            Create Contract
                          </Button>
                        </Link>
                      )}
                      {booking.customerProfile.user.phone && (
                        <a href={`tel:${booking.customerProfile.user.phone}`}>
                          <Button size="sm" variant="outline">
                            <Phone className="mr-1 h-3 w-3" />
                            Call Customer
                          </Button>
                        </a>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
