'use client';

import { useRouter } from 'next/navigation';
import { useBookingStore } from '@/lib/booking-store';
import { useAuthStore } from '@/lib/auth-store';
import { useMutation } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { format } from 'date-fns';
import { useState, useEffect } from 'react';

// Helper function to decode JWT token and extract passengerId
function getPassengerIdFromToken(token: string): string | null {
  try {
    if (!token) {
      console.warn('No token provided');
      return null;
    }

    const parts = token.split('.');
    if (parts.length !== 3) {
      console.warn('Invalid token format - expected 3 parts, got', parts.length);
      return null;
    }
    
    // Decode JWT payload with proper base64 padding
    const payload = parts[1];
    const padded = payload + '='.repeat((4 - payload.length % 4) % 4);
    
    let decoded;
    try {
      decoded = JSON.parse(atob(padded));
    } catch (e) {
      console.error('Failed to parse base64:', e);
      return null;
    }
    
    console.log('Decoded JWT payload keys:', Object.keys(decoded));
    console.log('passengerId from JWT:', decoded.passengerId);
    
    if (!decoded.passengerId) {
      console.warn('No passengerId in JWT payload, available keys:', Object.keys(decoded));
      return null;
    }
    
    return decoded.passengerId;
  } catch (error) {
    console.error('Error in getPassengerIdFromToken:', error);
    return null;
  }
}

