import Link from "next/link";
import Image from "next/image";
import {getTranslations} from "next-intl/server";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {Button} from "@/components/ui/button";
import {Card, CardContent} from "@/components/ui/card";
import {Badge} from "@/components/ui/badge";
import {
  Car,
  MapPin,
  Shield,
  Star,
  ChevronRight,
  Search,
  Calendar,
  LayoutDashboard,
  LogIn,
  Building2,
  Zap,
  CheckCircle2
} from "lucide-react";

async function getFeaturedVehicles() {
  return prisma.vehicle.findMany({
    where: {featured: true, isPublic: true, status: "AVAILABLE"},
    include: {brand: true, model: true, tenant: true},
    take: 6,
    orderBy: {createdAt: "desc"}
  });
}

async function getFeaturedCompanies() {
  return prisma.tenant.findMany({
    where: {status: "ACTIVE", isPublicListingEnabled: true},
    include: {_count: {select: {vehicles: true, branches: true}}},
    take: 6,
    orderBy: {createdAt: "desc"}
  });
}

export default async function HomePage() {
  const t = await getTranslations("home");
  const session = await auth();
  const [vehicles, companies] = await Promise.all([getFeaturedVehicles(), getFeaturedCompanies()]);

  // Resolve dashboard link for logged-in users
  let dashboardHref: string | null = null;
  let dashboardLabel = "Dashboard";
  if (session?.user) {
    if (session.user.platformRole === "SUPER_ADMIN") {
      dashboardHref = "/super-admin";
      dashboardLabel = "Super Admin Panel";
    } else if (session.user.memberships && session.user.memberships.length > 0) {
      const slug = session.user.memberships[0].tenantSlug;
      dashboardHref = `/company/${slug}`;
      dashboardLabel = "Company Dashboard";
    }
  }

  return (
    <div className="flex flex-col">
      {/* Admin Banner */}
      {session?.user && dashboardHref && (
        <div className="bg-indigo-600 px-6 py-2.5 text-white">
          <div className="mx-auto flex max-w-7xl items-center justify-between">
            <div className="flex items-center gap-2 text-sm">
              <LayoutDashboard className="h-4 w-4 shrink-0" />
              <span>مرحباً {session.user.name ?? session.user.email} — لديك صلاحية الوصول للوحة التحكم</span>
            </div>
            <Link href={dashboardHref}>
              <Button size="sm" className="bg-white text-indigo-600 hover:bg-indigo-50 shadow-none rounded-lg font-semibold">
                <LayoutDashboard className="me-1.5 h-3.5 w-3.5" />
                {dashboardLabel}
              </Button>
            </Link>
          </div>
        </div>
      )}

      {/* Sign-in Banner for guests */}
      {!session?.user && (
        <div className="bg-gray-900 px-6 py-2.5 text-white">
          <div className="mx-auto flex max-w-7xl items-center justify-between">
            <div className="flex items-center gap-4 text-sm text-gray-400">
              <span>هل أنت مدير شركة أو مشرف؟</span>
              <Link href="/super-admin" className="text-indigo-400 hover:text-indigo-300 transition-colors">
                Super Admin →
              </Link>
            </div>
            <div className="flex items-center gap-2">
              <Link href="/auth/sign-in">
                <Button size="sm" variant="outline" className="border-gray-700 bg-transparent text-white hover:bg-gray-800 hover:border-gray-600 shadow-none rounded-lg">
                  <LogIn className="me-1.5 h-3.5 w-3.5" />
                  تسجيل الدخول
                </Button>
              </Link>
              <Link href="/auth/sign-up">
                <Button size="sm" className="bg-indigo-600 hover:bg-indigo-700 shadow-none rounded-lg">
                  إنشاء حساب
                </Button>
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* Hero Section */}
      <section className="relative overflow-hidden bg-gradient-to-br from-indigo-600 via-indigo-700 to-purple-700 px-6 py-24 text-white">
        {/* Background decoration */}
        <div className="pointer-events-none absolute inset-0 overflow-hidden">
          <div className="absolute -top-40 -right-40 h-[600px] w-[600px] rounded-full bg-white/5 blur-3xl" />
          <div className="absolute -bottom-40 -left-20 h-[400px] w-[400px] rounded-full bg-purple-400/10 blur-3xl" />
          <div
            className="absolute inset-0 opacity-[0.03]"
            style={{backgroundImage: "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' width='32' height='32' fill='none' stroke='rgb(255 255 255 / 1)'%3e%3cpath d='M0 .5H31.5V32'/%3e%3c/svg%3e\")"}}
          />
        </div>

        <div className="relative mx-auto max-w-5xl text-center">
          <Badge className="mb-5 border-white/20 bg-white/10 text-white hover:bg-white/15">
            <Zap className="me-1.5 h-3 w-3" />
            Car Rental Platform
          </Badge>
          <h1 className="text-4xl font-bold tracking-tight sm:text-5xl md:text-6xl leading-tight">
            {t("hero.title")}
          </h1>
          <p className="mx-auto mt-5 max-w-2xl text-lg text-indigo-100 leading-relaxed">
            {t("hero.subtitle")}
          </p>

          {/* Search Box — white card */}
          <div className="mx-auto mt-10 max-w-2xl rounded-xl bg-white p-6 shadow-2xl shadow-indigo-900/30">
            <div className="grid gap-3 sm:grid-cols-2">
              <div className="flex items-center gap-3 rounded-xl border border-gray-100 bg-gray-50 px-4 py-3 cursor-pointer hover:border-indigo-200 hover:bg-indigo-50 transition-colors">
                <Calendar className="h-5 w-5 text-indigo-500 shrink-0" />
                <div className="text-start">
                  <p className="text-xs text-gray-400 font-medium">{t("search.pickupDate")}</p>
                  <p className="text-sm font-semibold text-gray-700">Select date</p>
                </div>
              </div>
              <div className="flex items-center gap-3 rounded-xl border border-gray-100 bg-gray-50 px-4 py-3 cursor-pointer hover:border-indigo-200 hover:bg-indigo-50 transition-colors">
                <Calendar className="h-5 w-5 text-indigo-500 shrink-0" />
                <div className="text-start">
                  <p className="text-xs text-gray-400 font-medium">{t("search.returnDate")}</p>
                  <p className="text-sm font-semibold text-gray-700">Select date</p>
                </div>
              </div>
            </div>
            <Link className="mt-4 block" href="/cars">
              <Button className="w-full bg-indigo-600 hover:bg-indigo-700 py-3 text-base font-semibold rounded-lg shadow-sm shadow-indigo-200" size="lg">
                <Search className="me-2 h-5 w-5" />
                {t("search.searchBtn")}
              </Button>
            </Link>
          </div>

          {/* Quick Access */}
          <div className="mt-8 flex flex-wrap justify-center gap-3 text-sm">
            <Link href="/auth/sign-in">
              <Button variant="outline" className="border-white/25 bg-white/10 text-white hover:bg-white/15 hover:border-white/35 shadow-none rounded-lg backdrop-blur-sm">
                <LogIn className="me-2 h-4 w-4" />
                تسجيل الدخول
              </Button>
            </Link>
            <Link href="/super-admin">
              <Button variant="outline" className="border-white/25 bg-white/10 text-white hover:bg-white/15 hover:border-white/35 shadow-none rounded-lg backdrop-blur-sm">
                <Shield className="me-2 h-4 w-4" />
                Super Admin
              </Button>
            </Link>
            {companies[0] && (
              <Link href={`/company/${companies[0].slug}`}>
                <Button variant="outline" className="border-white/25 bg-white/10 text-white hover:bg-white/15 hover:border-white/35 shadow-none rounded-lg backdrop-blur-sm">
                  <Building2 className="me-2 h-4 w-4" />
                  Company Dashboard
                </Button>
              </Link>
            )}
          </div>

          {/* Trust Badges */}
          <div className="mt-8 flex flex-wrap justify-center gap-6 text-sm text-indigo-100">
            <div className="flex items-center gap-2">
              <CheckCircle2 className="h-4 w-4 text-emerald-300" />
              <span>Verified Companies</span>
            </div>
            <div className="flex items-center gap-2">
              <Star className="h-4 w-4 text-amber-300" />
              <span>Top-Rated Service</span>
            </div>
            <div className="flex items-center gap-2">
              <Car className="h-4 w-4 text-indigo-200" />
              <span>Wide Selection</span>
            </div>
          </div>
        </div>
      </section>

      {/* Featured Cars */}
      {vehicles.length > 0 && (
        <section className="bg-gray-50 px-6 py-20">
          <div className="mx-auto max-w-7xl">
            <div className="mb-10 flex items-end justify-between">
              <div>
                <p className="mb-1 text-xs font-semibold uppercase tracking-widest text-indigo-600">Fleet</p>
                <h2 className="text-3xl font-bold text-gray-900">{t("featured.title")}</h2>
                <p className="mt-2 text-gray-500">{t("featured.subtitle")}</p>
              </div>
              <Link href="/cars">
                <Button variant="ghost" className="hidden items-center gap-1 sm:flex text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50 rounded-lg">
                  {t("featured.viewAll")} <ChevronRight className="h-4 w-4" />
                </Button>
              </Link>
            </div>

            <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
              {vehicles.map((vehicle) => (
                <Link key={vehicle.id} href={`/cars/${vehicle.slug}`}>
                  <Card className="group overflow-hidden rounded-xl shadow-sm border-gray-100 hover:-translate-y-1 hover:shadow-lg hover:shadow-gray-200/80 transition-all duration-200">
                    <div className="relative h-48 overflow-hidden bg-gray-100">
                      {vehicle.primaryImageUrl ? (
                        <Image
                          src={vehicle.primaryImageUrl}
                          alt={vehicle.name}
                          fill
                          className="object-cover transition-transform duration-300 group-hover:scale-105"
                          unoptimized
                        />
                      ) : (
                        <div className="flex h-full items-center justify-center bg-gradient-to-br from-indigo-50 to-gray-50">
                          <Car className="h-16 w-16 text-indigo-200" />
                        </div>
                      )}
                      {vehicle.featured && (
                        <Badge className="absolute start-3 top-3 bg-indigo-600 text-white border-indigo-600 shadow-sm">
                          Featured
                        </Badge>
                      )}
                    </div>
                    <CardContent className="p-5">
                      <div className="flex items-start justify-between">
                        <div>
                          <p className="text-xs font-semibold text-indigo-600 uppercase tracking-wide">{vehicle.brand.name}</p>
                          <h3 className="font-semibold text-gray-900 mt-0.5 text-base">{vehicle.name}</h3>
                          <p className="mt-0.5 text-xs text-gray-400">{vehicle.tenant.name}</p>
                        </div>
                        <div className="text-end">
                          <p className="text-2xl font-bold text-gray-900">${Number(vehicle.dailyRate).toFixed(0)}</p>
                          <p className="text-xs text-gray-400">/ day</p>
                        </div>
                      </div>
                      <div className="mt-3 flex flex-wrap gap-1.5">
                        <span className="rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">
                          {vehicle.seats} seats
                        </span>
                        <span className="rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">
                          {vehicle.transmission === "AUTOMATIC" ? "Auto" : "Manual"}
                        </span>
                        <span className="rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">
                          {vehicle.fuelType.charAt(0) + vehicle.fuelType.slice(1).toLowerCase()}
                        </span>
                      </div>
                    </CardContent>
                  </Card>
                </Link>
              ))}
            </div>

            <div className="mt-8 text-center sm:hidden">
              <Link href="/cars">
                <Button variant="outline" className="rounded-lg">{t("featured.viewAll")}</Button>
              </Link>
            </div>
          </div>
        </section>
      )}

      {/* How It Works */}
      <section className="bg-white px-6 py-20">
        <div className="mx-auto max-w-5xl text-center">
          <p className="mb-1 text-xs font-semibold uppercase tracking-widest text-indigo-600">Process</p>
          <h2 className="text-3xl font-bold text-gray-900">{t("howItWorks.title")}</h2>
          <p className="mt-2 text-gray-500">{t("howItWorks.subtitle")}</p>
          <div className="mt-12 grid gap-6 sm:grid-cols-3">
            {[
              {icon: Search, step: "01", title: t("howItWorks.step1Title"), desc: t("howItWorks.step1Desc"), color: "bg-indigo-50 text-indigo-600"},
              {icon: Calendar, step: "02", title: t("howItWorks.step2Title"), desc: t("howItWorks.step2Desc"), color: "bg-emerald-50 text-emerald-600"},
              {icon: Car, step: "03", title: t("howItWorks.step3Title"), desc: t("howItWorks.step3Desc"), color: "bg-amber-50 text-amber-600"}
            ].map(({icon: Icon, step, title, desc, color}) => (
              <div key={step} className="relative rounded-2xl border border-gray-100 bg-gray-50 p-6 text-start hover:shadow-md hover:border-indigo-100 transition-all duration-200">
                <div className={`mb-4 inline-flex h-12 w-12 items-center justify-center rounded-xl ${color}`}>
                  <Icon className="h-5 w-5" />
                </div>
                <span className="absolute end-5 top-5 text-5xl font-black text-gray-100 select-none">{step}</span>
                <h3 className="text-base font-semibold text-gray-900">{title}</h3>
                <p className="mt-2 text-sm text-gray-500 leading-relaxed">{desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Partner Companies */}
      {companies.length > 0 && (
        <section className="bg-gray-50 px-6 py-20">
          <div className="mx-auto max-w-7xl">
            <div className="mb-10 flex items-end justify-between">
              <div>
                <p className="mb-1 text-xs font-semibold uppercase tracking-widest text-indigo-600">Partners</p>
                <h2 className="text-3xl font-bold text-gray-900">{t("companies.title")}</h2>
                <p className="mt-2 text-gray-500">{t("companies.subtitle")}</p>
              </div>
              <Link href="/companies">
                <Button variant="ghost" className="hidden items-center gap-1 sm:flex text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50 rounded-lg">
                  {t("companies.viewAll")} <ChevronRight className="h-4 w-4" />
                </Button>
              </Link>
            </div>
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {companies.map((company) => (
                <Link key={company.id} href={`/companies/${company.slug}`}>
                  <Card className="group rounded-xl border-gray-100 shadow-sm hover:-translate-y-0.5 hover:shadow-md hover:shadow-gray-200/60 transition-all duration-200">
                    <CardContent className="flex items-center gap-4 p-5">
                      <div className="flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-gray-100 bg-white shadow-sm">
                        {company.logoUrl ? (
                          <Image
                            src={company.logoUrl}
                            alt={company.name}
                            width={48}
                            height={48}
                            className="object-contain"
                            unoptimized
                          />
                        ) : (
                          <Building2 className="h-6 w-6 text-gray-300" />
                        )}
                      </div>
                      <div className="min-w-0 flex-1">
                        <h3 className="truncate font-semibold text-gray-900">{company.name}</h3>
                        {company.city && (
                          <div className="mt-0.5 flex items-center gap-1 text-xs text-gray-400">
                            <MapPin className="h-3 w-3 shrink-0" />
                            <span>{company.city}</span>
                          </div>
                        )}
                        <div className="mt-2 flex gap-3 text-xs text-gray-400">
                          <span className="flex items-center gap-1">
                            <Car className="h-3 w-3" />
                            {company._count.vehicles} vehicles
                          </span>
                          <span className="flex items-center gap-1">
                            <MapPin className="h-3 w-3" />
                            {company._count.branches} branches
                          </span>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* CTA Section */}
      <section className="relative overflow-hidden bg-gradient-to-br from-indigo-600 to-purple-700 px-6 py-20 text-white">
        <div className="pointer-events-none absolute inset-0">
          <div className="absolute -top-20 -right-20 h-80 w-80 rounded-full bg-white/5 blur-3xl" />
          <div className="absolute -bottom-20 -left-20 h-60 w-60 rounded-full bg-purple-400/10 blur-3xl" />
        </div>
        <div className="relative mx-auto max-w-3xl text-center">
          <h2 className="text-3xl font-bold sm:text-4xl">{t("cta.title")}</h2>
          <p className="mt-4 text-lg text-indigo-100/90">{t("cta.subtitle")}</p>
          <div className="mt-8 flex flex-wrap justify-center gap-4">
            <Link href="/cars" className="inline-block">
              <Button className="bg-white text-indigo-600 hover:bg-indigo-50 shadow-lg shadow-indigo-900/20 font-semibold rounded-lg" size="lg">
                {t("cta.btn")}
              </Button>
            </Link>
            <Link href="/auth/sign-in" className="inline-block">
              <Button
                variant="outline"
                className="border-white/30 bg-white/10 text-white hover:bg-white/20 hover:border-white/40 shadow-none rounded-lg"
                size="lg"
              >
                <LogIn className="me-2 h-5 w-5" />
                تسجيل الدخول للإدارة
              </Button>
            </Link>
          </div>
        </div>
      </section>
    </div>
  );
}
