import {redirect} from "next/navigation";
import Link from "next/link";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {Card, CardContent} from "@/components/ui/card";
import {Button} from "@/components/ui/button";
import {Calendar, Car, Heart, Clock} from "lucide-react";

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

export default async function AccountPage({params}: AccountPageProps) {
  const {locale} = await params;
  const session = await auth();

  if (!session?.user?.id) {
    redirect(`/${locale}/auth/sign-in`);
  }

  const [totalBookings, activeBookings, favoritesCount] = await Promise.all([
    prisma.booking.count({where: {customerUserId: session.user.id}}),
    prisma.booking.count({where: {customerUserId: session.user.id, status: {in: ["CONFIRMED", "ACTIVE", "PENDING_APPROVAL"]}}}),
    prisma.favoriteVehicle.count({where: {userId: session.user.id}})
  ]);

  const recentBookings = await prisma.booking.findMany({
    where: {customerUserId: session.user.id},
    include: {vehicle: {include: {brand: true}}, tenant: true},
    orderBy: {createdAt: "desc"},
    take: 3
  });

  const user = await prisma.user.findUnique({
    where: {id: session.user.id},
    select: {firstName: true, lastName: true, createdAt: true}
  });

  const stats = [
    {icon: Calendar, label: "Active Bookings", value: activeBookings, color: "text-blue-600 bg-blue-50"},
    {icon: Car, label: "Total Bookings", value: totalBookings, color: "text-green-600 bg-green-50"},
    {icon: Heart, label: "Saved Cars", value: favoritesCount, color: "text-red-600 bg-red-50"},
    {icon: Clock, label: "Member Since", value: user?.createdAt ? new Date(user.createdAt).getFullYear().toString() : "—", color: "text-purple-600 bg-purple-50"}
  ];

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

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-slate-900">Welcome back, {user?.firstName ?? "there"}!</h1>
        <p className="mt-1 text-slate-500">Here's an overview of your account</p>
      </div>

      {/* Stats */}
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4 mb-8">
        {stats.map(({icon: Icon, label, value, color}) => (
          <Card key={label} className="border-slate-200">
            <CardContent className="flex items-center gap-4 p-4">
              <div className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-xl ${color}`}>
                <Icon className="h-6 w-6" />
              </div>
              <div>
                <p className="text-2xl font-bold text-slate-900">{value}</p>
                <p className="text-xs text-slate-500">{label}</p>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Recent Bookings */}
      <div>
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-slate-900">Recent Bookings</h2>
          <Link href="/account/bookings">
            <Button variant="ghost" size="sm">View all</Button>
          </Link>
        </div>
        {recentBookings.length === 0 ? (
          <Card className="border-dashed border-slate-300">
            <CardContent className="py-12 text-center">
              <Car className="mx-auto h-10 w-10 text-slate-300" />
              <p className="mt-3 text-slate-500">No bookings yet</p>
              <Link href="/cars" className="mt-3 inline-block">
                <Button size="sm">Browse Cars</Button>
              </Link>
            </CardContent>
          </Card>
        ) : (
          <div className="space-y-3">
            {recentBookings.map((b) => (
              <Link key={b.id} href={`/bookings/${b.bookingNumber}`}>
                <Card className="border-slate-200 transition hover:border-blue-200 hover:shadow-sm">
                  <CardContent className="flex items-center justify-between gap-4 p-4">
                    <div>
                      <p className="font-semibold text-slate-900">{b.vehicle.brand.name} {b.vehicle.name}</p>
                      <p className="text-sm text-slate-500">{b.tenant.name} · {new Date(b.pickupAt).toLocaleDateString()}</p>
                      <p className="mt-0.5 font-mono text-xs text-slate-400">{b.bookingNumber}</p>
                    </div>
                    <span className={`shrink-0 rounded-full px-2.5 py-1 text-xs font-medium ${statusColors[b.status] ?? "bg-slate-100 text-slate-600"}`}>
                      {b.status.replace(/_/g, " ")}
                    </span>
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
