'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import {
  CheckCircle2,
  ArrowRight,
  Calendar,
  Sparkles,
  ShieldCheck,
  Loader2,
  MapPin,
  Clock,
  CreditCard,
  Banknote,
  Send,
  CalendarPlus,
  MessageCircle,
} from 'lucide-react';
import { motion } from 'framer-motion';
import { type Locale } from '@/i18n';
import { ImageWithFallback } from '@/components/ui/ImageWithFallback';

export interface HydratedBooking {
  id: number | string;
  service_id?: number;
  service_name?: string;
  service_image?: string | null;
  date?: string;
  booking_slot?: string;
  time?: string;
  address?: string;
  flat?: string;
  building?: string;
  quantity?: number;
  total_amount?: number;
  payment_method?: string;
  payment_status?: string;
  customer_name?: string;
  customer_email?: string;
  customer_phone?: string;
  status?: string;
}

interface CheckoutSuccessClientProps {
  locale: Locale;
  initialBookingId?: string;
  intentId?: string;
  checkoutId?: string;
}

export default function CheckoutSuccessClient({
  locale,
  initialBookingId,
  intentId,
  checkoutId,
}: CheckoutSuccessClientProps) {
  const isAr = locale === 'ar';
  const [bookingId, setBookingId] = useState<string | undefined>(initialBookingId);
  const [booking, setBooking] = useState<HydratedBooking | null>(null);
  const [isVerifying, setIsVerifying] = useState<boolean>(!initialBookingId && !!(intentId || checkoutId));
  const [verifyError, setVerifyError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;
    let attempts = 0;
    const maxAttempts = 8;

    const verify = async () => {
      try {
        const query = new URLSearchParams();
        if (intentId) query.set('intent_id', intentId);
        if (checkoutId) query.set('checkout_id', checkoutId);
        if (initialBookingId && !intentId && !checkoutId) query.set('booking_id', initialBookingId);

        const res = await fetch(`/api/checkout/verify?${query.toString()}`);
        const data = await res.json().catch(() => ({}));

        if (!isMounted) return;

        if (data.status && (data.booking_id || data.booking?.id)) {
          const resolvedId = String(data.booking_id || data.booking?.id);
          setBookingId(resolvedId);
          if (data.booking) {
            setBooking(data.booking);
          }
          setIsVerifying(false);
          return;
        }

        if (data.status === false && data.pending === false) {
          setVerifyError(data.message || (isAr ? 'تعذر التحقق من الدفع' : 'Payment verification failed'));
          setIsVerifying(false);
          return;
        }

        attempts++;
        if (attempts < maxAttempts) {
          setTimeout(verify, 2000);
        } else {
          setIsVerifying(false);
        }
      } catch (err) {
        if (!isMounted) return;
        attempts++;
        if (attempts < maxAttempts) {
          setTimeout(verify, 2000);
        } else {
          setIsVerifying(false);
        }
      }
    };

    if (intentId || checkoutId || initialBookingId) {
      verify();
    }

    return () => {
      isMounted = false;
    };
  }, [initialBookingId, intentId, checkoutId, isAr]);

  const displayRef = bookingId
    ? `#SC-${bookingId}`
    : intentId
    ? `#INT-${intentId.slice(0, 8).toUpperCase()}`
    : '';

  // Format date display
  const formattedDate = React.useMemo(() => {
    if (!booking?.date) return '';
    try {
      const d = new Date(booking.date.replace(' ', 'T'));
      if (isNaN(d.getTime())) return booking.date.split(' ')[0] || '';
      return d.toLocaleDateString(isAr ? 'ar-AE' : 'en-US', {
        weekday: 'long',
        month: 'short',
        day: 'numeric',
        year: 'numeric',
      });
    } catch {
      return booking.date.split(' ')[0] || '';
    }
  }, [booking?.date, isAr]);

  // Generate Google Calendar Link
  const googleCalendarUrl = React.useMemo(() => {
    if (!booking?.date) return null;
    try {
      const dateOnly = booking.date.split(' ')[0]?.replace(/-/g, '') || '';
      const title = encodeURIComponent(booking.service_name || 'ShineCode Beauty Session');
      const details = encodeURIComponent(
        `ShineCode Luxury Doorstep Session. Booking Ref: ${displayRef}. Address: ${booking.address || ''}`
      );
      const location = encodeURIComponent(booking.address || 'Dubai, UAE');
      return `https://calendar.google.com/calendar/render?action=TEMPLATE&text=${title}&details=${details}&location=${location}&dates=${dateOnly}T090000Z/${dateOnly}T110000Z`;
    } catch {
      return null;
    }
  }, [booking, displayRef]);

  return (
    <div className="min-h-screen bg-zinc-50/60 dark:bg-zinc-950 flex flex-col items-center justify-center px-4 sm:px-6 py-12 sm:py-16 text-center transition-colors">
      
      {/* Animated Icon Container */}
      <motion.div
        initial={{ scale: 0.7, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        transition={{ type: 'spring', stiffness: 220, damping: 20 }}
        className="w-20 h-20 sm:w-24 sm:h-24 rounded-3xl bg-emerald-100 dark:bg-emerald-950/60 flex items-center justify-center mb-6 shadow-xl border border-emerald-200/60 dark:border-emerald-800/60"
      >
        <CheckCircle2 className="w-10 h-10 sm:w-12 sm:h-12 text-emerald-600 dark:text-emerald-400 stroke-[2.5]" />
      </motion.div>

      <div className="max-w-xl w-full space-y-6">
        
        {/* Header Badges & Title */}
        <div className="space-y-3">
          <div className="inline-flex items-center gap-1.5 px-3.5 py-1 rounded-full bg-emerald-50 dark:bg-emerald-950/50 border border-emerald-200 dark:border-emerald-800 text-emerald-700 dark:text-emerald-300 text-xs font-bold uppercase tracking-wider shadow-2xs">
            <ShieldCheck className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />
            <span>
              {booking?.payment_method === 'cash'
                ? (isAr ? 'تم تأكيد طلب الحجز (الدفع عند الزيارة)' : 'Cash / Card on Arrival Confirmed')
                : (isAr ? 'تم الدفع وتأكيد الموعد عبر نومود' : 'Payment Verified via Nomod')}
            </span>
          </div>

          <h1 className="text-2xl sm:text-4xl font-extrabold text-zinc-950 dark:text-white tracking-tight">
            {isAr ? '🎉 تم تأكيد حجزك بنجاح!' : '🎉 Booking Confirmed!'}
          </h1>

          <p className="text-zinc-600 dark:text-zinc-400 text-xs sm:text-sm leading-relaxed max-w-lg mx-auto">
            {isAr
              ? `تم تسجيل الموعد في النظام وتأمين نافذة الوصول${displayRef ? ` (رقم الحجز: ${displayRef})` : ''}. تم إرسال إشعار فوري لمزود الخدمة وتأكيد الحجز لبريدك الإلكتروني.`
              : `Your session is secured and scheduled in our real-time system${displayRef ? ` (Ref: ${displayRef})` : ''}. Real-time notifications have been dispatched to your service provider and email.`}
          </p>

          {isVerifying && (
            <div className="inline-flex items-center gap-2 text-xs text-brand-600 dark:text-brand-400 pt-1 font-medium bg-brand-50/70 dark:bg-brand-950/40 px-3 py-1 rounded-full">
              <Loader2 className="w-3.5 h-3.5 animate-spin" />
              <span>{isAr ? 'جاري مزامنة تفاصيل الحجز النهائية...' : 'Synchronizing official booking record...'}</span>
            </div>
          )}

          {verifyError && (
            <div className="p-3 bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-800 rounded-xl text-xs text-rose-700 dark:text-rose-300">
              {verifyError}
            </div>
          )}
        </div>

        {/* ── Fully Hydrated Booking Details Card ── */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.15 }}
          className="p-5 sm:p-6 bg-white dark:bg-zinc-900 border border-zinc-200/80 dark:border-zinc-800 rounded-3xl text-start space-y-4 shadow-sm"
        >
          {/* Service Header */}
          <div className="flex items-center gap-3.5 pb-4 border-b border-zinc-100 dark:border-zinc-800">
            <ImageWithFallback
              src={booking?.service_image || '/images/fallback-placeholder.svg'}
              fallbackSrc="/images/fallback-placeholder.svg"
              alt={booking?.service_name || 'Service'}
              width={56}
              height={56}
              className="w-14 h-14 rounded-2xl object-cover border border-zinc-200/80 dark:border-zinc-700 shrink-0 bg-zinc-100 dark:bg-zinc-800"
            />
            <div className="min-w-0 flex-1">
              <div className="text-xs font-semibold text-brand-600 dark:text-brand-400 uppercase tracking-wider">
                {isAr ? 'الخدمة المختارة' : 'Confirmed Treatment'}
              </div>
              <div className="font-bold text-zinc-950 dark:text-white text-base sm:text-lg truncate">
                {booking?.service_name || (isAr ? 'جلسة العناية والتجميل' : 'Beauty & Wellness Session')}
              </div>
              {displayRef && (
                <div className="text-xs font-mono font-bold text-zinc-400 dark:text-zinc-500">
                  {displayRef}
                </div>
              )}
            </div>
          </div>

          {/* Grid of Key Booking Facts */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3.5 text-xs">
            {/* Date */}
            <div className="p-3 bg-zinc-50 dark:bg-zinc-800/60 rounded-2xl border border-zinc-100 dark:border-zinc-800/80 space-y-1">
              <div className="flex items-center gap-1.5 text-zinc-400 dark:text-zinc-500 font-medium">
                <Calendar className="w-3.5 h-3.5" />
                <span>{isAr ? 'تاريخ الحجز' : 'Booking Date'}</span>
              </div>
              <div className="font-bold text-zinc-900 dark:text-white text-sm">
                {formattedDate || booking?.date?.split(' ')[0] || (isAr ? 'تم تأكيد الموعد' : 'Date Confirmed')}
              </div>
            </div>

            {/* Time Slot */}
            <div className="p-3 bg-zinc-50 dark:bg-zinc-800/60 rounded-2xl border border-zinc-100 dark:border-zinc-800/80 space-y-1">
              <div className="flex items-center gap-1.5 text-zinc-400 dark:text-zinc-500 font-medium">
                <Clock className="w-3.5 h-3.5" />
                <span>{isAr ? 'نافذة وقت الوصول' : 'Arrival Window'}</span>
              </div>
              <div className="font-bold text-zinc-900 dark:text-white text-sm">
                {booking?.time || booking?.booking_slot || (isAr ? 'نافذة وصول مؤكدة' : '09:00 AM – 11:30 PM')}
              </div>
            </div>

            {/* Location */}
            <div className="p-3 bg-zinc-50 dark:bg-zinc-800/60 rounded-2xl border border-zinc-100 dark:border-zinc-800/80 space-y-1 sm:col-span-2">
              <div className="flex items-center gap-1.5 text-zinc-400 dark:text-zinc-500 font-medium">
                <MapPin className="w-3.5 h-3.5" />
                <span>{isAr ? 'عنوان وموقع الزيارة المنزلية' : 'Doorstep Venue Address'}</span>
              </div>
              <div className="font-bold text-zinc-900 dark:text-white text-xs sm:text-sm leading-relaxed">
                {[booking?.flat, booking?.building, booking?.address].filter(Boolean).join(', ') || (isAr ? 'دبي / الشارقة / عجمان' : 'Doorstep Location (UAE)')}
              </div>
            </div>

            {/* Payment & Amount */}
            <div className="p-3 bg-zinc-50 dark:bg-zinc-800/60 rounded-2xl border border-zinc-100 dark:border-zinc-800/80 space-y-1">
              <div className="flex items-center gap-1.5 text-zinc-400 dark:text-zinc-500 font-medium">
                {booking?.payment_method === 'cash' ? <Banknote className="w-3.5 h-3.5" /> : <CreditCard className="w-3.5 h-3.5" />}
                <span>{isAr ? 'طريقة الدفع' : 'Payment Mode'}</span>
              </div>
              <div className="font-bold text-emerald-700 dark:text-emerald-400 text-xs sm:text-sm">
                {booking?.payment_method === 'cash'
                  ? (isAr ? 'نقداً / POS بعد الخدمة' : 'Cash / Card on Arrival')
                  : (isAr ? 'دفع إلكتروني آمن ✓' : 'Online Nomod Gateway ✓')}
              </div>
            </div>

            {/* Total */}
            <div className="p-3 bg-zinc-50 dark:bg-zinc-800/60 rounded-2xl border border-zinc-100 dark:border-zinc-800/80 space-y-1">
              <div className="text-zinc-400 dark:text-zinc-500 font-medium">
                {isAr ? 'المبلغ الإجمالي شامل الضريبة' : 'Total (incl. VAT)'}
              </div>
              <div className="font-black text-zinc-950 dark:text-white text-base">
                AED {booking?.total_amount ? Number(booking.total_amount).toFixed(2) : '--'}
              </div>
            </div>
          </div>
        </motion.div>

        {/* ── Multi-Channel Notification Status Confirmation Card ── */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.25 }}
          className="p-4 sm:p-5 bg-emerald-50/70 dark:bg-emerald-950/40 border border-emerald-200/80 dark:border-emerald-800/70 rounded-3xl text-start space-y-3 shadow-2xs"
        >
          <div className="text-xs font-bold text-emerald-900 dark:text-emerald-300 uppercase tracking-wider flex items-center gap-2">
            <Send className="w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400" />
            <span>{isAr ? 'حالة الإشعارات والتأكيد المباشر' : 'Dispatched Notification Status'}</span>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-emerald-900/90 dark:text-emerald-200">
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400 shrink-0" />
              <span>{isAr ? 'إشعار البريد الإلكتروني مع الفاتورة' : 'Confirmation email & invoice sent'}</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400 shrink-0" />
              <span>{isAr ? 'إشعار فوري لمزود الخدمة المعتمد' : 'Service provider notified in real-time'}</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400 shrink-0" />
              <span>{isAr ? 'تأكيد الحجز في لوحة تحكم الإدارة' : 'Admin live dashboard synced'}</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400 shrink-0" />
              <span>{isAr ? 'رسالة نصية وتحديثات الوصول' : 'Doorstep arrival alerts enabled'}</span>
            </div>
          </div>
        </motion.div>

        {/* ── Guarantees & Safety ── */}
        <div className="p-4 bg-white dark:bg-zinc-900 border border-zinc-200/80 dark:border-zinc-800 rounded-2xl text-start space-y-2.5 text-xs text-zinc-600 dark:text-zinc-400 shadow-2xs">
          <div className="flex items-center gap-2.5">
            <Sparkles className="w-4 h-4 text-brand-500 shrink-0" />
            <span>{isAr ? 'أدوات معقمة ومغلفة بالكامل تفتح أمامك قبل بدء الجلسة.' : '100% Sterilized and single-use kits unsealed right in front of you.'}</span>
          </div>
          <div className="flex items-center gap-2.5">
            <ShieldCheck className="w-4 h-4 text-emerald-600 dark:text-emerald-400 shrink-0" />
            <span>{isAr ? 'إلغاء مجاني ومرن حتى 4 ساعات قبل موعد الزيارة.' : 'Flexible & free cancellation up to 4 hours before the booking.'}</span>
          </div>
        </div>

        {/* ── Interactive CTA Actions ── */}
        <div className="space-y-2.5 pt-2">
          <div className="flex flex-col sm:flex-row gap-3">
            <Link
              href={`/${locale}/dashboard`}
              className="flex-1 h-13 bg-zinc-900 dark:bg-white hover:bg-brand-500 active:bg-brand-600 dark:hover:bg-brand-500 dark:hover:text-white text-white dark:text-zinc-950 font-bold rounded-2xl flex items-center justify-center gap-2 transition-all shadow-md text-sm cursor-pointer"
            >
              <span>{isAr ? 'متابعة الحجز في لوحة التحكم' : 'Track in Dashboard'}</span>
              <ArrowRight className="w-4 h-4 rtl:rotate-180" />
            </Link>

            {googleCalendarUrl && (
              <a
                href={googleCalendarUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="h-13 px-5 bg-zinc-100 dark:bg-zinc-800 hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-800 dark:text-zinc-200 font-semibold rounded-2xl flex items-center justify-center gap-2 transition-colors text-sm cursor-pointer shrink-0"
              >
                <CalendarPlus className="w-4 h-4" />
                <span>{isAr ? 'إضافة للتقويم' : 'Add to Calendar'}</span>
              </a>
            )}
          </div>

          <div className="flex flex-col sm:flex-row gap-2.5">
            <a
              href="https://wa.me/971501234567?text=Hello%20ShineCode%2C%20I%20have%20a%20question%20about%20my%20booking"
              target="_blank"
              rel="noopener noreferrer"
              className="flex-1 h-11 border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 hover:bg-zinc-50 dark:hover:bg-zinc-800 text-zinc-700 dark:text-zinc-300 font-semibold rounded-xl flex items-center justify-center gap-2 transition-colors text-xs cursor-pointer"
            >
              <MessageCircle className="w-3.5 h-3.5 text-emerald-500" />
              <span>{isAr ? 'مساعدة عبر الواتساب' : 'WhatsApp Concierge Support'}</span>
            </a>

            <Link
              href={`/${locale}/services`}
              className="flex-1 h-11 border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 hover:bg-zinc-50 dark:hover:bg-zinc-800 text-zinc-700 dark:text-zinc-300 font-semibold rounded-xl flex items-center justify-center gap-2 transition-colors text-xs cursor-pointer"
            >
              <span>{isAr ? 'استكشاف المزيد من الخدمات' : 'Explore More Services'}</span>
            </Link>
          </div>
        </div>

      </div>
    </div>
  );
}
