import FadeInText from '@/components/shared/FadeInText'
import { Section } from '@/components/ui/section'
import { getPayload } from 'payload'
import configPromise from '@payload-config'
import { Car, Media } from '@/payload-types'
import CarCard from '@/components/shared/cards/CarCard'
import StickyStackCards from '@/components/shared/StickyStackCards'
import { Vehicle, VehicleApiResponse } from '@/lib/types/api/vehicle'
import { customFetch } from '@/lib/utils/apiClient'
import { getI18n } from '@/locales/server'

export const RecommendsTeslaBlock = async () => {
  // const payload = await getPayload({ config: configPromise })

  // const result = await payload.find({
  //   collection: 'cars',
  //   limit: 4,
  //   pagination: false,
  //   depth: 2,
  // })

  // const docs = result.docs as Car[]

  let vehicles: Vehicle[] = []
  try {
    const vehicleResponse = await customFetch('https://api.rentsyst.com/v2/vehicle', true, 'GET')
    const vehicleData: VehicleApiResponse = await vehicleResponse.json()
    if (Array.isArray(vehicleData)) {
      vehicles = vehicleData.slice(0, 4)
    }
  } catch {
    console.error('Failed to fetch vehicles from rentsyst API')
  }

  const t = await getI18n()

  return (
    <Section sectionClass="py-30" boxClass="">
      <h2 className="h4 md:h2 mb-2 text-base-white">
        <FadeInText text={t('catalog.recommendedForYou')} />
      </h2>
      <div className="hidden md:grid md:grid-cols-2 lg:grid-cols-4 md:gap-5 lg:gap-4 mt-8">
        {vehicles.map((doc) => (
          <CarCard
            id={doc.id}
            key={doc.id}
            type={
              doc.brand.charAt(0).toUpperCase() + doc.brand.slice(1).toLowerCase() + ' ' + doc.mark
            }
            price={doc.price}
            image={doc.thumbnail}
            carLabels={[doc.color.title, `${doc.number_seats} seats`].filter(Boolean)}
          />
        ))}
      </div>
      <div className="md:hidden mt-8">
        <StickyStackCards className="mb-[65px]" cardGap={16}>
          {vehicles.map((doc, i) => (
            <CarCard
              id={doc.id}
              key={doc.id}
              type={
                doc.brand.charAt(0).toUpperCase() +
                doc.brand.slice(1).toLowerCase() +
                ' ' +
                doc.mark
              }
              price={doc.price}
              image={doc.thumbnail}
              carLabels={[doc.color.title, `${doc.number_seats} seats`].filter(Boolean)}
              isActive
            />
          ))}
        </StickyStackCards>
      </div>
    </Section>
  )
}
