/**
 * Service Details Page (PDP) — "Airbnb Luxe" Architecture
 * 
 * Maximizes SEO and organic traffic conversion with a high-trust narrative engine,
 * interactive Accordion FAQs, verified reviews, and a sticky desktop booking card.
 * Smartly wired with live Laravel API service details and dynamic addons.
 */

import { type Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getServices, getServiceBySlug, getServiceDetail } from '@/lib/api/client';
import { ServiceDetailView, type ServiceDetailData, type ServiceAddon } from '@/components/service/ServiceDetailView';
import { adaptApiServiceAddon } from '@/lib/addons';
import { maskCustomerName, formatReviewDate, stripHtml } from '@/lib/utils';
import type { Service } from '@shinecode/api-client/types';
import { type Locale } from '@/i18n';

interface ServicePageProps {
  params: Promise<{ locale: Locale; slug: string }>;
}

export const revalidate = 60;

export async function generateStaticParams() {
  const result = await getServices();
  const slugs = new Set<string>();

  if (result.ok) {
    result.data.forEach((service) => {
      if (service.slug) slugs.add(service.slug);
    });
  }

  const params: { locale: Locale; slug: string }[] = [];
  slugs.forEach((slug) => {
    params.push({ locale: 'en', slug });
    params.push({ locale: 'ar', slug });
  });

  return params;
}

export async function generateMetadata({ params }: ServicePageProps): Promise<Metadata> {
  const { locale, slug } = await params;
  const isAr = locale === 'ar';

  let title = 'Service Treatment';
  let description = 'Book premium at-home beauty & wellness treatments in Dubai.';
  let image = 'https://images.unsplash.com/photo-1632345031435-8727f6897d53?w=1200&auto=format&fit=crop&q=85';

  const serviceResult = await getServiceBySlug(slug);
  if (serviceResult.ok && serviceResult.data) {
    const apiService = serviceResult.data;
    title = apiService.name;
    if (apiService.description) {
      description = stripHtml(apiService.description, 160);
    }
    
    if (Array.isArray(apiService.attchments) && apiService.attchments.length > 0) {
      const first = apiService.attchments[0];
      image = typeof first === 'string' ? first : (first?.url || image);
    } else if (apiService.provider_image) {
      image = apiService.provider_image;
    }
  }

  const pageTitle = isAr
    ? `${title} خدمة منزلية في دبي | ShineCode`
    : `${title} Home Service in Dubai | ShineCode`;

  return {
    title: pageTitle,
    description,
    alternates: {
      canonical: `https://shinecode.ae/${locale}/services/${slug}`,
      languages: {
        en: `https://shinecode.ae/en/services/${slug}`,
        ar: `https://shinecode.ae/ar/services/${slug}`,
        'x-default': `https://shinecode.ae/en/services/${slug}`,
      },
    },
    openGraph: {
      title: pageTitle,
      description,
      url: `https://shinecode.ae/${locale}/services/${slug}`,
      siteName: 'ShineCode Dubai',
      images: [
        {
          url: image,
          width: 1200,
          height: 630,
          alt: title,
        },
      ],
      type: 'website',
      locale: locale === 'ar' ? 'ar_AE' : 'en_AE',
    },
    twitter: {
      card: 'summary_large_image',
      title: pageTitle,
      description,
      images: [image],
    },
  };
}

