'use client';

import { Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { useQuery, useMutation } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { useState } from 'react';
import { 
  Clock, 
  Users, 
  CheckCircle2, 
  AlertCircle,
  Download,
  Share2,
  Copy,
  Check,
  CreditCard,
  Wallet
} from 'lucide-react';
import { format } from 'date-fns';
import QRCode from 'qrcode.react';

function BookingDetailContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const bookingRef = searchParams.get('ref') || searchParams.get('bookingRef') || searchParams.get('pnr');
  
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>('');
  const [copiedPNR, setCopiedPNR] = useState(false);
  const [isGeneratingVoucher, setIsGeneratingVoucher] = useState(false);

  const { data: booking, isLoading, error, refetch } = useQuery({
    queryKey: ['booking-detail', bookingRef],
    queryFn: async () => {
      if (!bookingRef) throw new Error('No booking reference provided');
      console.log('🔍 Fetching Booking:', bookingRef);
      const response = await apiClient.get(`/bookings/${bookingRef}`);
      console.log('✅ Booking Response:', response);
      // Handle wrapped response
      return (response as any)?.data || response;
    },
    enabled: !!bookingRef,
    retry: 1,
  });

  const { data: paymentMethods } = useQuery({
    queryKey: ['payment-methods'],
    queryFn: () => apiClient.get('/payments/methods'),
    enabled: booking?.status === 'PENDING_PAYMENT' || booking?.status === 'DRAFT',
  });

  const paymentMutation = useMutation({
    mutationFn: async (paymentData: any) => {
      const response = await apiClient.post('/payments/intent', paymentData);
      return response;
    },
    onSuccess: async (data: any) => {
      console.log('Payment intent created:', data);
      await apiClient.patch(`/bookings/${booking?.id}/confirm`, {
        paymentIntentId: data.id,
        paymentMethod: selectedPaymentMethod,
      });
      refetch();
    },
    onError: (error: any) => {
      console.error('Payment failed:', error);
      alert(error?.response?.data?.message || 'Payment failed. Please try again.');
    },
  });

  const handlePayment = () => {
    if (!selectedPaymentMethod) {
      alert('Please select a payment method');
      return;
    }

    paymentMutation.mutate({
      bookingId: booking?.id,
      amount: booking?.totalMinor || 0,
      currency: booking?.currency || 'ETB',
      paymentMethodId: selectedPaymentMethod,
    });
  };

  const copyPNR = () => {
    if (booking?.bookingRef) {
      navigator.clipboard.writeText(booking.bookingRef);
      setCopiedPNR(true);
      setTimeout(() => setCopiedPNR(false), 2000);
    }
  };

  const handleDownloadVoucher = async () => {
    if (!booking || !booking.bookingRef) {
      alert('Booking data not available. Please try again.');
      return;
    }

    setIsGeneratingVoucher(true);
    try {
      console.log('📄 Generating voucher for booking:', booking);
      const { generateVoucherPDF } = await import('@/lib/generate-voucher');
      await generateVoucherPDF(booking as any);
    } catch (error) {
      console.error('Failed to generate voucher:', error);
      alert(`Failed to generate voucher: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsGeneratingVoucher(false);
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
        <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 text-center max-w-md w-full">
          <div className="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4" />
          <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Loading Booking Details</h2>
          <p className="text-sm text-gray-500 dark:text-gray-400">Fetching your booking information...</p>
        </div>
      </div>
    );
  }

  if (error || !booking) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
        <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 text-center max-w-md w-full">
          <div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
            <AlertCircle className="w-8 h-8 text-red-500" />
          </div>
          <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Booking Not Found</h2>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
            {!bookingRef 
              ? 'No booking reference provided in the URL.'
              : `Unable to find booking with reference: ${bookingRef}`
            }
          </p>
          <button onClick={() => refetch()} className="btn-secondary mb-2">Try Again</button>
          <button onClick={() => router.push('/booking/search')} className="btn-primary">New Booking</button>
        </div>
      </div>
    );
  }

  const isPendingPayment = booking.status === 'PENDING_PAYMENT' || booking.status === 'DRAFT';
  const isConfirmed = booking.status === 'TICKETED' || booking.status === 'CONFIRMED';
  const isExpired = booking.status === 'EXPIRED';
  const isCancelled = booking.status === 'CANCELLED';

  console.log('📊 Booking Status:', booking.status);
  console.log('📊 isPendingPayment:', isPendingPayment);
  console.log('📊 isConfirmed:', isConfirmed);
  console.log('📊 isExpired:', isExpired);
  console.log('📊 isCancelled:', isCancelled);

  const StatusBadge = () => {
    const statusConfig = {
      PENDING_PAYMENT: { color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400', label: 'Pending Payment' },
      DRAFT: { color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400', label: 'Pending Payment' },
      CONFIRMED: { color: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400', label: 'Confirmed' },
      TICKETED: { color: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400', label: 'Ticketed' },
      EXPIRED: { color: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400', label: 'Expired' },
      CANCELLED: { color: 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300', label: 'Cancelled' },
    };

    const config = statusConfig[booking.status as keyof typeof statusConfig] || statusConfig.DRAFT;

    return (
      <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-semibold ${config.color}`}>
        {isConfirmed && <CheckCircle2 className="w-4 h-4" />}
        {config.label}
      </span>
    );
  };

  if (isPendingPayment && !isExpired) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-6">
        <div className="container mx-auto px-4">
          <div className="max-w-5xl mx-auto">
            
            <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 mb-6 border border-gray-200 dark:border-gray-700">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Complete Payment</h1>
                  <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    Booking Reference: <span className="font-mono font-semibold">{booking.bookingRef}</span>
                  </p>
                </div>
                <StatusBadge />
              </div>
              
              {booking.createdAt && (
                <div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3 flex items-center gap-2">
                  <Clock className="w-5 h-5 text-amber-600 dark:text-amber-400" />
                  <span className="text-sm text-amber-800 dark:text-amber-300">
                    Booking created on {format(new Date(booking.createdAt), 'PPpp')}
                  </span>
                </div>
              )}
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              
              <div className="lg:col-span-2 space-y-6">
                
                <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
                  <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">Trip Summary</h2>
                  
                  <div className="flex items-center gap-2 mb-4">
                    <div className="w-2 h-2 bg-primary rounded-full" />
                    <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">Your Journey</span>
                    {booking.passengers?.[0]?.seat?.seatClass && (
                      <span className="ml-auto text-xs px-2 py-0.5 bg-primary/10 text-primary rounded-full font-medium">
                        {booking.passengers[0].seat.seatClass}
                      </span>
                    )}
                  </div>

                  {/* Flight-style timeline */}
                  <div className="flex">
                    {/* Left column: Timeline with dots and line */}
                    <div className="flex flex-col items-center w-8 flex-shrink-0">
                      {/* Origin dot */}
                      <div className="w-4 h-4 rounded-full border-4 border-primary bg-white dark:bg-gray-900 z-10" />
                      {/* Vertical line */}
                      <div className="w-0.5 flex-1 bg-gradient-to-b from-primary via-gray-300 dark:via-gray-700 to-gray-300 dark:to-gray-700 my-2" />
                      {/* Destination dot */}
                      <div className="w-4 h-4 rounded-full border-4 border-gray-400 dark:border-gray-600 bg-white dark:bg-gray-900 z-10" />
                    </div>
                    
                    {/* Right column: Content */}
                    <div className="flex-1 flex flex-col">
                      {/* Origin */}
                      <div className="pb-8">
                        <div className="text-2xl font-bold text-gray-900 dark:text-white">
                          {booking.schedule?.departureAt ? format(new Date(booking.schedule.departureAt), 'HH:mm') : '--:--'}
                        </div>
                        <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                          {booking.schedule?.departureAt ? format(new Date(booking.schedule.departureAt), 'EEE, MMM d') : 'N/A'}
                        </div>
                        <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                          {booking.schedule?.origin?.name}
                        </div>
                        <div className="text-sm text-gray-500 dark:text-gray-400">
                          {booking.schedule?.origin?.city}
                        </div>
                      </div>

                      {/* Journey Info */}
                      <div className="pb-8">
                        <div className="flex items-center gap-6 text-sm text-gray-600 dark:text-gray-400">
                          <div className="flex items-center gap-1.5">
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                            </svg>
                            <span className="font-medium">Train {booking.schedule?.trainNumber}</span>
                          </div>
                          {booking.schedule?.trainName && (
                            <span className="text-xs text-gray-500 dark:text-gray-400">
                              {booking.schedule.trainName}
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Destination */}
                      <div>
                        <div className="text-2xl font-bold text-gray-900 dark:text-white">
                          {booking.schedule?.arrivalAt ? format(new Date(booking.schedule.arrivalAt), 'HH:mm') : '--:--'}
                        </div>
                        <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                          {booking.schedule?.arrivalAt ? format(new Date(booking.schedule.arrivalAt), 'EEE, MMM d') : 'N/A'}
                        </div>
                        <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                          {booking.schedule?.destination?.name}
                        </div>
                        <div className="text-sm text-gray-500 dark:text-gray-400">
                          {booking.schedule?.destination?.city}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="border-t border-gray-200 dark:border-gray-700 pt-4">
                    <div className="flex items-center gap-2 mb-3">
                      <Users className="w-4 h-4 text-gray-500" />
                      <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                        {booking.passengers?.length || 0} Passenger(s)
                      </span>
                    </div>
                    <div className="space-y-2">
                      {booking.passengers?.map((passenger: any, idx: number) => (
                        <div key={idx} className="flex items-center justify-between text-sm py-2 px-3 bg-gray-50 dark:bg-gray-900 rounded-lg">
                          <div>
                            <div className="text-gray-900 dark:text-white font-medium">{passenger.fullName}</div>
                            <div className="text-xs text-gray-500 dark:text-gray-400">
                              {passenger.category} • Coach {passenger.seat?.coach}
                            </div>
                          </div>
                          <div className="text-right">
                            <div className="font-semibold text-gray-900 dark:text-white">
                              Seat {passenger.seat?.number}
                            </div>
                            <div className="text-xs text-gray-500 dark:text-gray-400">
                              {passenger.seat?.seatClass}
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
                  <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">Select Payment Method</h2>
                  
                  {paymentMethods && Array.isArray(paymentMethods) && paymentMethods.length > 0 ? (
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      {paymentMethods.map((method: any) => (
                        <button
                          key={method.id}
                          onClick={() => setSelectedPaymentMethod(method.id)}
                          className={`p-4 rounded-xl border-2 text-left transition-all ${
                            selectedPaymentMethod === method.id
                              ? 'border-primary bg-primary/5 dark:bg-primary/10'
                              : 'border-gray-200 dark:border-gray-700 hover:border-primary/50'
                          }`}
                        >
                          <div className="flex items-center gap-3">
                            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                              selectedPaymentMethod === method.id
                                ? 'bg-primary/20 dark:bg-primary/30'
                                : 'bg-gray-100 dark:bg-gray-700'
                            }`}>
                              {method.type === 'WALLET' ? (
                                <Wallet className={`w-5 h-5 ${selectedPaymentMethod === method.id ? 'text-primary' : 'text-gray-600 dark:text-gray-400'}`} />
                              ) : (
                                <CreditCard className={`w-5 h-5 ${selectedPaymentMethod === method.id ? 'text-primary' : 'text-gray-600 dark:text-gray-400'}`} />
                              )}
                            </div>
                            <div className="flex-1">
                              <div className="font-semibold text-gray-900 dark:text-white">{method.displayName}</div>
                              <div className="text-xs text-gray-500 dark:text-gray-400">{method.currency}</div>
                            </div>
                            {selectedPaymentMethod === method.id && (
                              <Check className="w-5 h-5 text-primary" />
                            )}
                          </div>
                        </button>
                      ))}
                    </div>
                  ) : (
                    <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                      No payment methods available
                    </div>
                  )}
                </div>

                <button
                  onClick={handlePayment}
                  disabled={!selectedPaymentMethod || paymentMutation.isPending}
                  className="w-full py-4 bg-gradient-to-r from-[rgb(20,113,76)] to-[rgb(16,95,65)] hover:from-[rgb(16,89,60)] hover:to-[rgb(12,75,50)] text-white font-bold text-lg rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg"
                >
                  {paymentMutation.isPending ? 'Processing Payment...' : `Pay ${booking.displayCurrency} ${((booking.displayTotalMinor || booking.totalMinor || 0) / 100).toFixed(2)}`}
                </button>
              </div>

              <div className="lg:col-span-1">
                <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700 sticky top-6">
                  <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">Order Summary</h2>
                  
                  <div className="space-y-3 mb-4">
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600 dark:text-gray-400">Subtotal ({booking.adultCount} Adult{booking.adultCount > 1 ? 's' : ''}{booking.childCount > 0 ? `, ${booking.childCount} Child${booking.childCount > 1 ? 'ren' : ''}` : ''})</span>
                      <span className="font-semibold text-gray-900 dark:text-white">
                        {booking.currency} {((booking.totalMinor || 0) / 100).toFixed(2)}
                      </span>
                    </div>
                  </div>
                  
                  <div className="border-t border-gray-200 dark:border-gray-700 pt-4 mt-4">
                    <div className="flex justify-between">
                      <span className="text-lg font-bold text-gray-900 dark:text-white">Total</span>
                      <span className="text-2xl font-bold text-primary">
                        {booking.displayCurrency} {((booking.displayTotalMinor || booking.totalMinor || 0) / 100).toFixed(2)}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (isConfirmed || isCancelled || isExpired) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-6">
        <div className="container mx-auto px-4">
          <div className="max-w-4xl mx-auto">
            
            <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 mb-6 text-center border border-gray-200 dark:border-gray-700">
              <div className={`w-20 h-20 ${isConfirmed ? 'bg-green-100 dark:bg-green-900/30' : 'bg-gray-100 dark:bg-gray-700'} rounded-full flex items-center justify-center mx-auto mb-4`}>
                {isConfirmed ? (
                  <CheckCircle2 className="w-10 h-10 text-green-600 dark:text-green-400" />
                ) : (
                  <AlertCircle className="w-10 h-10 text-gray-500" />
                )}
              </div>
              <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
                {isConfirmed ? 'Booking Confirmed!' : isCancelled ? 'Booking Cancelled' : 'Booking Expired'}
              </h1>
              <p className="text-gray-600 dark:text-gray-400 mb-6">
                {isConfirmed ? 'Your tickets have been generated successfully' : isCancelled ? 'This booking has been cancelled' : 'This booking has expired'}
              </p>
              
              <div className="inline-flex items-center gap-3 bg-gray-50 dark:bg-gray-900 rounded-xl px-6 py-4">
                <div className="text-left">
                  <div className="text-xs text-gray-500 dark:text-gray-400 mb-1">Booking Reference</div>
                  <div className="text-2xl font-mono font-bold text-primary">{booking.bookingRef}</div>
                </div>
                <button
                  onClick={copyPNR}
                  className="w-10 h-10 rounded-lg bg-white dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 border border-gray-200 dark:border-gray-700 flex items-center justify-center transition-all"
                >
                  {copiedPNR ? <Check className="w-5 h-5 text-green-600" /> : <Copy className="w-5 h-5 text-gray-600 dark:text-gray-400" />}
                </button>
              </div>

              <div className="flex flex-wrap gap-3 justify-center mt-6">
                {isConfirmed && (
                  <>
                    <button 
                      onClick={handleDownloadVoucher}
                      disabled={isGeneratingVoucher}
                      className="btn-primary flex items-center gap-2"
                    >
                      {isGeneratingVoucher ? (
                        <>
                          <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                          Generating...
                        </>
                      ) : (
                        <>
                          <Download className="w-4 h-4" />
                          Download Voucher
                        </>
                      )}
                    </button>
                    <button className="btn-secondary flex items-center gap-2">
                      <Download className="w-4 h-4" />
                      Download Tickets
                    </button>
                    <button className="btn-secondary flex items-center gap-2">
                      <Share2 className="w-4 h-4" />
                      Share
                    </button>
                  </>
                )}
              </div>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 mb-6 border border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">Journey Details</h2>
              
              <div className="flex items-center gap-2 mb-4">
                <div className="w-2 h-2 bg-primary rounded-full" />
                <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">Your Journey</span>
                {booking.passengers?.[0]?.seat?.seatClass && (
                  <span className="ml-auto text-xs px-2 py-0.5 bg-primary/10 text-primary rounded-full font-medium">
                    {booking.passengers[0].seat.seatClass}
                  </span>
                )}
              </div>

              {/* Flight-style timeline */}
              <div className="flex">
                {/* Left column: Timeline with dots and line */}
                <div className="flex flex-col items-center w-8 flex-shrink-0">
                  {/* Origin dot */}
                  <div className="w-4 h-4 rounded-full border-4 border-primary bg-white dark:bg-gray-900 z-10" />
                  {/* Vertical line */}
                  <div className="w-0.5 flex-1 bg-gradient-to-b from-primary via-gray-300 dark:via-gray-700 to-gray-300 dark:to-gray-700 my-2" />
                  {/* Destination dot */}
                  <div className="w-4 h-4 rounded-full border-4 border-gray-400 dark:border-gray-600 bg-white dark:bg-gray-900 z-10" />
                </div>
                
                {/* Right column: Content */}
                <div className="flex-1 flex flex-col">
                  {/* Origin */}
                  <div className="pb-8">
                    <div className="text-2xl font-bold text-gray-900 dark:text-white">
                      {booking.schedule?.departureAt ? format(new Date(booking.schedule.departureAt), 'HH:mm') : '--:--'}
                    </div>
                    <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                      {booking.schedule?.departureAt ? format(new Date(booking.schedule.departureAt), 'EEE, MMM d') : 'N/A'}
                    </div>
                    <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                      {booking.schedule?.origin?.name}
                    </div>
                    <div className="text-sm text-gray-500 dark:text-gray-400">
                      {booking.schedule?.origin?.city}
                    </div>
                  </div>

                  {/* Journey Info */}
                  <div className="pb-8">
                    <div className="flex items-center gap-6 text-sm text-gray-600 dark:text-gray-400">
                      <div className="flex items-center gap-1.5">
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                        </svg>
                        <span className="font-medium">Train {booking.schedule?.trainNumber}</span>
                      </div>
                      {booking.schedule?.trainName && (
                        <span className="text-xs text-gray-500 dark:text-gray-400">
                          {booking.schedule.trainName}
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Destination */}
                  <div>
                    <div className="text-2xl font-bold text-gray-900 dark:text-white">
                      {booking.schedule?.arrivalAt ? format(new Date(booking.schedule.arrivalAt), 'HH:mm') : '--:--'}
                    </div>
                    <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                      {booking.schedule?.arrivalAt ? format(new Date(booking.schedule.arrivalAt), 'EEE, MMM d') : 'N/A'}
                    </div>
                    <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                      {booking.schedule?.destination?.name}
                    </div>
                    <div className="text-sm text-gray-500 dark:text-gray-400">
                      {booking.schedule?.destination?.city}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">
                Passenger Details ({booking.passengers?.length || 0})
              </h2>
              
              <div className="space-y-4">
                {booking.passengers?.map((passenger: any, idx: number) => (
                  <div key={idx} className="border border-gray-200 dark:border-gray-700 rounded-xl p-4">
                    <div className="flex flex-col md:flex-row md:items-center gap-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="w-6 h-6 bg-primary text-white rounded-full flex items-center justify-center text-xs font-bold">
                            {idx + 1}
                          </span>
                          <h3 className="font-bold text-gray-900 dark:text-white">{passenger.fullName}</h3>
                          <span className="text-xs px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded-full">
                            {passenger.category}
                          </span>
                        </div>
                        
                        <div className="grid grid-cols-2 gap-3 text-sm">
                          <div>
                            <span className="text-gray-500 dark:text-gray-400">Coach:</span>
                            <div className="font-mono font-semibold text-gray-900 dark:text-white">
                              {passenger.seat?.coach || 'N/A'}
                            </div>
                          </div>
                          <div>
                            <span className="text-gray-500 dark:text-gray-400">Seat Number:</span>
                            <div className="font-semibold text-gray-900 dark:text-white">
                              {passenger.seat?.number || 'N/A'}
                            </div>
                          </div>
                          <div className="col-span-2">
                            <span className="text-gray-500 dark:text-gray-400">Class:</span>
                            <div className="font-medium text-gray-900 dark:text-white">
                              {passenger.seat?.seatClass || 'N/A'}
                            </div>
                          </div>
                        </div>
                      </div>

                      {isConfirmed && (
                        <div className="flex-shrink-0">
                          <div className="bg-white p-3 rounded-lg border-2 border-gray-200">
                            <QRCode
                              value={`TICKET:${booking.bookingRef}-${passenger.seat?.id || idx}`}
                              size={80}
                              level="M"
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="mt-6 text-center">
              <button onClick={() => router.push('/booking/search')} className="btn-primary">
                Book Another Trip
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Fallback for any other status
  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
      <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 text-center max-w-md w-full">
        <div className="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4">
          <AlertCircle className="w-8 h-8 text-gray-500" />
        </div>
        <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Unknown Booking Status</h2>
        <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
          Booking status: {booking.status}
        </p>
        <button onClick={() => router.push('/booking/search')} className="btn-primary">New Booking</button>
      </div>
    </div>
  );
}

export default function BookingDetailPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
        <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 text-center max-w-md w-full">
          <div className="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4" />
          <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Loading...</h2>
        </div>
      </div>
    }>
      <BookingDetailContent />
    </Suspense>
  );
}
