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 {Button} from "@/components/ui/button";
import {Badge} from "@/components/ui/badge";
import {CalendarDays, ArrowLeft, Car, CheckCircle} from "lucide-react";

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

function getDaysInMonth(year: number, month: number) {
  return new Date(year, month + 1, 0).getDate();
}

export default async function MonitoringCalendarPage({params}: CalendarPageProps) {
  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();
  const year = now.getFullYear();
  const month = now.getMonth();

  const startOfMonth = new Date(year, month, 1);
  const endOfMonth = new Date(year, month + 1, 0, 23, 59, 59);

  // Get all bookings that overlap with this month
  const bookings = await db.booking.findMany({
    where: {
      status: {in: ["CONFIRMED", "ACTIVE", "COMPLETED"]},
      AND: [
        {pickupAt: {lte: endOfMonth}},
        {dropoffAt: {gte: startOfMonth}}
      ]
    },
    include: {
      vehicle: {include: {brand: true}},
      customerProfile: {include: {user: {select: {firstName: true, lastName: true}}}}
    },
    orderBy: {pickupAt: "asc"}
  });

  const daysInMonth = getDaysInMonth(year, month);
  const firstDayOfWeek = new Date(year, month, 1).getDay();
  const monthName = new Date(year, month, 1).toLocaleString("default", {month: "long", year: "numeric"});

  const pickupsByDay: Record<number, typeof bookings> = {};
  const dropoffsByDay: Record<number, typeof bookings> = {};

  for (const booking of bookings) {
    const pickupDay = new Date(booking.pickupAt);
    if (pickupDay.getMonth() === month && pickupDay.getFullYear() === year) {
      const d = pickupDay.getDate();
      if (!pickupsByDay[d]) pickupsByDay[d] = [];
      pickupsByDay[d].push(booking);
    }
    const dropoffDay = new Date(booking.dropoffAt);
    if (dropoffDay.getMonth() === month && dropoffDay.getFullYear() === year) {
      const d = dropoffDay.getDate();
      if (!dropoffsByDay[d]) dropoffsByDay[d] = [];
      dropoffsByDay[d].push(booking);
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <Link href={`/company/${tenantSlug}/monitoring`} className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700">
            <ArrowLeft className="h-4 w-4" />
            Back to Monitoring
          </Link>
          <h1 className="text-2xl font-bold text-slate-900">Booking Calendar</h1>
          <p className="mt-1 text-slate-500">{monthName} — Pickups & Returns</p>
        </div>
      </div>

      {/* Legend */}
      <div className="flex flex-wrap gap-4 text-sm">
        <div className="flex items-center gap-2">
          <div className="h-3 w-3 rounded-full bg-blue-500" />
          <span className="text-slate-600">Pickup</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="h-3 w-3 rounded-full bg-green-500" />
          <span className="text-slate-600">Return</span>
        </div>
      </div>

      {/* Calendar Grid */}
      <Card>
        <CardContent className="p-4">
          {/* Day headers */}
          <div className="grid grid-cols-7 gap-1 mb-2">
            {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((d) => (
              <div key={d} className="py-2 text-center text-xs font-semibold text-slate-500">{d}</div>
            ))}
          </div>
          {/* Days */}
          <div className="grid grid-cols-7 gap-1">
            {Array.from({length: firstDayOfWeek}).map((_, i) => (
              <div key={`empty-${i}`} />
            ))}
            {Array.from({length: daysInMonth}, (_, i) => i + 1).map((day) => {
              const pickups = pickupsByDay[day] ?? [];
              const dropoffs = dropoffsByDay[day] ?? [];
              const isToday = day === now.getDate() && month === now.getMonth() && year === now.getFullYear();

              return (
                <div
                  key={day}
                  className={`min-h-20 rounded-lg border p-1.5 text-xs ${
                    isToday ? "border-blue-300 bg-blue-50" : "border-slate-100 hover:border-slate-200"
                  }`}
                >
                  <p className={`mb-1 font-semibold ${isToday ? "text-blue-600" : "text-slate-700"}`}>{day}</p>
                  {pickups.slice(0, 2).map((b) => (
                    <div key={`p-${b.id}`} className="mb-0.5 truncate rounded bg-blue-100 px-1 py-0.5 text-blue-700">
                      <Car className="inline h-2.5 w-2.5 mr-0.5" />
                      {b.vehicle.name.split(" ")[0]}
                    </div>
                  ))}
                  {pickups.length > 2 && <div className="text-blue-500">+{pickups.length - 2} more</div>}
                  {dropoffs.slice(0, 2).map((b) => (
                    <div key={`d-${b.id}`} className="mb-0.5 truncate rounded bg-green-100 px-1 py-0.5 text-green-700">
                      <CheckCircle className="inline h-2.5 w-2.5 mr-0.5" />
                      {b.vehicle.name.split(" ")[0]}
                    </div>
                  ))}
                  {dropoffs.length > 2 && <div className="text-green-500">+{dropoffs.length - 2} more</div>}
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Upcoming returns this week */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <CalendarDays className="h-5 w-5 text-blue-600" />
            Upcoming This Week
          </CardTitle>
        </CardHeader>
        <CardContent>
          {bookings.filter((b) => {
            const d = new Date(b.dropoffAt);
            const weekLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
            return d >= now && d <= weekLater;
          }).length === 0 ? (
            <p className="text-center text-slate-400 py-4">No returns scheduled this week</p>
          ) : (
            <div className="space-y-2">
              {bookings
                .filter((b) => {
                  const d = new Date(b.dropoffAt);
                  const weekLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
                  return d >= now && d <= weekLater;
                })
                .map((b) => {
                  const customerName = [b.customerProfile.user.firstName, b.customerProfile.user.lastName].filter(Boolean).join(" ");
                  return (
                    <div key={b.id} className="flex items-center justify-between rounded-lg border border-slate-100 bg-slate-50 p-3">
                      <div className="flex items-center gap-3">
                        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-green-100">
                          <CheckCircle className="h-4 w-4 text-green-600" />
                        </div>
                        <div>
                          <p className="text-sm font-medium text-slate-900">{b.vehicle.name}</p>
                          <p className="text-xs text-slate-500">{customerName}</p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-semibold text-slate-900">
                          {new Date(b.dropoffAt).toLocaleDateString()}
                        </p>
                        <Badge className="bg-green-100 text-green-700 text-xs">Return</Badge>
                      </div>
                    </div>
                  );
                })}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