export default function ReviewPage() {
  const router = useRouter();
  const { selectedSchedule, outboundSchedule, inboundSchedule, passengers, seatHold, setBookingId, setPNR, createAccount, passengerId: storedPassengerId, searchCriteria } = useBookingStore();
  const { user, isAuthenticated } = useAuthStore();
  const [timeLeft, setTimeLeft] = useState<string>('');
  const [seatDetails, setSeatDetails] = useState<Record<string, string>>({});

  const isRoundTrip = searchCriteria?.tripType === 'ROUND_TRIP';

  useEffect(() => {
    if (!seatHold?.expiresAt) return;

    const interval = setInterval(() => {
      const now = new Date().getTime();
      const expiry = new Date(seatHold.expiresAt).getTime();
      const diff = expiry - now;

      if (diff <= 0) {
        setTimeLeft('Expired');
        clearInterval(interval);
      } else {
        const minutes = Math.floor(diff / 60000);
        const seconds = Math.floor((diff % 60000) / 1000);
        setTimeLeft(`${minutes}:${seconds.toString().padStart(2, '0')}`);
      }
    }, 1000);

    return () => clearInterval(interval);
  }, [seatHold]);

  useEffect(() => {
    const fetchSeatDetails = async () => {
      try {
        const details: Record<string, string> = {};
        
        // Fetch outbound seat details
        if (isRoundTrip && outboundSchedule?.id) {
          const outboundSeatMap: any = await apiClient.get(`/seats/seatmap/${outboundSchedule.id}`);
          const outboundCoaches = outboundSeatMap?.coaches || [];
          const outboundSeats = outboundCoaches.flatMap((coach: any) => coach.seats || []);
          
          passengers.forEach(p => {
            if ((p as any).outboundSeatId) {
              const seat = outboundSeats.find((s: any) => s.id === (p as any).outboundSeatId);
              if (seat) {
                details[`outbound-${(p as any).outboundSeatId}`] = seat.number || seat.label || seat.seatNumber || 'N/A';
              }
            }
          });
        }
        
        // Fetch inbound seat details
        if (isRoundTrip && inboundSchedule?.id) {
          const inboundSeatMap: any = await apiClient.get(`/seats/seatmap/${inboundSchedule.id}`);
          const inboundCoaches = inboundSeatMap?.coaches || [];
          const inboundSeats = inboundCoaches.flatMap((coach: any) => coach.seats || []);
          
          passengers.forEach(p => {
            if ((p as any).inboundSeatId) {
              const seat = inboundSeats.find((s: any) => s.id === (p as any).inboundSeatId);
              if (seat) {
                details[`inbound-${(p as any).inboundSeatId}`] = seat.number || seat.label || seat.seatNumber || 'N/A';
              }
            }
          });
        }
        
        // Fetch one-way seat details
        if (!isRoundTrip && selectedSchedule?.id) {
          const seatMapData: any = await apiClient.get(`/seats/seatmap/${selectedSchedule.id}`);
          const coaches = seatMapData?.coaches || [];
          const allSeats = coaches.flatMap((coach: any) => coach.seats || []);
          
          passengers.forEach(p => {
            if (p.seatId) {
              const seat = allSeats.find((s: any) => s.id === p.seatId);
              if (seat) {
                details[p.seatId] = seat.number || seat.label || seat.seatNumber || 'N/A';
              }
            }
          });
        }
        
        setSeatDetails(details);
      } catch (error) {
        console.error('Failed to fetch seat details:', error);
      }
    };
    
    fetchSeatDetails();
  }, [selectedSchedule?.id, outboundSchedule?.id, inboundSchedule?.id, passengers, isRoundTrip]);

  const createBookingMutation = useMutation({
    mutationFn: (data: any) => {
      const endpoint = isAuthenticated ? '/bookings' : '/bookings/guest';
      console.log('=== API REQUEST ===');
      console.log('Endpoint:', endpoint);
      console.log('Request Data:', JSON.stringify(data, null, 2));
      return apiClient.post(endpoint, data);
    },
    onSuccess: (data: any) => {
      console.log('=== API RESPONSE SUCCESS ===');
      console.log('Response Data:', JSON.stringify(data, null, 2));
      console.log('Booking created successfully:', data);
      const bookingIdValue = data.bookingId || data.id;
      const pnrValue = data.pnr || data.bookingReference || data.bookingRef;
      
      console.log('Setting booking ID:', bookingIdValue);
      console.log('Setting PNR:', pnrValue);
      console.log('Booking via endpoint:', isAuthenticated ? '/bookings' : '/bookings/guest');
      
      setBookingId(bookingIdValue);
      setPNR(pnrValue);
      
      const totalAmount = isAuthenticated ? (data.totalMinor || data.totalAmount || 0) : (data.totalMinor || data.totalAmount || 0);
      
      console.log('Total amount:', totalAmount);
      
      setTimeout(() => {
        const currentState = useBookingStore.getState();
        console.log('Current booking store state:', currentState);
        console.log('bookingId:', currentState.bookingId);
        console.log('pnr:', currentState.pnr);
        
        if (totalAmount > 0) {
          console.log('Redirecting to payment page');
          router.push('/booking/payment');
        } else {
          console.log('Redirecting to confirmation page');
          router.push('/booking/confirmation');
        }
      }, 100);
    },
    onError: (error: any) => {
      console.log('=== API RESPONSE ERROR ===');
      console.error('Error Object:', error);
      console.error('Error Response:', error?.response);
      console.error('Error Response Data:', JSON.stringify(error?.response?.data, null, 2));
      console.error('Error Status:', error?.response?.status);
      console.error('Error Message:', error?.message);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to create booking. Please try again.';
      alert(errorMessage);
    },
  });

  const handleConfirm = async () => {
    console.log('handleConfirm called');
    try {
      const { searchCriteria } = useBookingStore.getState();
      
      console.log('Search criteria:', searchCriteria);
      console.log('Seat hold:', seatHold);
      console.log('Selected schedule:', selectedSchedule);
      console.log('Outbound schedule:', outboundSchedule);
      console.log('Inbound schedule:', inboundSchedule);
      console.log('Passengers:', passengers);
      
      if (!seatHold?.holdId && (passengers.some(p => p.seatId) || passengers.some(p => (p as any).outboundSeatId || (p as any).inboundSeatId))) {
        console.error('No seat hold found');
        alert('Please select seats before continuing.');
        router.push('/booking/seats');
        return;
      }
      
      if (!searchCriteria?.originStationId || !searchCriteria?.destinationStationId) {
        console.error('Missing search criteria');
        alert('Missing search criteria. Please start over.');
        router.push('/booking/search');
        return;
      }
      
      // Get seat class ID
      let seatClassId = 'default-seat-class-id';
      let returnSeatClassId = 'default-seat-class-id';
      try {
        const seatClasses: any = await apiClient.get('/seat-classes');
        console.log('Seat classes:', seatClasses);
        if (seatClasses && seatClasses.length > 0) {
          seatClassId = seatClasses[0].id;
          returnSeatClassId = seatClasses[0].id;
        }
      } catch (err) {
        console.error('Failed to fetch seat classes:', err);
      }
      
      let bookingData: any;
      if (isAuthenticated) {
        // For authenticated users: get passengerId from multiple sources
        const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null;
        
        if (!token) {
          console.error('No token in localStorage');
          throw new Error('Authentication token not found. Please log in again.');
        }

        console.log('Token found, length:', token.length);

        let passengerId = getPassengerIdFromToken(token);
        console.log('Extracted passenger ID from JWT token:', passengerId);
        
        // Fallback 1: Use passengerId from booking store
        if (!passengerId && storedPassengerId) {
          passengerId = storedPassengerId;
          console.log('Fallback 1: Using passengerId from booking store:', passengerId);
        }
        
        // Fallback 2: Use passengerId from localStorage
        if (!passengerId && typeof window !== 'undefined') {
          const localStoragePassengerId = localStorage.getItem('booking_passengerId');
          if (localStoragePassengerId) {
            passengerId = localStoragePassengerId;
            console.log('Fallback 2: Using passengerId from localStorage:', passengerId);
          }
        }
        
        // Fallback 3: Use passengerId from user object
        if (!passengerId && user) {
          passengerId = (user as any).passengerId;
          console.log('Fallback 3: Using passengerId from user object:', passengerId);
        }
        
        if (!passengerId) {
          console.error('Failed to extract passengerId');
          console.error('User object:', user);
          console.error('User object keys:', user ? Object.keys(user) : 'null');
          console.error('Stored passengerId from booking store:', storedPassengerId);
          if (typeof window !== 'undefined') {
            console.error('Stored passengerId from localStorage:', localStorage.getItem('booking_passengerId'));
          }
          throw new Error('Passenger ID not found in authentication token. Please log in again.');
        }

        // Build booking request for authenticated users
        bookingData = {
          passengerId: passengerId,
          scheduleId: isRoundTrip ? outboundSchedule?.id : selectedSchedule?.id,
          holdId: seatHold?.holdId || '',
          originStationId: searchCriteria.originStationId,
          destinationStationId: searchCriteria.destinationStationId,
          seatClassId: seatClassId,
          bookingType: isRoundTrip ? 'ROUND_TRIP' : 'ONE_WAY',
          displayCurrency: 'ETB',
          passengers: passengers.map((p) => {
            const isEthiopian = p.nationality === 'ETHIOPIAN' || p.nationality === 'Ethiopian';
            return {
              seatId: isRoundTrip ? (p as any).outboundSeatId : (p.seatId || ''),
              ...(isRoundTrip && { returnSeatId: (p as any).inboundSeatId || '' }),
              passengerName: p.name,
              dateOfBirth: p.dateOfBirth,
              idDocumentType: isEthiopian ? 'NATIONAL_ID' : 'PASSPORT',
              idDocumentNumber: isEthiopian ? (p.nationalId || '') : '',
              passportNumber: !isEthiopian ? (p.passportNumber || '') : '',
              passportCountry: !isEthiopian ? (p.passportCountry || '') : '',
              nationality: p.nationality,
            };
          }),
        };
        
        // Add round trip specific fields
        if (isRoundTrip && inboundSchedule) {
          bookingData.returnScheduleId = inboundSchedule.id;
          bookingData.returnOriginStationId = searchCriteria.destinationStationId;
          bookingData.returnDestinationStationId = searchCriteria.originStationId;
          bookingData.returnHoldId = seatHold?.holdId || ''; // Assuming same hold ID, adjust if needed
          bookingData.returnSeatClassId = returnSeatClassId;
        }
        
        // Add promo code if exists
        if (searchCriteria.promoCode) {
          bookingData.promoCode = searchCriteria.promoCode;
        }
      } else {
        // For guests: send full passenger details array
        bookingData = {
          scheduleId: isRoundTrip ? outboundSchedule?.id : selectedSchedule?.id,
          holdId: seatHold?.holdId || '',
          originStationId: searchCriteria.originStationId,
          destinationStationId: searchCriteria.destinationStationId,
          seatClassId: seatClassId,
          bookingType: isRoundTrip ? 'ROUND_TRIP' : 'ONE_WAY',
          displayCurrency: 'ETB',
          passengers: passengers.map(p => {
            const isEthiopian = p.nationality === 'ETHIOPIAN' || p.nationality === 'Ethiopian';
            return {
              seatId: isRoundTrip ? (p as any).outboundSeatId : (p.seatId || ''),
              ...(isRoundTrip && { returnSeatId: (p as any).inboundSeatId || '' }),
              passengerName: p.name,
              dateOfBirth: p.dateOfBirth,
              idDocumentType: isEthiopian ? 'NATIONAL_ID' : 'PASSPORT',
              idDocumentNumber: isEthiopian ? (p.nationalId || '') : '',
              passportNumber: !isEthiopian ? (p.passportNumber || '') : '',
              passportCountry: !isEthiopian ? (p.passportCountry || '') : '',
              nationality: p.nationality,
              phone: p.phone || '',
              email: p.email || '',
            };
          }),
          createAccount: createAccount || false,
          savePassengerDetails: true,
          deviceId: typeof window !== 'undefined' ? (localStorage.getItem('deviceId') || `device-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`) : undefined,
        };
        
        // Add round trip specific fields
        if (isRoundTrip && inboundSchedule) {
          bookingData.returnScheduleId = inboundSchedule.id;
          bookingData.returnOriginStationId = searchCriteria.destinationStationId;
          bookingData.returnDestinationStationId = searchCriteria.originStationId;
          bookingData.returnHoldId = seatHold?.holdId || ''; // Assuming same hold ID, adjust if needed
          bookingData.returnSeatClassId = returnSeatClassId;
        }
        
        // Add promo code if exists
        if (searchCriteria.promoCode) {
          bookingData.promoCode = searchCriteria.promoCode;
        }
      }

      if (typeof window !== 'undefined' && !isAuthenticated && bookingData.deviceId && !localStorage.getItem('deviceId')) {
        localStorage.setItem('deviceId', bookingData.deviceId);
      }

      console.log('Creating booking with payload:', JSON.stringify(bookingData, null, 2));
      console.log('API endpoint:', isAuthenticated ? '/bookings' : '/bookings/guest');
      await createBookingMutation.mutateAsync(bookingData);
    } catch (error) {
      console.error('Error in handleConfirm:', error);
      alert(error instanceof Error ? error.message : 'An unexpected error occurred. Please try again.');
    }
  };

  useEffect(() => {
    if (isRoundTrip) {
      if (!outboundSchedule || !inboundSchedule || !passengers.length) {
        if (!createBookingMutation.isPending && !createBookingMutation.isSuccess) {
          console.log('Redirecting to search - missing round trip data');
          router.push('/booking/search');
        }
      }
    } else {
      if (!selectedSchedule || !passengers.length) {
        if (!createBookingMutation.isPending && !createBookingMutation.isSuccess) {
          console.log('Redirecting to search - missing data');
          router.push('/booking/search');
        }
      }
    }
  }, [isRoundTrip, selectedSchedule, outboundSchedule, inboundSchedule, passengers.length, createBookingMutation.isPending, createBookingMutation.isSuccess, router]);

  if (isRoundTrip && (!outboundSchedule || !inboundSchedule || !passengers.length)) {
    return null;
  }

  if (!isRoundTrip && (!selectedSchedule || !passengers.length)) {
    return null;
  }

  const displaySchedule = isRoundTrip ? outboundSchedule : selectedSchedule;

  console.log('Selected schedule:', displaySchedule);
  console.log('Base fare adult:', displaySchedule?.baseFareAdult);
  console.log('Passengers:', passengers);

  const outboundBaseFare = isRoundTrip && outboundSchedule ? passengers.reduce((sum) => {
    return sum + (outboundSchedule.baseFareAdult || 0);
  }, 0) : 0;

  const inboundBaseFare = isRoundTrip && inboundSchedule ? passengers.reduce((sum) => {
    return sum + (inboundSchedule.baseFareAdult || 0);
  }, 0) : 0;

  const baseFare = isRoundTrip ? (outboundBaseFare + inboundBaseFare) : passengers.reduce((sum, p, i) => {
    const farePerPassenger = selectedSchedule?.baseFareAdult || 
                             (selectedSchedule as any)?.fareAdult || 
                             (selectedSchedule as any)?.price || 
                             0;
    
    console.log(`Passenger ${i}: ${p.name}, fare = ${farePerPassenger}`);
    
    return sum + farePerPassenger;
  }, 0);

  console.log('Calculated base fare:', baseFare);

  const total = baseFare;

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
      <div className="container mx-auto px-4">
        <div className="max-w-6xl mx-auto">
          <h1 className="text-3xl font-bold mb-6 text-gray-900 dark:text-gray-100">Review your booking</h1>

          {seatHold && (
            <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-6">
              <p className="text-yellow-800 dark:text-yellow-200">
                ⏱️ Your seats will be released in: <span className="font-bold">{timeLeft}</span>
              </p>
            </div>
          )}

          <div className="space-y-6">
            {/* Outbound Trip Details */}
            {isRoundTrip && outboundSchedule && (
              <div className="card overflow-hidden">
                <div className="flex items-center gap-2 mb-6 pb-4 border-b border-gray-100 dark:border-gray-800">
                  <div className="w-2 h-2 bg-primary rounded-full" />
                  <h2 className="text-lg font-bold text-gray-900 dark:text-gray-100">Outbound Journey</h2>
                  <span className="ml-auto text-xs px-2.5 py-1 bg-primary/10 text-primary rounded-full font-semibold">
                    {outboundSchedule.selectedSeatClass?.replace(/_/g, ' ') || 'Standard'}
                  </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">
                        {outboundSchedule.departureTime ? format(new Date(outboundSchedule.departureTime), 'HH:mm') : '--:--'}
                      </div>
                      <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                        {outboundSchedule.departureTime ? format(new Date(outboundSchedule.departureTime), 'EEE, MMM d') : 'N/A'}
                      </div>
                      <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                        {outboundSchedule.origin}
                      </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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                          <span className="font-medium">{outboundSchedule.duration}</span>
                        </div>
                        <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 {outboundSchedule.trainNumber}</span>
                        </div>
                      </div>
                    </div>

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

            {/* Inbound Trip Details */}
            {isRoundTrip && inboundSchedule && (
              <div className="card overflow-hidden">
                <div className="flex items-center gap-2 mb-6 pb-4 border-b border-gray-100 dark:border-gray-800">
                  <div className="w-2 h-2 bg-blue-500 rounded-full" />
                  <h2 className="text-lg font-bold text-gray-900 dark:text-gray-100">Return Journey</h2>
                  <span className="ml-auto text-xs px-2.5 py-1 bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded-full font-semibold">
                    {inboundSchedule.selectedSeatClass?.replace(/_/g, ' ') || 'Standard'}
                  </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-blue-500 bg-white dark:bg-gray-900 z-10" />
                    {/* Vertical line */}
                    <div className="w-0.5 flex-1 bg-gradient-to-b from-blue-500 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">
                        {inboundSchedule.departureTime ? format(new Date(inboundSchedule.departureTime), 'HH:mm') : '--:--'}
                      </div>
                      <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                        {inboundSchedule.departureTime ? format(new Date(inboundSchedule.departureTime), 'EEE, MMM d') : 'N/A'}
                      </div>
                      <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                        {inboundSchedule.origin}
                      </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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                          <span className="font-medium">{inboundSchedule.duration}</span>
                        </div>
                        <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 {inboundSchedule.trainNumber}</span>
                        </div>
                      </div>
                    </div>

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

            {/* One-Way Trip Details */}
            {!isRoundTrip && selectedSchedule && (
              <div className="card overflow-hidden">
                <div className="flex items-center gap-2 mb-6 pb-4 border-b border-gray-100 dark:border-gray-800">
                  <div className="w-2 h-2 bg-primary rounded-full" />
                  <h2 className="text-lg font-bold text-gray-900 dark:text-gray-100">Trip Details</h2>
                  <span className="ml-auto text-xs px-2.5 py-1 bg-primary/10 text-primary rounded-full font-semibold">
                    {selectedSchedule.selectedSeatClass?.replace(/_/g, ' ') || 'Standard'}
                  </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">
                        {selectedSchedule.departureTime ? format(new Date(selectedSchedule.departureTime), 'HH:mm') : '--:--'}
                      </div>
                      <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                        {selectedSchedule.departureTime ? format(new Date(selectedSchedule.departureTime), 'EEE, MMM d') : 'N/A'}
                      </div>
                      <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                        {selectedSchedule.origin}
                      </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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                          <span className="font-medium">{selectedSchedule.duration}</span>
                        </div>
                        <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 {selectedSchedule.trainNumber}</span>
                        </div>
                      </div>
                    </div>

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

            <div className="card">
              <h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-gray-100">Passengers</h2>
              <div className="space-y-3">
                {passengers.map((p, i) => (
                  <div key={i} className="border-b border-gray-200 dark:border-gray-700 pb-3 last:border-0">
                    <div className="flex justify-between items-start mb-2">
                      <div>
                        <p className="font-medium text-gray-900 dark:text-gray-100">{p.name}</p>
                        <p className="text-sm text-gray-600 dark:text-gray-400">
                          {p.dateOfBirth ? format(new Date(p.dateOfBirth), 'PP') : 'N/A'} • {p.nationality}
                        </p>
                      </div>
                    </div>
                    {isRoundTrip ? (
                      <div className="grid grid-cols-2 gap-3 mt-2">
                        <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-2">
                          <p className="text-xs text-gray-500 dark:text-gray-400">Outbound Seat</p>
                          <p className="font-semibold text-sm text-gray-900 dark:text-gray-100">
                            {(p as any).outboundSeatId ? (seatDetails[`outbound-${(p as any).outboundSeatId}`] || 'Loading...') : 'Auto-assign'}
                          </p>
                        </div>
                        <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-2">
                          <p className="text-xs text-gray-500 dark:text-gray-400">Return Seat</p>
                          <p className="font-semibold text-sm text-gray-900 dark:text-gray-100">
                            {(p as any).inboundSeatId ? (seatDetails[`inbound-${(p as any).inboundSeatId}`] || 'Loading...') : 'Auto-assign'}
                          </p>
                        </div>
                      </div>
                    ) : (
                      <div className="text-right">
                        <p className="text-sm text-gray-600 dark:text-gray-400">Seat</p>
                        <p className="font-medium text-gray-900 dark:text-gray-100">{p.seatId ? (seatDetails[p.seatId] || 'Loading...') : 'Auto-assign'}</p>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>

            <div className="card">
              <h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-gray-100">Fare breakdown</h2>
              <div className="space-y-2">
                {isRoundTrip ? (
                  <>
                    <div className="flex justify-between">
                      <span className="text-gray-600 dark:text-gray-400">Outbound fare</span>
                      <span className="text-gray-900 dark:text-gray-100">ETB {(outboundBaseFare / 100).toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600 dark:text-gray-400">Return fare</span>
                      <span className="text-gray-900 dark:text-gray-100">ETB {(inboundBaseFare / 100).toFixed(2)}</span>
                    </div>
                  </>
                ) : (
                  <div className="flex justify-between">
                    <span className="text-gray-600 dark:text-gray-400">Base fare</span>
                    <span className="text-gray-900 dark:text-gray-100">ETB {(baseFare / 100).toFixed(2)}</span>
                  </div>
                )}
                <div className="flex justify-between text-lg font-bold border-t border-gray-200 dark:border-gray-700 pt-2">
                  <span className="text-gray-900 dark:text-gray-100">Total</span>
                  <span className="text-primary dark:text-gray-100">ETB {(total / 100).toFixed(2)}</span>
                </div>
              </div>
            </div>

            <div className="flex gap-4">
              <button onClick={() => router.back()} className="btn-secondary flex-1">
                Back
              </button>
              <button
                onClick={handleConfirm}
                disabled={createBookingMutation.isPending}
                className="btn-primary flex-1"
              >
                {createBookingMutation.isPending ? 'Creating booking...' : `Confirm ${isAuthenticated ? '' : 'and pay'}`}
              </button>
            </div>
            
            {createBookingMutation.isError && (
              <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mt-4">
                <p className="text-red-800 dark:text-red-200 text-sm">
                  ⚠️ {createBookingMutation.error instanceof Error ? createBookingMutation.error.message : 'An error occurred while creating your booking. Please try again.'}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
