import {notFound, redirect} from "next/navigation";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";

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

function BarChart({
  data,
  label,
  color = "bg-blue-500"
}: {
  data: {label: string; value: number}[];
  label: string;
  color?: string;
}) {
  const max = Math.max(...data.map((d) => d.value), 1);
  return (
    <div>
      <p className="mb-3 text-sm font-semibold text-slate-700">{label}</p>
      <div className="space-y-2">
        {data.map((item, i) => (
          <div key={i} className="flex items-center gap-3">
            <span className="w-20 shrink-0 truncate text-right text-xs text-slate-500">{item.label}</span>
            <div className="flex-1 rounded-full bg-slate-100 h-4 overflow-hidden">
              <div
                className={`h-full rounded-full ${color} transition-all`}
                style={{width: `${(item.value / max) * 100}%`}}
              />
            </div>
            <span className="w-16 shrink-0 text-right text-xs font-semibold text-slate-700">
              {item.value.toFixed(0)}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function StatCard({title, value, sub, color = "text-slate-900"}: {title: string; value: string; sub?: string; color?: string}) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
      <p className="text-xs font-medium uppercase tracking-wide text-slate-500">{title}</p>
      <p className={`mt-2 text-2xl font-bold ${color}`}>{value}</p>
      {sub && <p className="mt-1 text-xs text-slate-400">{sub}</p>}
    </div>
  );
}

export default async function ReportsPage({params}: ReportsPageProps) {
  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 now = new Date();
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const startOfYear = new Date(now.getFullYear(), 0, 1);

  // Fetch all needed data in parallel
  const [bookings, vehicles, payments, customers] = await Promise.all([
    db.booking.findMany({
      include: {vehicle: {include: {brand: true}}},
      orderBy: {createdAt: "desc"}
    }),
    db.vehicle.findMany({where: {deletedAt: null}}),
    db.paymentTransaction.findMany({where: {status: "PAID"}}),
    db.customerProfile.findMany()
  ]);

  // Revenue stats
  const totalRevenue = payments.reduce((sum, p) => sum + Number(p.amount), 0);
  const monthRevenue = payments
    .filter((p) => p.paidAt && p.paidAt >= startOfMonth)
    .reduce((sum, p) => sum + Number(p.amount), 0);

  const confirmedBookings = bookings.filter((b) => !["CANCELLED", "REJECTED", "DRAFT"].includes(b.status));
  const completedBookings = bookings.filter((b) => b.status === "COMPLETED");
  const activeBookings = bookings.filter((b) => b.status === "ACTIVE");

  // Fleet occupancy
  const rentedCount = vehicles.filter((v) => ["RENTED", "RESERVED"].includes(v.status)).length;
  const occupancyRate = vehicles.length > 0 ? Math.round((rentedCount / vehicles.length) * 100) : 0;

  // Revenue by month (last 6 months)
  const revenueByMonth: {label: string; value: number}[] = [];
  for (let i = 5; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const end = new Date(now.getFullYear(), now.getMonth() - i + 1, 1);
    const monthLabel = d.toLocaleDateString("en", {month: "short", year: "2-digit"});
    const rev = payments
      .filter((p) => p.paidAt && p.paidAt >= d && p.paidAt < end)
      .reduce((s, p) => s + Number(p.amount), 0);
    revenueByMonth.push({label: monthLabel, value: rev});
  }

  // Top 5 booked vehicles
  const vehicleBookingCount: Record<string, {name: string; count: number}> = {};
  for (const b of confirmedBookings) {
    const key = b.vehicleId;
    if (!vehicleBookingCount[key]) {
      vehicleBookingCount[key] = {
        name: `${b.vehicle.brand.name} ${b.vehicle.name}`,
        count: 0
      };
    }
    vehicleBookingCount[key].count++;
  }
  const topVehicles = Object.values(vehicleBookingCount)
    .sort((a, b) => b.count - a.count)
    .slice(0, 5)
    .map((v) => ({label: v.name, value: v.count}));

  // Bookings by status distribution
  const statusDistribution = [
    "CONFIRMED",
    "ACTIVE",
    "COMPLETED",
    "PENDING_APPROVAL",
    "CANCELLED"
  ].map((s) => ({
    label: s.replace(/_/g, " "),
    value: bookings.filter((b) => b.status === s).length
  }));

  // Vehicle status distribution
  const vehicleStatusDist = ["AVAILABLE", "RENTED", "RESERVED", "MAINTENANCE"].map((s) => ({
    label: s,
    value: vehicles.filter((v) => v.status === s).length
  }));

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Reports & Analytics</h1>
        <p className="mt-1 text-slate-500">Overview of your business performance</p>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <StatCard
          title="Total Revenue"
          value={`${tenant.currency} ${totalRevenue.toFixed(0)}`}
          sub="All time"
          color="text-green-700"
        />
        <StatCard
          title="This Month"
          value={`${tenant.currency} ${monthRevenue.toFixed(0)}`}
          color="text-blue-700"
        />
        <StatCard
          title="Fleet Size"
          value={String(vehicles.length)}
          sub={`${occupancyRate}% occupied`}
        />
        <StatCard
          title="Customers"
          value={String(customers.length)}
          sub={`${completedBookings.length} completed`}
        />
      </div>

      {/* Revenue chart */}
      <div className="grid gap-6 lg:grid-cols-2">
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
          <h2 className="mb-5 font-semibold text-slate-900">Revenue — Last 6 Months</h2>
          <BarChart data={revenueByMonth} label={`Amount (${tenant.currency})`} color="bg-blue-500" />
        </div>

        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
          <h2 className="mb-5 font-semibold text-slate-900">Booking Status Distribution</h2>
          <BarChart data={statusDistribution} label="Bookings" color="bg-violet-500" />
        </div>
      </div>

      {/* Top vehicles + Fleet occupancy */}
      <div className="grid gap-6 lg:grid-cols-2">
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
          <h2 className="mb-5 font-semibold text-slate-900">Top 5 Most Booked Vehicles</h2>
          {topVehicles.length > 0 ? (
            <BarChart data={topVehicles} label="Confirmed Bookings" color="bg-amber-500" />
          ) : (
            <p className="text-sm text-slate-400">No booking data yet.</p>
          )}
        </div>

        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
          <h2 className="mb-5 font-semibold text-slate-900">Fleet Occupancy</h2>

          {/* Progress ring (CSS-based) */}
          <div className="flex items-center gap-6">
            <div className="relative flex h-28 w-28 shrink-0 items-center justify-center">
              <svg className="h-28 w-28 -rotate-90" viewBox="0 0 100 100">
                <circle
                  cx="50"
                  cy="50"
                  r="40"
                  stroke="#e2e8f0"
                  strokeWidth="12"
                  fill="none"
                />
                <circle
                  cx="50"
                  cy="50"
                  r="40"
                  stroke="#3b82f6"
                  strokeWidth="12"
                  fill="none"
                  strokeDasharray={`${2 * Math.PI * 40}`}
                  strokeDashoffset={`${2 * Math.PI * 40 * (1 - occupancyRate / 100)}`}
                  strokeLinecap="round"
                />
              </svg>
              <span className="absolute text-xl font-bold text-slate-900">{occupancyRate}%</span>
            </div>
            <div className="space-y-2">
              <BarChart data={vehicleStatusDist} label="Vehicles by Status" color="bg-emerald-500" />
            </div>
          </div>
        </div>
      </div>

      {/* Customer summary */}
      <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="mb-4 font-semibold text-slate-900">Customer Summary</h2>
        <div className="grid grid-cols-3 gap-6 text-center">
          <div>
            <p className="text-3xl font-bold text-slate-900">{customers.length}</p>
            <p className="mt-1 text-xs text-slate-500 uppercase">Total Customers</p>
          </div>
          <div>
            <p className="text-3xl font-bold text-blue-700">{confirmedBookings.length}</p>
            <p className="mt-1 text-xs text-slate-500 uppercase">Confirmed Bookings</p>
          </div>
          <div>
            <p className="text-3xl font-bold text-green-700">{activeBookings.length}</p>
            <p className="mt-1 text-xs text-slate-500 uppercase">Active Rentals</p>
          </div>
        </div>
      </div>
    </div>
  );
}
