'use client';

import { useSearchParams, useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { useBookingStore } from '@/lib/booking-store';
import { Schedule } from '@/types';
import { ArrowRight, Clock, Calendar, Users, ChevronLeft, Check, X, MapPin, Gift, Train, Bed, Armchair, Star } from 'lucide-react';
import { format } from 'date-fns';
import { useState, useEffect } from 'react';

export default function ResultsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { setSelectedSchedule, setOutboundSchedule, setInboundSchedule } = useBookingStore();
  const [selectedCoachTypes, setSelectedCoachTypes] = useState<Record<string, { id: string; code: string; name: string }>>({});
  const [outboundScheduleData, setOutboundScheduleData] = useState<any>(null);
  const [classModal, setClassModal] = useState<Schedule | null>(null);
  const [promoData, setPromoData] = useState<{ code: string; discount: string; message: string } | null>(null);

  const searchCriteria = useBookingStore((s) => s.searchCriteria);
  const setSearchCriteria = useBookingStore((s) => s.setSearchCriteria);

  const searchData = {
    originStationId: searchParams.get('origin') || searchCriteria?.originStationId || '',
    destinationStationId: searchParams.get('destination') || searchCriteria?.destinationStationId || '',
    date: searchParams.get('date') || searchCriteria?.departureDate || '',
    returnDate: searchParams.get('returnDate') || searchCriteria?.returnDate,
    journeyType: searchParams.get('tripType') === 'ROUND_TRIP' ? 'ROUND_TRIP' : 'ONE_WAY',
    adultCount: parseInt(searchParams.get('adults') || '') || searchCriteria?.adultCount || 1,
    childCount: parseInt(searchParams.get('children') || '') || searchCriteria?.childCount || 0,
    nationality: searchParams.get('nationality') || searchCriteria?.nationality || 'ETHIOPIAN',
    promoCode: searchParams.get('promoCode') || searchCriteria?.promoCode || '',
  };

  useEffect(() => {
    if (searchParams.get('origin')) {
      setSearchCriteria({
        tripType: (searchParams.get('tripType') || 'ONE_WAY') as 'ONE_WAY' | 'ROUND_TRIP',
        originStationId: searchParams.get('origin')!,
        destinationStationId: searchParams.get('destination')!,
        departureDate: searchParams.get('date')!,
        returnDate: searchParams.get('returnDate') || undefined,
        adultCount: parseInt(searchParams.get('adults') || '1'),
        childCount: parseInt(searchParams.get('children') || '0'),
        nationality: (searchParams.get('nationality') || 'ETHIOPIAN') as 'ETHIOPIAN' | 'DJIBOUTIAN' | 'OTHER',
        promoCode: searchParams.get('promoCode') || '',
      });
    }
  }, [searchParams, setSearchCriteria]);

  useEffect(() => {
    if (searchData.promoCode) {
      apiClient
        .post('/promos/validate', { code: searchData.promoCode })
        .then((response: any) => {
          if (response.applicable || response.valid) {
            setPromoData({
              code: searchData.promoCode,
              discount: response.message || 'Discount applied',
              message: response.message || 'Promo code applied successfully!',
            });
          }
        })
        .catch(() => {
          // Promo validation failed - silently ignore
        });
    }
  }, [searchData.promoCode]);

  const buildSearchUrl = () => {
    const params = new URLSearchParams({
      tripType: searchData.journeyType,
      origin: searchData.originStationId,
      destination: searchData.destinationStationId,
      date: searchData.date,
      adults: searchData.adultCount.toString(),
      children: searchData.childCount.toString(),
      nationality: searchData.nationality,
      ...(searchData.returnDate && { returnDate: searchData.returnDate }),
      ...(searchData.promoCode && { promoCode: searchData.promoCode }),
    });
    return `/booking/search?${params}`;
  };

  const { data: results, isLoading, error } = useQuery<any>({
    queryKey: ['search', searchData],
    queryFn: async (): Promise<any> => {
      const payload: any = {
        originStationId: searchData.originStationId,
        destinationStationId: searchData.destinationStationId,
        date: searchData.date,
        adultCount: searchData.adultCount,
        childCount: searchData.childCount,
        nationality: searchData.nationality,
        journeyType: searchData.journeyType,
      };
      
      if (searchData.journeyType === 'ROUND_TRIP' && searchData.returnDate) {
        payload.returnDate = searchData.returnDate;
      }
      
      console.log('🚂 Search Request:', JSON.stringify(payload, null, 2));
      
      const response = await apiClient.post('/search', payload) as any;
      
      console.log('✅ Search Response:', JSON.stringify(response, null, 2));
      
      return response;
    },
    enabled: !!searchData.originStationId && !!searchData.destinationStationId,
  });

  const isRoundTrip = searchData.journeyType === 'ROUND_TRIP';
  
  // Handle both response formats:
  // 1. One-way: response can be array of schedules OR object with journeyType and outbound
  // 2. Round-trip: response has journeyType, outbound, inbound properties
  let outboundSchedules: Schedule[] = [];
  let inboundSchedules: Schedule[] = [];
  
  if (results) {
    if (results.journeyType === 'ROUND_TRIP') {
      // Round trip response format
      outboundSchedules = results.outbound || [];
      inboundSchedules = results.inbound || [];
    } else if (results.journeyType === 'ONE_WAY' && results.outbound) {
      // One-way response format with outbound array
      outboundSchedules = results.outbound || [];
    } else if (Array.isArray(results)) {
      // One-way response format (direct array of schedules)
      outboundSchedules = results;
    } else if (results.data && Array.isArray(results.data)) {
      // Fallback: wrapped in data property
      outboundSchedules = results.data;
    }
  }
  
  // For one-way, check if outbound has results
  // For round-trip, check if BOTH outbound and inbound have results
  const hasResults = isRoundTrip 
    ? (outboundSchedules.length > 0 && inboundSchedules.length > 0)
    : outboundSchedules.length > 0;

  const handleSelectCoachType = (scheduleId: string, coachId: string, coachTypeCode: string, coachTypeName: string) => {
    setSelectedCoachTypes(prev => ({ ...prev, [scheduleId]: { id: coachId, code: coachTypeCode, name: coachTypeName } }));
  };

  const handleSelect = (schedule: Schedule, isOutbound: boolean = false) => {
    const scheduleId = schedule.scheduleId || schedule.id || '';
    const selectedCoachType = selectedCoachTypes[scheduleId];
    
    if (!selectedCoachType) {
      alert('Please select a coach type before continuing');
      return;
    }

    // Find the coach type to get pricing info
    const coachType = schedule.coachTypes?.find(ct => ct.coachId === selectedCoachType.id);
    const minFare = coachType?.classes.length ? Math.min(...coachType.classes.map(c => c.baseFareMinor)) : 0;
    
    const hours = Math.floor((schedule.durationMinutes || 0) / 60);
    const minutes = (schedule.durationMinutes || 0) % 60;
    const durationStr = `${hours}h ${minutes}m`;
    
    const scheduleData = {
      id: scheduleId,
      trainNumber: schedule.trainNumber,
      origin: schedule.origin?.name || 'Origin',
      destination: schedule.destination?.name || 'Destination',
      departureTime: schedule.departureAt || schedule.departureTime || '',
      arrivalTime: schedule.arrivalAt || schedule.arrivalTime || '',
      duration: durationStr,
      baseFareAdult: minFare,
      baseFareChild: minFare,
      selectedSeatClass: selectedCoachType.name,
      selectedSeatClassName: selectedCoachType.name,
      selectedCoachId: selectedCoachType.id,
      selectedCoachTypeCode: selectedCoachType.code,
      selectedCoachTypeName: selectedCoachType.name,
    };

    // For round trip, store outbound and wait for inbound selection
    if (isRoundTrip && isOutbound) {
      setOutboundScheduleData(scheduleData);
      setOutboundSchedule(scheduleData);
      setClassModal(null);
      // Scroll to inbound section
      setTimeout(() => {
        const inboundSection = document.getElementById('inbound-section');
        if (inboundSection) {
          inboundSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
      }, 100);
      return;
    }

    // For round trip inbound, proceed with both schedules
    if (isRoundTrip && !isOutbound) {
      setInboundSchedule(scheduleData);
      setSelectedSchedule(outboundScheduleData); // Set primary as outbound
    } else {
      // For one-way
      setSelectedSchedule(scheduleData);
    }
    
    router.push('/booking/auth-check');
  };

  const renderScheduleCard = (schedule: Schedule, isOutbound: boolean = false) => {
    const scheduleId = schedule.scheduleId || schedule.id || '';
    const selectedCoachType = selectedCoachTypes[scheduleId];
    
    // Calculate lowest fare from coach types
    let lowestFare = null;
    if (schedule.coachTypes?.length) {
      const allFares = schedule.coachTypes.flatMap(ct => ct.classes.map(c => c.baseFareMinor)).filter(f => f > 0);
      lowestFare = allFares.length ? Math.min(...allFares) : null;
    } else if (schedule.faresByClass?.length) {
      lowestFare = Math.min(...schedule.faresByClass.map((f: any) => f.baseFareMinor).filter((fare: number) => fare > 0));
    }
    const hours = Math.floor((schedule.durationMinutes || 0) / 60);
    const minutes = (schedule.durationMinutes || 0) % 60;
    const durationStr = `${hours}h ${minutes}m`;
    const departureDate = schedule.departureAt ? new Date(schedule.departureAt) : null;
    const arrivalDate   = schedule.arrivalAt   ? new Date(schedule.arrivalAt)   : null;
    const isNextDay = departureDate && arrivalDate && departureDate.toDateString() !== arrivalDate.toDateString();

    return (
      <div key={scheduleId} className="card">
        <div className="flex flex-col lg:flex-row lg:items-center gap-6">
          <div className="flex-1">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center flex-shrink-0">
                <Clock className="w-5 h-5 text-primary" />
              </div>
              <div>
                <div className="font-bold text-lg text-gray-900 dark:text-gray-100">{schedule.trainNumber}</div>
                <div className="text-sm text-gray-600 dark:text-gray-400">{schedule.trainName || 'Express Service'}</div>
              </div>
            </div>

            <div className="flex items-center gap-4">
              <div className="text-center">
                <div className="text-3xl font-bold text-gray-900 dark:text-gray-100">
                  {schedule.departureAt ? format(new Date(schedule.departureAt), 'HH:mm') : '--:--'}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                  {schedule.departureAt ? format(new Date(schedule.departureAt), 'MMM d') : ''}
                </div>
                <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">{schedule.origin?.name || 'Origin'}</div>
              </div>

              <div className="flex-1 flex flex-col items-center">
                <div className="flex items-center gap-2 mb-2 text-sm text-gray-600 dark:text-gray-400">
                  <Clock className="w-4 h-4" />
                  <span>{durationStr}</span>
                </div>
                <div className="w-full h-0.5 bg-gray-200 dark:bg-gray-700 relative">
                  <div className="absolute left-0 top-1/2 -translate-y-1/2 w-2 h-2 bg-primary rounded-full" />
                  <div className="absolute right-0 top-1/2 -translate-y-1/2 w-2 h-2 bg-primary rounded-full" />
                </div>
                {schedule.stops && schedule.stops.length > 0 && (
                  <div className="flex items-center gap-1 mt-2 text-sm text-gray-600 dark:text-gray-400">
                    <MapPin className="w-4 h-4" />
                    <span>{schedule.stops.length - 2} stops</span>
                  </div>
                )}
              </div>

              <div className="text-center">
                <div className="text-3xl font-bold text-gray-900 dark:text-gray-100">
                  {schedule.arrivalAt ? format(new Date(schedule.arrivalAt), 'HH:mm') : '--:--'}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 flex items-center justify-center gap-1">
                  <span>{schedule.arrivalAt ? format(new Date(schedule.arrivalAt), 'MMM d') : ''}</span>
                  {isNextDay && <span className="text-orange-500 font-medium">(+1)</span>}
                </div>
                <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">{schedule.destination?.name || 'Destination'}</div>
              </div>
            </div>
          </div>

          <div className="lg:border-l dark:border-gray-700 lg:pl-6 lg:min-w-[220px]">
            <div className="text-center lg:text-right">
              <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Starting from</div>
              <div className="text-3xl font-bold text-primary">
                {lowestFare ? `ETB ${(lowestFare / 100).toFixed(2)}` : 'N/A'}
              </div>
              <div className="text-xs text-gray-500 dark:text-gray-400 mt-1 mb-4">per adult</div>
              {selectedCoachType && (
                <p className="text-xs text-primary font-semibold mb-2">
                  {selectedCoachType.name} selected
                </p>
              )}
              <button
                onClick={() => setClassModal({ ...schedule, isOutbound } as any)}
                className="btn-secondary w-full flex items-center justify-center gap-2"
              >
                {selectedCoachType ? 'Change' : 'Select'}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-4 md:py-6">
        <div className="container mx-auto px-4">
          <div className="max-w-6xl mx-auto">
            {/* Progress Header */}
            <div className="mb-8">
              <div className="card p-6">
                <div className="flex items-center gap-4">
                  <div className="relative">
                    <div className="w-12 h-12 rounded-full border-4 border-primary/20 border-t-primary animate-spin" />
                  </div>
                  <div className="flex-1">
                    <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-1">
                      Searching for trains...
                    </h2>
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      Finding the best options for your journey
                    </p>
                  </div>
                </div>
                {/* Progress bar */}
                <div className="mt-4 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                  <div 
                    className="h-full bg-primary rounded-full"
                    style={{
                      animation: 'progressBar 2s ease-in-out infinite',
                    }}
                  />
                </div>
              </div>
            </div>

            {/* Skeleton Cards */}
            <div className="space-y-4">
              {[1, 2, 3].map((i) => (
                <div key={i} className="card animate-pulse">
                  <div className="flex flex-col lg:flex-row lg:items-center gap-6">
                    <div className="flex-1">
                      {/* Train info skeleton */}
                      <div className="flex items-center gap-3 mb-4">
                        <div 
                          className="w-10 h-10 bg-gray-200 dark:bg-gray-700 rounded-lg"
                          style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                        />
                        <div className="flex-1 space-y-2">
                          <div 
                            className="h-5 bg-gray-200 dark:bg-gray-700 rounded w-24"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                          <div 
                            className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-32"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                        </div>
                      </div>

                      {/* Time and route skeleton */}
                      <div className="flex items-center gap-4">
                        <div className="text-center space-y-2">
                          <div 
                            className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-16"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                          <div 
                            className="h-3 bg-gray-200 dark:bg-gray-700 rounded w-12"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                          <div 
                            className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-20"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                        </div>

                        <div className="flex-1 flex flex-col items-center">
                          <div 
                            className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                          <div 
                            className="w-full h-0.5 bg-gray-200 dark:bg-gray-700 relative"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          >
                            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-2 h-2 bg-gray-300 dark:bg-gray-600 rounded-full" />
                            <div className="absolute right-0 top-1/2 -translate-y-1/2 w-2 h-2 bg-gray-300 dark:bg-gray-600 rounded-full" />
                          </div>
                          <div 
                            className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-12 mt-2"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                        </div>

                        <div className="text-center space-y-2">
                          <div 
                            className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-16"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                          <div 
                            className="h-3 bg-gray-200 dark:bg-gray-700 rounded w-12"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                          <div 
                            className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-20"
                            style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                          />
                        </div>
                      </div>
                    </div>

                    <div className="lg:border-l dark:border-gray-700 lg:pl-6 lg:min-w-[220px]">
                      <div className="text-center lg:text-right space-y-3">
                        <div 
                          className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mx-auto lg:ml-auto"
                          style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                        />
                        <div 
                          className="h-10 bg-gray-200 dark:bg-gray-700 rounded w-32 mx-auto lg:ml-auto"
                          style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                        />
                        <div 
                          className="h-3 bg-gray-200 dark:bg-gray-700 rounded w-16 mx-auto lg:ml-auto"
                          style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                        />
                        <div 
                          className="h-10 bg-gray-200 dark:bg-gray-700 rounded w-full"
                          style={{ animation: 'shimmer 1.5s ease-in-out infinite' }}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
        <div className="card max-w-md text-center">
          <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">
            <span className="text-3xl">⚠️</span>
          </div>
          <h2 className="text-xl font-bold mb-2 text-gray-900 dark:text-gray-100">Search Error</h2>
          <p className="text-gray-600 dark:text-gray-400 mb-6">Unable to load results. Please try again.</p>
          <button onClick={() => router.push(buildSearchUrl())} className="btn-primary">
            Back to Search
          </button>
        </div>
      </div>
    );
  }

  if (!hasResults) {
    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-2xl mx-auto">
            <div className="card text-center">
              <div className="w-20 h-20 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-6">
                <Calendar className="w-10 h-10 text-gray-400 dark:text-gray-500" />
              </div>
              <h2 className="text-2xl font-bold mb-3 text-gray-900 dark:text-gray-100">No trains found</h2>
              <p className="text-gray-600 dark:text-gray-400 mb-8">
                We couldn&apos;t find any trains matching your search criteria. <br /> Try adjusting your dates or route.
              </p>
              <button onClick={() => router.push(buildSearchUrl())} className="btn-primary">
                Modify search
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-4 md:py-6">
      <div className="container mx-auto px-4">
        <div className="max-w-6xl mx-auto">

          {classModal && (() => {
            const scheduleId = classModal.scheduleId || classModal.id || '';
            const selectedCoachType = selectedCoachTypes[scheduleId];
            const isOutbound = (classModal as any).isOutbound;
            const coachTypes = classModal.coachTypes || [];
            
            const getCoachIcon = (typeName: string) => {
              const lower = typeName.toLowerCase();
              if (lower.includes('soft') || lower.includes('vip')) return Star;
              if (lower.includes('bed')) return Bed;
              return Armchair;
            };
            
            return (
              <>
                <div className="fixed inset-0 z-[99] bg-black/50 backdrop-blur-sm" onClick={() => setClassModal(null)} />
                <div className="fixed inset-y-0 right-0 z-[100] w-full sm:w-[680px] lg:w-[95vw] xl:w-[90vw] 2xl:w-[85vw] max-w-[1400px] bg-white dark:bg-gray-900 shadow-2xl flex flex-col"
                  style={{ animation: 'drawer-slide-in 0.3s cubic-bezier(0.22,1,0.36,1)' }}
                >
                    <div className="flex items-center justify-between px-6 py-5 border-b border-gray-100 dark:border-gray-800 flex-shrink-0">
                      <div>
                        <h2 className="text-lg font-bold text-gray-900 dark:text-white">Choose Your Coach</h2>
                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1 flex items-center gap-1.5">
                          <Train className="w-3.5 h-3.5" />
                          <span className="font-medium">{classModal.trainNumber}</span>
                          <span className="text-gray-400">·</span>
                          <span>{classModal.origin?.name} → {classModal.destination?.name}</span>
                        </p>
                      </div>
                      <button
                        type="button"
                        onClick={() => setClassModal(null)}
                        className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-all"
                        aria-label="Close"
                      >
                        <X className="w-5 h-5 text-gray-500" />
                      </button>
                    </div>

                    <div className="flex-1 overflow-y-auto px-6 py-4">
                      {coachTypes.length > 0 ? (
                        <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4 pt-2">
                          {coachTypes.map((coachType: any, index: number) => {
                            const isSelected = selectedCoachType?.id === coachType.coachId;
                            const minPrice = coachType.classes.length ? Math.min(...coachType.classes.map((c: any) => c.baseFareMinor)) : 0;
                            const CoachIcon = getCoachIcon(coachType.coachTypeName);
                            
                            return (
                              <button
                                key={coachType.coachId}
                                onClick={() => handleSelectCoachType(scheduleId, coachType.coachId, coachType.coachTypeCode, coachType.coachTypeName)}
                                className={`group relative w-full p-5 rounded-2xl border-2 text-left transition-all duration-200 ${
                                  isSelected
                                    ? 'border-primary bg-gradient-to-br from-primary/8 to-primary/3 dark:from-primary/15 dark:to-primary/5 shadow-lg shadow-primary/20 scale-[1.02]'
                                    : 'border-gray-200 dark:border-gray-700 hover:border-primary/40 hover:shadow-md hover:scale-[1.01] bg-white dark:bg-gray-800/50'
                                }`}
                                style={{ animation: `fade-in-up 0.3s ease-out ${index * 0.1}s both` }}
                              >
                                {isSelected && (
                                  <div className="absolute top-4 right-4 w-7 h-7 bg-primary rounded-full flex items-center justify-center shadow-lg animate-scale-in">
                                    <Check className="w-4 h-4 text-white" strokeWidth={3} />
                                  </div>
                                )}

                                <div className="flex flex-col">
                                  <div className="flex items-start gap-4 pr-2">
                                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0 transition-all ${
                                      isSelected
                                        ? 'bg-primary/15 dark:bg-primary/25 shadow-inner'
                                        : 'bg-gray-100 dark:bg-gray-700 group-hover:bg-primary/10'
                                    }`}>
                                      <CoachIcon className={`w-6 h-6 transition-colors ${
                                        isSelected ? 'text-primary' : 'text-gray-600 dark:text-gray-400 group-hover:text-primary'
                                      }`} />
                                    </div>

                                    <div className="flex-1 min-w-0">
                                      <div className="flex items-start justify-between gap-2 mb-2">
                                        <div>
                                          <h3 className="font-bold text-base text-gray-900 dark:text-white leading-tight">
                                            {coachType.coachTypeName}
                                          </h3>
                                        </div>
                                      </div>

                                      <div className="mt-3">
                                        <div className="flex items-baseline gap-1">
                                          <span className="text-xs text-gray-500 dark:text-gray-400 font-medium">From</span>
                                          <span className={`text-2xl font-bold tracking-tight ${
                                            isSelected ? 'text-primary' : 'text-gray-900 dark:text-white'
                                          }`}>
                                            {(minPrice / 100).toFixed(2)}
                                          </span>
                                          <span className="text-sm font-semibold text-gray-600 dark:text-gray-400">ETB</span>
                                        </div>
                                      </div>
                                    </div>
                                  </div>

                                  {coachType.classes.length > 0 && (
                                    <div className="mt-4 pt-4 border-t border-gray-200/60 dark:border-gray-700/60">
                                      <div className="flex items-center justify-between mb-3">
                                        <p className="text-xs font-bold text-gray-700 dark:text-gray-300 uppercase tracking-wider">
                                          Class Options
                                        </p>
                                        <span className="text-xs text-gray-500 dark:text-gray-400 font-medium">
                                          {coachType.classes.length} available
                                        </span>
                                      </div>
                                      <div className="space-y-2.5">
                                        {coachType.classes.map((cls: any, idx: number) => (
                                          <div 
                                            key={idx} 
                                            className="flex items-center justify-between py-2 px-3 rounded-lg bg-gray-50/80 dark:bg-gray-800/40 hover:bg-gray-100/80 dark:hover:bg-gray-800/60 transition-colors"
                                          >
                                            <div className="flex items-center gap-2.5">
                                              <CoachIcon className="w-3.5 h-3.5 text-gray-500 dark:text-gray-400" />
                                              <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                                {cls.name}
                                              </span>
                                            </div>
                                            <div className="flex items-baseline gap-1">
                                              <span className="text-base font-bold tabular-nums text-gray-900 dark:text-white">
                                                {(cls.baseFareMinor / 100).toFixed(2)}
                                              </span>
                                              <span className="text-xs text-gray-500 dark:text-gray-400 font-medium">
                                                ETB
                                              </span>
                                            </div>
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                  )}
                                </div>
                              </button>
                            );
                          })}
                        </div>
                      ) : (
                        <div className="flex flex-col items-center justify-center py-16 text-center">
                          <div className="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mb-4">
                            <Train className="w-8 h-8 text-gray-400" />
                          </div>
                          <p className="text-gray-500 dark:text-gray-400 text-sm">No coach types available for this journey</p>
                        </div>
                      )}
                    </div>

                    <div className="px-6 py-5 border-t border-gray-100 dark:border-gray-800 flex-shrink-0 bg-gray-50/50 dark:bg-gray-800/30 flex justify-center">
                      <div className="w-full max-w-md">
                        <button
                          onClick={() => { if (selectedCoachType) { handleSelect(classModal, isOutbound); } }}
                          disabled={!selectedCoachType}
                          className="w-full flex items-center justify-center gap-2.5 px-6 py-3.5 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-sm rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-primary/30 disabled:shadow-none hover:shadow-xl hover:scale-[1.02] active:scale-[0.98]"
                        >
                          <span>{isRoundTrip && isOutbound ? 'Continue to Return Journey' : 'Continue to Passenger Details'}</span>
                          <ArrowRight className="w-4 h-4" />
                        </button>
                        {!selectedCoachType && (
                          <p className="text-center text-xs text-gray-500 dark:text-gray-400 mt-3 flex items-center justify-center gap-1">
                            <span className="w-1.5 h-1.5 rounded-full bg-gray-400 animate-pulse" />
                            Select a coach type to continue
                          </p>
                        )}
                      </div>
                    </div>
                </div>
                <style>{`
                  @keyframes drawer-slide-in{from{transform:translateX(100%)}to{transform:translateX(0)}}
                  @keyframes fade-in-up{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}
                  @keyframes scale-in{from{transform:scale(0)}to{transform:scale(1)}}
                `}</style>
              </>
            );
          })()}

          {promoData && (
            <div className="mb-6 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4 flex items-start gap-3">
              <Check className="w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <h3 className="font-semibold text-green-900 dark:text-green-200">Promo code applied!</h3>
                <p className="text-sm text-green-800 dark:text-green-300 mt-1">
                  <span className="font-mono font-bold">{promoData.code}</span> — {promoData.message}
                </p>
              </div>
            </div>
          )}

          <div className="mb-8">
            <button onClick={() => router.push(buildSearchUrl())} className="btn-ghost px-0 py-4 flex items-center gap-2">
              <ChevronLeft className="w-4 h-4" />
              Modify search
            </button>
            <h1 className="section-title">Available schedules</h1>
            <div className="hidden sm:flex flex-wrap items-center gap-4 text-gray-600 dark:text-gray-400 mt-3">
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4" />
                <span>{searchData.date ? format(new Date(searchData.date), 'EEEE, MMMM d, yyyy') : 'Date not specified'}</span>
              </div>
              <div className="flex items-center gap-2">
                <Users className="w-4 h-4" />
                <span>{searchData.adultCount} adult(s), {searchData.childCount} child(ren)</span>
              </div>
              {searchData.promoCode && (
                <div className="flex items-center gap-2 bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-300 px-3 py-1 rounded-full text-sm">
                  <Gift className="w-4 h-4" />
                  <span>{searchData.promoCode}</span>
                </div>
              )}
            </div>
          </div>

          <div className="space-y-8">
            {outboundSchedules.length > 0 && (
              <div>
                {isRoundTrip && (
                  <div className="mb-4">
                    <h2 className="text-xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
                      <ArrowRight className="w-5 h-5 text-primary" />
                      Outbound Journey
                    </h2>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                      {searchData.date ? format(new Date(searchData.date), 'EEEE, MMMM d, yyyy') : ''}
                    </p>
                  </div>
                )}
                <div className="space-y-4">
                  {outboundSchedules.map((schedule: Schedule) => renderScheduleCard(schedule, true))}
                </div>
              </div>
            )}

            {isRoundTrip && inboundSchedules.length > 0 && outboundScheduleData && (
              <div id="inbound-section">
                <div className="mb-4">
                  <h2 className="text-xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
                    <ArrowRight className="w-5 h-5 text-primary rotate-180" />
                    Return Journey
                  </h2>
                  <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    {searchData.returnDate ? format(new Date(searchData.returnDate), 'EEEE, MMMM d, yyyy') : ''}
                  </p>
                </div>
                <div className="space-y-4">
                  {inboundSchedules.map((schedule: Schedule) => renderScheduleCard(schedule))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
