'use client';

import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { useTranslations } from 'next-intl';
import { discoveryApi } from '@/lib/api';
import { ServiceCardClient } from '@/components/ServiceCardClient';
import { EmptyState } from '@/components/ui/empty-state';
import { ErrorState } from '@/components/ui/error-state';
import { Skeleton } from '@/components/ui/skeleton';
import { AddToEventButton } from '@/components/vendor/AddToEventButton';

interface Props {
  vendorPublicId: string;
  locale: string;
  servicesHeading: string;
  noServicesLabel: string;
}

export function VendorServicesSection({
  vendorPublicId,
  locale,
  servicesHeading,
  noServicesLabel,
}: Props) {
  const t = useTranslations('vendor');
  const { data: services, isLoading, isError, refetch } = useQuery({
    queryKey: ['vendor-services', vendorPublicId, locale],
    queryFn: () => {
      const q = new URLSearchParams({ vendor_public_id: vendorPublicId });
      return discoveryApi.searchServices(q, locale);
    },
    staleTime: 60_000,
  });

  return (
    <div>
      <h2 className="font-heading text-lg font-semibold text-neutral-900 text-start mb-4">
        {servicesHeading}
      </h2>

      {isLoading ? (
        <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
          {Array.from({ length: 6 }).map((_, i) => (
            <Skeleton key={i} className="h-48 rounded-xl" />
          ))}
        </div>
      ) : isError ? (
        <ErrorState
          body={t('services_load_error')}
          onRetry={refetch}
          retryLabel={t('services_retry')}
          inline
        />
      ) : !services || services.items.length === 0 ? (
        <EmptyState heading={noServicesLabel} />
      ) : (
        <>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
            {services.items.map((service) => (
              <div key={service.public_id} className="flex flex-col gap-2">
                <ServiceCardClient service={service} locale={locale} />
                <AddToEventButton service={service} variant="card" />
              </div>
            ))}
          </div>
          {/* Secondary, demoted: "Browse all services from this vendor". */}
          <div className="mt-6 text-center">
            <Link
              href={`/${locale}/search?vendor_public_id=${vendorPublicId}`}
              className="text-sm text-neutral-600 hover:underline"
              data-testid="vendor-browse-all-link"
            >
              {services.meta.total > services.items.length
                ? t('view_all_count', { count: services.meta.total })
                : t('browse_all_secondary')}
            </Link>
          </div>
        </>
      )}
    </div>
  );
}