export default async function ServiceDetailPage({ params }: ServicePageProps) {
  const { locale, slug } = await params;
  const isAr = locale === 'ar';

  let serviceData: ServiceDetailData | null = null;
  let relatedServicesData: Service[] = [];

  const [serviceResult, allServicesResult] = await Promise.all([
    getServiceBySlug(slug),
    getServices(),
  ]);
  
  if (serviceResult.ok && serviceResult.data) {
    const apiService = serviceResult.data;

    // Pick related services from the same category first, excluding the active service
    const allServices: Service[] = allServicesResult.ok && Array.isArray(allServicesResult.data) ? allServicesResult.data : [];
    const sameCategory = allServices.filter(
      (s) => s.category_id === apiService.category_id && s.id !== apiService.id && s.slug !== apiService.slug
    );
    const otherServices = allServices.filter(
      (s) => s.category_id !== apiService.category_id && s.id !== apiService.id && s.slug !== apiService.slug
    );
    relatedServicesData = [...sameCategory, ...otherServices].slice(0, 4);
    
    let heroImg = 'https://images.unsplash.com/photo-1632345031435-8727f6897d53?w=1000&auto=format&fit=crop&q=85';
    if (Array.isArray(apiService.attchments) && apiService.attchments.length > 0) {
      const first = apiService.attchments[0];
      heroImg = typeof first === 'string' ? first : (first?.url || heroImg);
    } else if (apiService.provider_image) {
      heroImg = apiService.provider_image;
    }

    let durationMinutes = 60;
    if (typeof apiService.duration === 'number') {
      durationMinutes = apiService.duration;
    } else if (typeof apiService.duration === 'string') {
      const parts = apiService.duration.split(':');
      if (parts.length >= 2) {
        const hours = parseInt(parts[0], 10) || 0;
        const mins = parseInt(parts[1], 10) || 0;
        durationMinutes = hours * 60 + mins || 60;
      } else {
        durationMinutes = parseInt(apiService.duration, 10) || 60;
      }
    }

    // Dynamic Live Addons from Laravel API
    let serviceAddons: ServiceAddon[] = [];
    let dynamicReviews: ServiceDetailData['reviews'] = [];
    let dynamicFaqsEn = [
      {
        question: 'How should I prepare my home for this treatment?',
        answer: 'Clear a comfortable chair and table space near a power outlet. Your artist brings all necessary tools and mats.',
      },
      {
        question: 'What is your cancellation policy?',
        answer: 'Free cancellation up to 4 hours before your scheduled appointment time.',
      },
    ];
    let dynamicFaqsAr = [
      {
        question: 'كيف أجهز منزلي للاستقبال؟',
        answer: 'وفري كرسياً وطاولة بالقرب من مقبس كهربائي، وستحضر الخبيرة كافة المعدات.',
      },
      {
        question: 'ما هي سياسة الإلغاء؟',
        answer: 'إلغاء مجاني حتى 4 ساعات قبل موعد جلستك المحدد.',
      },
    ];

    try {
      const detailResult = await getServiceDetail(apiService.id);
      if (detailResult.ok && detailResult.data) {
        const rawAddons = detailResult.data.serviceaddon;
        if (Array.isArray(rawAddons) && rawAddons.length > 0) {
          serviceAddons = rawAddons
            .filter((a) => a.status === 1 || a.status === undefined)
            .map((a) => adaptApiServiceAddon(a as unknown as Record<string, unknown>));
        }

        const rawRatings = Array.isArray(detailResult.data.rating_data)
          ? detailResult.data.rating_data
          : (Array.isArray(detailResult.data.customer_review) ? (detailResult.data.customer_review as Array<{ id: number; rating: number; review?: string | null; customer_name?: string; created_at?: string }>) : []);

        if (Array.isArray(rawRatings) && rawRatings.length > 0) {
          // Filter 5-star reviews
          const fiveStarRatings = rawRatings.filter((r) => Number(r.rating) === 5);
          const pool = fiveStarRatings.length > 0 ? fiveStarRatings : rawRatings;

          // Prioritize reviews with text at the top
          const withText = pool.filter((r) => typeof r.review === 'string' && r.review.trim().length > 0);
          const withoutText = pool.filter((r) => !r.review || !r.review.trim());

          // Sort both newest first
          withText.sort((a, b) => new Date(b.created_at || 0).getTime() - new Date(a.created_at || 0).getTime());
          withoutText.sort((a, b) => new Date(b.created_at || 0).getTime() - new Date(a.created_at || 0).getTime());

          const topReviews = [...withText, ...withoutText].slice(0, 3);

          dynamicReviews = topReviews.map((r, idx) => {
            const rawAuthor = typeof r.customer_name === 'string' ? r.customer_name : undefined;
            const author = maskCustomerName(rawAuthor);
            const dateEn = formatReviewDate(r.created_at, 'en');
            const dateAr = formatReviewDate(r.created_at, 'ar');
            const reviewText = typeof r.review === 'string' ? r.review.trim() : '';

            return {
              id: Number(r.id) || (idx + 1),
              author,
              dateEn,
              dateAr,
              rating: Number(r.rating) || 5,
              textEn: reviewText,
              textAr: reviewText,
            };
          });
        }

        const rawFaqs = detailResult.data.service_faq;
        if (Array.isArray(rawFaqs) && rawFaqs.length > 0) {
          dynamicFaqsEn = rawFaqs.map((f: { title?: string; question?: string; description?: string; answer?: string }) => ({
            question: f.title || f.question || '',
            answer: f.description || f.answer || '',
          }));
          dynamicFaqsAr = rawFaqs.map((f: { title?: string; question?: string; description?: string; answer?: string }) => ({
            question: f.title || f.question || '',
            answer: f.description || f.answer || '',
          }));
        }
      }
    } catch {
      // In case of network timeout, continue with base service data
    }

    serviceData = {
      id: apiService.id,
      slug: apiService.slug,
      nameEn: apiService.name,
      nameAr: apiService.name,
      categorySlug: apiService.category_name ? apiService.category_name.toLowerCase().replace(/[^a-z0-9]+/g, '-') : 'treatment',
      categoryNameEn: apiService.category_name || 'Beauty & Wellness',
      categoryNameAr: apiService.category_name || 'التجميل والعافية',
      price: apiService.discount_price || apiService.price,
      originalPrice: apiService.discount_price ? apiService.price : undefined,
      durationMinutes: durationMinutes,
      rating: Number(apiService.total_rating ?? apiService.rating ?? 0),
      reviewCount: Number(apiService.total_review ?? apiService.review_count ?? 0),
      heroImage: heroImg,
      descriptionEn: apiService.description || 'Premium doorstep beauty and wellness treatment in Dubai.',
      descriptionAr: apiService.description || 'علاج تجميلي فاخر يقدم في منزلك في دبي.',
      addons: serviceAddons,
      faqsEn: dynamicFaqsEn,
      faqsAr: dynamicFaqsAr,
      reviews: dynamicReviews,
    };
  }

  if (!serviceData) {
    notFound();
  }

  const cleanDescription = stripHtml(
    isAr ? serviceData.descriptionAr : serviceData.descriptionEn,
    200
  );

  // 1. Service Schema
  const serviceJsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Service',
    name: isAr ? serviceData.nameAr : serviceData.nameEn,
    description: cleanDescription,
    provider: {
      '@type': 'BeautySalon',
      name: 'ShineCode',
      url: 'https://shinecode.ae',
      telephone: '+97143298815',
      image: serviceData.heroImage || 'https://shinecode.ae/images/frontend/socialP.webp',
      priceRange: '$-$$',
      address: {
        '@type': 'PostalAddress',
        addressLocality: 'Dubai',
        addressRegion: 'Dubai',
        addressCountry: 'AE',
      },
    },
    areaServed: [
      { '@type': 'City', name: 'Dubai' },
      { '@type': 'City', name: 'Sharjah' },
      { '@type': 'City', name: 'Ajman' },
    ],
    offers: {
      '@type': 'Offer',
      price: serviceData.price,
      priceCurrency: 'AED',
      availability: 'https://schema.org/InStock',
      url: `https://shinecode.ae/${locale}/services/${slug}`,
    },
    aggregateRating: serviceData.rating > 0
      ? {
          '@type': 'AggregateRating',
          ratingValue: serviceData.rating,
          reviewCount: serviceData.reviewCount || 1,
          bestRating: 5,
          worstRating: 1,
        }
      : undefined,
  };

  // 2. BreadcrumbList Schema
  const breadcrumbJsonLd = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      {
        '@type': 'ListItem',
        position: 1,
        name: isAr ? 'الرئيسية' : 'Home',
        item: `https://shinecode.ae/${locale}`,
      },
      {
        '@type': 'ListItem',
        position: 2,
        name: isAr ? 'الخدمات' : 'Services',
        item: `https://shinecode.ae/${locale}/services`,
      },
      {
        '@type': 'ListItem',
        position: 3,
        name: isAr ? serviceData.categoryNameAr : serviceData.categoryNameEn,
        item: `https://shinecode.ae/${locale}/categories/${serviceData.categorySlug}`,
      },
      {
        '@type': 'ListItem',
        position: 4,
        name: isAr ? serviceData.nameAr : serviceData.nameEn,
        item: `https://shinecode.ae/${locale}/services/${slug}`,
      },
    ],
  };

  // 3. Dynamic FAQPage Schema (if FAQs exist)
  const activeFaqs = isAr ? serviceData.faqsAr : serviceData.faqsEn;
  const faqJsonLd =
    activeFaqs && activeFaqs.length > 0
      ? {
          '@context': 'https://schema.org',
          '@type': 'FAQPage',
          mainEntity: activeFaqs.map((f) => ({
            '@type': 'Question',
            name: f.question,
            acceptedAnswer: {
              '@type': 'Answer',
              text: stripHtml(f.answer, 500),
            },
          })),
        }
      : null;

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(serviceJsonLd) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbJsonLd) }}
      />
      {faqJsonLd && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd) }}
        />
      )}
      <ServiceDetailView
        service={serviceData}
        relatedServices={relatedServicesData}
        locale={locale}
      />
    </>
  );
}
