import Link from 'next/link';
import type { FeaturedListPayload, ServiceDetail } from '@/types/api';
import { discoveryApi } from '@/lib/api';
import { SmartImage } from '@/components/ui';
import { demoForServiceType } from '@/lib/demo-images';

export async function FeaturedServices({ payload, locale }: { payload: FeaturedListPayload; locale: string }) {
  const ids = payload.service_public_ids ?? [];
  if (ids.length === 0) return null;

  const results = await Promise.allSettled(
    ids.map((id) => discoveryApi.getServiceDetail(id, locale)),
  );
  const services = results
    .filter((r): r is PromiseFulfilledResult<ServiceDetail> => r.status === 'fulfilled')
    .map((r) => r.value);

  if (services.length === 0) return null;

  return (
    <section className="py-8 md:py-12">
      {payload.title ? (
        <div className="mx-auto max-w-7xl px-4 pb-6">
          <h2 className="font-heading text-2xl md:text-3xl font-bold text-neutral-900 text-start">
            {payload.title}
          </h2>
        </div>
      ) : null}
      <div className="mx-auto max-w-7xl px-4">
        <ul className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 list-none p-0">
          {services.map((service) => (
            <li key={service.public_id}>
              <Link
                href={`/${locale}/services/${service.public_id}`}
                className="group block rounded-xl border border-neutral-200 bg-white hover:shadow-md transition-shadow overflow-hidden"
              >
                <div className="aspect-[4/3] bg-neutral-100 overflow-hidden">
                  <SmartImage
                    src={service.cover_image_url}
                    alt={service.name}
                    entity
                    placeholderLabel={service.name}
                    fallbackCategory={demoForServiceType(service.product_type, service.name)}
                    fallbackSeed={service.public_id}
                    sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 280px"
                    className="h-full w-full"
                    imgClassName="h-full w-full object-cover group-hover:scale-105 transition-transform duration-300"
                  />
                </div>
                <div className="p-3">
                  <p className="text-sm font-semibold text-neutral-900 leading-snug line-clamp-2">{service.name}</p>
                  {service.vendor ? (
                    <p className="mt-0.5 text-xs text-neutral-500 truncate">{service.vendor.business_name}</p>
                  ) : null}
                  <p className="mt-2 text-sm font-medium text-primary-700">
                    {Math.floor(service.price_from_minor / 100).toLocaleString()} {service.currency}
                  </p>
                </div>
              </Link>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}
