/**
 * Checkout Route (/checkout)
 * 
 * Distraction-free checkout page for ShineCode.
 * Dedicated 5-step flow (Verification, Logistics, Calendar, Notes, Secure Payment)
 * with live real service data and add-on synchronization from Laravel backend API.
 */

import { type Metadata } from 'next';
import { notFound } from 'next/navigation';
import { CheckoutFlow, type CheckoutServiceDetails, type CheckoutAddon } from '@/components/checkout/CheckoutFlow';
import { getServices, getServiceDetail, getCoupons, slugify, type ApiCoupon } from '@/lib/api/client';
import { adaptApiServiceAddon } from '@/lib/addons';
import { type Locale } from '@/i18n';

interface CheckoutPageProps {
  params: Promise<{ locale: Locale }>;
  searchParams: Promise<{ id?: string; slug?: string; service?: string; quantity?: string; tier?: string; addons?: string }>;
}

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

  return {
    title: isAr
      ? 'الدفع الآمن وإتمام الحجز | ShineCode دبي'
      : 'Secure Checkout & Booking | ShineCode Dubai',
    description: isAr
      ? 'أكمل حجز جلستك التجميلية المنزلية بخطوات سهلة وآمنة مع ضمان الخصوصية والتعقيم الفائق.'
      : 'Complete your doorstep luxury treatment booking with fast, secure payment and 100% verified beauty professionals.',
    robots: {
      index: false,
      follow: false,
    },
  };
}

export default async function CheckoutPage({ params, searchParams }: CheckoutPageProps) {
  const { locale } = await params;
  const { id, slug, service, quantity, addons } = await searchParams;
  const targetIdentifier = slug || service;

  const initialQty = quantity ? Math.max(1, parseInt(quantity, 10) || 1) : 1;

  let serviceDetails: CheckoutServiceDetails | null = null;
  const initialSelectedAddons: CheckoutAddon[] = [];

  const servicesResult = await getServices();
  if (servicesResult.ok && servicesResult.data.length > 0) {
    let apiService = null;
    if (id) {
      apiService = servicesResult.data.find((s) => String(s.id) === id);
    } else if (targetIdentifier) {
      const target = targetIdentifier.toLowerCase().trim();
      apiService = servicesResult.data.find((s) => {
        const sSlug = s.slug.toLowerCase().trim();
        return sSlug === target || slugify(s.name) === target || sSlug.replace(/-/g, '') === target.replace(/-/g, '');
      });
    }

    // Default to the first live service if none specified or match not found
    if (!apiService && servicesResult.data.length > 0) {
      apiService = servicesResult.data[0];
    }
    
    if (apiService) {
      let heroImg = 'https://images.unsplash.com/photo-1632345031435-8727f6897d53?w=600&auto=format&fit=crop&q=85';
      if (Array.isArray(apiService.attchments) && apiService.attchments.length > 0) {
        heroImg = typeof apiService.attchments[0] === 'string' ? apiService.attchments[0] : (apiService.attchments[0]?.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;
        }
      }

      serviceDetails = {
        id: apiService.id,
        slug: apiService.slug,
        nameEn: apiService.name,
        nameAr: apiService.name,
        categoryEn: apiService.category_name || 'Beauty & Wellness',
        categoryAr: apiService.category_name || 'التجميل والعافية',
        price: apiService.discount_price || apiService.price,
        durationMinutes,
        image: heroImg,
      };

      // ── Synchronize Selected Add-ons from Live API & Query Params ──
      try {
        const detailResult = await getServiceDetail(apiService.id);
        const rawAddons = detailResult.ok && detailResult.data && Array.isArray(detailResult.data.serviceaddon)
          ? detailResult.data.serviceaddon
          : [];

        const liveApiAddons: CheckoutAddon[] = rawAddons.map((a) => {
          const adapted = adaptApiServiceAddon(a as unknown as Record<string, unknown>);
          return {
            ...adapted,
            qty: 1,
          };
        });

        if (addons && typeof addons === 'string') {
          const addonPairs = decodeURIComponent(addons).split(',').filter(Boolean);
          for (const pair of addonPairs) {
            const [addonId, rawQty] = pair.split(':');
            const cleanId = (addonId || '').trim();
            const qty = Math.max(1, parseInt(rawQty || '1', 10) || 1);
            if (!cleanId) continue;

            const matched = liveApiAddons.find((a) => a.id === cleanId || a.nameEn === cleanId || a.nameAr === cleanId);
            if (matched) {
              initialSelectedAddons.push({
                ...matched,
                qty,
              });
            }
          }
        }
      } catch (err) {
        console.error('[CheckoutPage] Error resolving service detail add-ons:', err);
      }

      // ── Synchronize Live Coupons for Service from Laravel API ──
      let initialCoupons: ApiCoupon[] = [];
      try {
        const couponsResult = await getCoupons(apiService.id);
        if (couponsResult.ok && couponsResult.data && Array.isArray(couponsResult.data.valid_cupon)) {
          initialCoupons = couponsResult.data.valid_cupon;
        }
      } catch (err) {
        console.error('[CheckoutPage] Error resolving coupons:', err);
      }

      return (
        <CheckoutFlow
          initialService={serviceDetails}
          locale={locale}
          initialQuantity={initialQty}
          initialAddons={initialSelectedAddons}
          initialCoupons={initialCoupons}
        />
      );
    }
  }

  notFound();
}

