export const dynamic = 'force-dynamic';
import { prisma } from '@/lib/prisma';
import { InventoryClient } from './inventory-client';

export default async function InventoryPage({ searchParams }: { searchParams: any }) {
  const params = searchParams ?? {};
  let vehicles: any[] = [];
  let categories: any[] = [];
  let makes: string[] = [];
  let years: number[] = [];
  let engines: string[] = [];
  let transmissions: string[] = [];
  let totalCount = 0;

  try {
    const where: any = {};
    if (params?.category) {
      const cat = await prisma.category.findUnique({
        where: { slug: params.category },
        include: { children: true },
      });
      if (cat) {
        // If category has children, include vehicles from all subcategories too
        const childIds = (cat.children ?? []).map((c: any) => c.id);
        if (childIds.length > 0 && !params?.subcategory) {
          where.categoryId = { in: [cat.id, ...childIds] };
        } else {
          where.categoryId = cat.id;
        }
      }
    }
    // Handle subcategory filter
    if (params?.subcategory) {
      const subCat = await prisma.category.findUnique({ where: { slug: params.subcategory } });
      if (subCat) where.categoryId = subCat.id;
    }
    if (params?.make) where.make = params.make;
    if (params?.year) where.year = parseInt(params.year);
    if (params?.status && params.status !== 'ALL') where.status = params.status;
    if (params?.engine) where.engineType = params.engine;
    if (params?.transmission) where.transmission = params.transmission;
    if (params?.minPrice || params?.maxPrice) {
      where.price = {};
      if (params?.minPrice) where.price.gte = parseFloat(params.minPrice);
      if (params?.maxPrice) where.price.lte = parseFloat(params.maxPrice);
    }
    if (params?.search) {
      where.OR = [
        { title: { contains: params.search, mode: 'insensitive' } },
        { make: { contains: params.search, mode: 'insensitive' } },
        { model: { contains: params.search, mode: 'insensitive' } },
      ];
    }

    const page = parseInt(params?.page ?? '1');
    const perPage = 12;

    totalCount = await prisma.vehicle.count({ where });
    vehicles = await prisma.vehicle.findMany({
      where,
      include: { images: { orderBy: { order: 'asc' } }, category: true },
      orderBy: { createdAt: 'desc' },
      skip: (page - 1) * perPage,
      take: perPage,
    });

    categories = await prisma.category.findMany({
      orderBy: { order: 'asc' },
      include: {
        children: { orderBy: { order: 'asc' } },
        _count: { select: { vehicles: true } },
      },
    });
    const allMakes = await prisma.vehicle.findMany({ select: { make: true }, distinct: ['make'], orderBy: { make: 'asc' } });
    makes = (allMakes ?? [])?.map((m: any) => m?.make ?? '')?.filter(Boolean);
    const allYears = await prisma.vehicle.findMany({ select: { year: true }, distinct: ['year'], orderBy: { year: 'desc' } });
    years = (allYears ?? [])?.map((y: any) => y?.year ?? 0)?.filter(Boolean);
    const allEngines = await prisma.vehicle.findMany({ select: { engineType: true }, distinct: ['engineType'], orderBy: { engineType: 'asc' } });
    engines = (allEngines ?? [])?.map((e: any) => e?.engineType ?? '')?.filter(Boolean);
    const allTransmissions = await prisma.vehicle.findMany({ select: { transmission: true }, distinct: ['transmission'], orderBy: { transmission: 'asc' } });
    transmissions = (allTransmissions ?? [])?.map((t: any) => t?.transmission ?? '')?.filter(Boolean);
  } catch (e) {
    console.error('Inventory error:', e);
  }

  return (
    <InventoryClient
      vehicles={JSON.parse(JSON.stringify(vehicles ?? []))}
      categories={JSON.parse(JSON.stringify(categories ?? []))}
      makes={makes ?? []}
      years={years ?? []}
      engines={engines ?? []}
      transmissions={transmissions ?? []}
      totalCount={totalCount ?? 0}
      currentParams={params ?? {}}
    />
  );
}
