import Link from "next/link";
import {notFound} from "next/navigation";
import {auth} from "@/auth";
import {redirect} 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 {Calendar, Car, DollarSign, Users, TrendingUp, ArrowRight, AlertTriangle, FileSignature, Clock, Monitor} from "lucide-react";

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

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

export default async function CompanyDashboardPage({params}: CompanyDashboardPageProps) {
  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 today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1);
  const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

  const [
    todayBookings,
    availableVehicles,
    rentedVehicles,
    maintenanceVehicles,
    totalCustomers,
    monthlyBookings,
    recentBookings,
    activeContracts,
    overdueContracts,
    todayReturns,
    pendingBookings
  ] = await Promise.all([
    db.booking.count({where: {createdAt: {gte: today, lt: tomorrow}}}),
    db.vehicle.count({where: {status: "AVAILABLE", isPublic: true}}),
    db.vehicle.count({where: {status: "RENTED"}}),
    db.vehicle.count({where: {status: "MAINTENANCE"}}),
    db.customerProfile.count({}),
    db.booking.findMany({
      where: {createdAt: {gte: startOfMonth}, status: {in: ["CONFIRMED", "ACTIVE", "COMPLETED"]}},
      select: {totalAmount: true}
    }),
    db.booking.findMany({
      orderBy: {createdAt: "desc"},
      take: 5,
      include: {
        vehicle: {include: {brand: true}},
        customerProfile: {include: {user: {select: {firstName: true, lastName: true, email: true}}}}
      }
    }),
    db.rentalContract.count({where: {status: "ACTIVE"}}),
    db.rentalContract.count({where: {status: "OVERDUE"}}),
    db.booking.count({
      where: {
        status: {in: ["CONFIRMED", "ACTIVE"]},
        dropoffAt: {gte: today, lt: tomorrow}
      }
    }),
    db.booking.count({where: {status: "PENDING_APPROVAL"}})
  ]);

  const monthlyRevenue = monthlyBookings.reduce((sum, b) => sum + Number(b.totalAmount), 0);

  const stats = [
    {icon: Calendar, label: "Today's Bookings", value: todayBookings, iconBg: "bg-indigo-50", iconColor: "text-indigo-600", href: "./bookings"},
    {icon: Car, label: "Available Vehicles", value: availableVehicles, iconBg: "bg-emerald-50", iconColor: "text-emerald-600", href: "./fleet"},
    {icon: Car, label: "Rented Now", value: rentedVehicles, iconBg: "bg-purple-50", iconColor: "text-purple-600", href: "./monitoring"},
    {icon: DollarSign, label: "Monthly Revenue", value: `${tenant.currency} ${monthlyRevenue.toFixed(0)}`, iconBg: "bg-indigo-50", iconColor: "text-indigo-600", href: "./bookings"},
    {icon: Users, label: "Total Customers", value: totalCustomers, iconBg: "bg-orange-50", iconColor: "text-orange-600", href: "./customers"},
    {icon: FileSignature, label: "Active Contracts", value: activeContracts, iconBg: "bg-teal-50", iconColor: "text-teal-600", href: "./contracts"}
  ];

  const alerts = [
    ...(overdueContracts > 0 ? [{type: "error" as const, icon: AlertTriangle, message: `${overdueContracts} overdue contract${overdueContracts > 1 ? "s" : ""} — immediate action required`, href: "./contracts?status=OVERDUE"}] : []),
    ...(todayReturns > 0 ? [{type: "warning" as const, icon: Clock, message: `${todayReturns} vehicle${todayReturns > 1 ? "s" : ""} due for return today`, href: "./monitoring"}] : []),
    ...(pendingBookings > 0 ? [{type: "info" as const, icon: Calendar, message: `${pendingBookings} booking${pendingBookings > 1 ? "s" : ""} awaiting approval`, href: "./bookings?status=PENDING_APPROVAL"}] : []),
    ...(maintenanceVehicles > 0 ? [{type: "warning" as const, icon: Car, message: `${maintenanceVehicles} vehicle${maintenanceVehicles > 1 ? "s" : ""} currently in maintenance`, href: "./fleet"}] : [])
  ];

  const alertColors = {
    error: "border-red-200 bg-red-50 text-red-700",
    warning: "border-amber-200 bg-amber-50 text-amber-700",
    info: "border-indigo-200 bg-indigo-50 text-indigo-700"
  };

  return (
    <div className="space-y-7">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
        <p className="mt-1 text-gray-500">{tenant.name} — Overview</p>
      </div>

      {/* Alerts */}
      {alerts.length > 0 && (
        <div className="space-y-2">
          {alerts.map(({type, icon: Icon, message, href}, i) => (
            <Link key={i} href={href}>
              <div className={`flex items-center gap-3 rounded-xl border px-4 py-3 transition-opacity hover:opacity-90 ${alertColors[type]}`}>
                <Icon className="h-4 w-4 shrink-0" />
                <span className="text-sm font-medium">{message}</span>
                <ArrowRight className="ms-auto h-4 w-4" />
              </div>
            </Link>
          ))}
        </div>
      )}

      {/* Stats Cards */}
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
        {stats.map(({icon: Icon, label, value, iconBg, iconColor, href}) => (
          <Link key={label} href={href}>
            <Card className="rounded-xl border-gray-100 shadow-sm transition-all duration-200 hover:shadow-md hover:-translate-y-0.5">
              <CardContent className="flex items-center gap-4 p-5">
                <div className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-xl ${iconBg}`}>
                  <Icon className={`h-5 w-5 ${iconColor}`} />
                </div>
                <div>
                  <p className="text-2xl font-bold text-gray-900">{value}</p>
                  <p className="text-sm text-gray-500 mt-0.5">{label}</p>
                </div>
              </CardContent>
            </Card>
          </Link>
        ))}
      </div>

      {/* Quick Actions */}
      <div className="grid gap-3 sm:grid-cols-3">
        <Link href={`./monitoring`}>
          <Card className="rounded-xl border-indigo-100 bg-indigo-50 transition-all duration-200 hover:shadow-md cursor-pointer">
            <CardContent className="flex items-center gap-3 p-4">
              <Monitor className="h-5 w-5 text-indigo-600 shrink-0" />
              <div>
                <p className="font-semibold text-indigo-900 text-sm">Live Monitoring</p>
                <p className="text-xs text-indigo-600 mt-0.5">View all active rentals</p>
              </div>
            </CardContent>
          </Card>
        </Link>
        <Link href={`./contracts/new`}>
          <Card className="rounded-xl border-teal-100 bg-teal-50 transition-all duration-200 hover:shadow-md cursor-pointer">
            <CardContent className="flex items-center gap-3 p-4">
              <FileSignature className="h-5 w-5 text-teal-600 shrink-0" />
              <div>
                <p className="font-semibold text-teal-900 text-sm">New Contract</p>
                <p className="text-xs text-teal-600 mt-0.5">Create a rental contract</p>
              </div>
            </CardContent>
          </Card>
        </Link>
        <Link href={`./monitoring/calendar`}>
          <Card className="rounded-xl border-purple-100 bg-purple-50 transition-all duration-200 hover:shadow-md cursor-pointer">
            <CardContent className="flex items-center gap-3 p-4">
              <Calendar className="h-5 w-5 text-purple-600 shrink-0" />
              <div>
                <p className="font-semibold text-purple-900 text-sm">Calendar</p>
                <p className="text-xs text-purple-600 mt-0.5">Pickups & returns</p>
              </div>
            </CardContent>
          </Card>
        </Link>
      </div>

      {/* Revenue Bar Chart (CSS-based) */}
      <Card className="rounded-xl border-gray-100 shadow-sm">
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="flex items-center gap-2 text-base font-semibold text-gray-900">
            <TrendingUp className="h-4 w-4 text-indigo-600" />
            Monthly Revenue Overview
          </CardTitle>
        </CardHeader>
        <CardContent className="pt-0">
          <div className="flex items-end gap-2 h-36 pt-4">
            {Array.from({length: 7}, (_, i) => {
              const height = [40, 55, 35, 70, 60, 85, 50][i];
              const months = ["Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
              return (
                <div key={i} className="flex flex-1 flex-col items-center gap-1">
                  <div
                    className="w-full rounded-t-md bg-indigo-500 transition-all hover:bg-indigo-600"
                    style={{height: `${height}%`}}
                  />
                  <span className="text-xs text-gray-400">{months[i]}</span>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Recent Bookings */}
      <Card className="rounded-xl border-gray-100 shadow-sm">
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-base font-semibold text-gray-900">Recent Bookings</CardTitle>
          <Link href="./bookings">
            <Button variant="ghost" size="sm" className="gap-1 text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50 rounded-lg text-xs">
              View All <ArrowRight className="h-3 w-3" />
            </Button>
          </Link>
        </CardHeader>
        <CardContent className="pt-0">
          {recentBookings.length === 0 ? (
            <p className="py-8 text-center text-gray-400">No bookings yet</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-100">
                    <th className="py-3 pe-4 text-start text-xs font-semibold text-gray-500 uppercase tracking-wide">Booking #</th>
                    <th className="py-3 pe-4 text-start text-xs font-semibold text-gray-500 uppercase tracking-wide">Customer</th>
                    <th className="py-3 pe-4 text-start text-xs font-semibold text-gray-500 uppercase tracking-wide">Vehicle</th>
                    <th className="py-3 pe-4 text-start text-xs font-semibold text-gray-500 uppercase tracking-wide">Status</th>
                    <th className="py-3 text-end text-xs font-semibold text-gray-500 uppercase tracking-wide">Total</th>
                  </tr>
                </thead>
                <tbody>
                  {recentBookings.map((booking) => (
                    <tr key={booking.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                      <td className="py-3.5 pe-4">
                        <Link href={`./bookings/${booking.id}`} className="font-mono text-xs text-indigo-600 hover:text-indigo-700 hover:underline">
                          {booking.bookingNumber}
                        </Link>
                      </td>
                      <td className="py-3.5 pe-4 text-gray-700 text-sm">
                        {booking.customerProfile.user.firstName
                          ? `${booking.customerProfile.user.firstName} ${booking.customerProfile.user.lastName ?? ""}`
                          : booking.customerProfile.user.email}
                      </td>
                      <td className="py-3.5 pe-4 text-gray-700 text-sm">
                        {booking.vehicle.brand.name} {booking.vehicle.name}
                      </td>
                      <td className="py-3.5 pe-4">
                        <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${statusColors[booking.status] ?? "bg-gray-100 text-gray-600"}`}>
                          {booking.status.replace(/_/g, " ")}
                        </span>
                      </td>
                      <td className="py-3.5 text-end font-semibold text-gray-900 text-sm">
                        {tenant.currency} {Number(booking.totalAmount).toFixed(0)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
