'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, passengers, seatHold, setBookingId, setPNR, createAccount, passengerId: storedPassengerId } = useBookingStore();
  const { user, isAuthenticated } = useAuthStore();
  const [timeLeft, setTimeLeft] = useState<string>('');
  const [seatDetails, setSeatDetails] = useState<Record<string, string>>({});

  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 () => {
      if (!selectedSchedule?.id) return;
      
      try {
        const seatMapData: any = await apiClient.get(`/seats/seatmap/${selectedSchedule.id}`);
        const coaches = seatMapData?.coaches || [];
        const allSeats = coaches.flatMap((coach: any) => coach.seats || []);
        
        const details: Record<string, string> = {};
        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, passengers]);

  const createBookingMutation = useMutation({
    mutationFn: (data: any) => {
      const endpoint = isAuthenticated ? '/bookings' : '/bookings/guest';
      return apiClient.post(endpoint, data);
    },
    onSuccess: (data: any) => {
      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.error('Booking creation failed:', error);
      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('Passengers:', passengers);
      
      if (!seatHold?.holdId) {
        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;
      }
      
      let seatClassId = '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;
        }
      } 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.');
        }

        bookingData = {
          scheduleId: selectedSchedule?.id || '',
          holdId: seatHold.holdId,
          originStationId: searchCriteria.originStationId,
          destinationStationId: searchCriteria.destinationStationId,
          seatClassId: seatClassId,
          displayCurrency: 'ETB',
          passengerId: passengerId,
          passengers: passengers.map((p) => {
            const isEthiopian = p.nationality === 'ETHIOPIAN' || p.nationality === 'Ethiopian';
            return {
              seatId: p.seatId || '',
              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,
            };
          }),
        };
      } else {
        // For guests: send full passenger details array
        bookingData = {
          scheduleId: selectedSchedule?.id || '',
          holdId: seatHold.holdId,
          originStationId: searchCriteria.originStationId,
          destinationStationId: searchCriteria.destinationStationId,
          seatClassId: seatClassId,
          displayCurrency: 'ETB',
          passengers: passengers.map(p => {
            const isEthiopian = p.nationality === 'ETHIOPIAN' || p.nationality === 'Ethiopian';
            return {
              seatId: p.seatId || '',
              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,
        };
      }

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

      console.log('Creating booking with payload:', bookingData);
      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 (!selectedSchedule || !passengers.length) {
      if (!createBookingMutation.isPending && !createBookingMutation.isSuccess) {
        console.log('Redirecting to search - missing data');
        router.push('/booking/search');
      }
    }
  }, [selectedSchedule, passengers.length, createBookingMutation.isPending, createBookingMutation.isSuccess, router]);

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

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

  const baseFare = 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">
            <div className="card">
              <h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-gray-100">Trip details</h2>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">Train</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">{selectedSchedule.trainNumber}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">Route</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">{selectedSchedule.origin} → {selectedSchedule.destination}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">Departure</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {selectedSchedule.departureTime ? format(new Date(selectedSchedule.departureTime), 'PPp') : 'N/A'}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">Arrival</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {selectedSchedule.arrivalTime ? format(new Date(selectedSchedule.arrivalTime), 'PPp') : 'N/A'}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">Duration</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">{selectedSchedule.duration}</span>
                </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="flex justify-between items-center border-b border-gray-200 dark:border-gray-700 pb-2 last:border-0">
                    <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 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">
                <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>
  );
}
