'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, Loader2, Check, ChevronDown, ChevronUp, MapPin } from 'lucide-react';
import { format } from 'date-fns';
import { useState } from 'react';

export default function ResultsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const setSelectedSchedule = useBookingStore((s) => s.setSelectedSchedule);
  const [selectedClasses, setSelectedClasses] = useState<Record<string, string>>({});
  const [expandedSchedules, setExpandedSchedules] = useState<Record<string, boolean>>({});

  const searchData = {
    originStationId: searchParams.get('origin') || '',
    destinationStationId: searchParams.get('destination') || '',
    date: searchParams.get('date') || '',
    adultCount: parseInt(searchParams.get('adults') || '1'),
    childCount: parseInt(searchParams.get('children') || '0'),
    nationality: searchParams.get('nationality') || 'ETHIOPIAN',
  };

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

  const { data: results, isLoading, error } = useQuery<Schedule[]>({
    queryKey: ['search', searchData],
    queryFn: async (): Promise<Schedule[]> => {
      console.log('Searching with criteria:', searchData);
      const response = await apiClient.post('/search', searchData) as Schedule[];
      console.log('Search results:', response);
      console.log('Number of results:', response?.length || 0);
      return response;
    },
    enabled: !!searchData.originStationId && !!searchData.destinationStationId,
  });

  const toggleExpanded = (scheduleId: string) => {
    setExpandedSchedules(prev => ({
      ...prev,
      [scheduleId]: !prev[scheduleId]
    }));
  };

  const handleSelectClass = (scheduleId: string, seatClass: string) => {
    setSelectedClasses(prev => ({
      ...prev,
      [scheduleId]: seatClass
    }));
  };

  const handleSelect = (schedule: Schedule) => {
    const scheduleId = schedule.scheduleId || schedule.id || '';
    const selectedClass = selectedClasses[scheduleId];
    
    if (!selectedClass) {
      alert('Please select a seat class before continuing');
      return;
    }

    const selectedClassFare = schedule.faresByClass?.find(
      (f: any) => f.seatClassName === selectedClass
    );
    
    if (!selectedClassFare) {
      alert('Unable to find fare for selected class');
      return;
    }
    
    const hours = Math.floor((schedule.durationMinutes || 0) / 60);
    const minutes = (schedule.durationMinutes || 0) % 60;
    const durationStr = `${hours}h ${minutes}m`;
    
    setSelectedSchedule({
      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: selectedClassFare.baseFareMinor,
      baseFareChild: selectedClassFare.baseFareMinor,
      selectedSeatClass: selectedClass,
      selectedSeatClassName: selectedClass,
    });
    router.push('/booking/auth-check');
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
          <p className="text-gray-600 dark:text-gray-400 font-medium">Searching for trains...</p>
        </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 (!results || results.length === 0) {
    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. 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-8 md:py-12">
      <div className="container mx-auto px-4">
        <div className="max-w-5xl mx-auto">
          <div className="mb-8">
            <button 
              onClick={() => router.push(buildSearchUrl())} 
              className="btn-ghost mb-4 flex items-center gap-2"
            >
              <ChevronLeft className="w-4 h-4" />
              Modify Search
            </button>
            <h1 className="section-title">Available Trains</h1>
            <div className="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>
            </div>
          </div>

          <div className="space-y-4">
            {results.map((schedule) => {
              const scheduleId = schedule.scheduleId || schedule.id || '';
              const isExpanded = expandedSchedules[scheduleId];
              const selectedClass = selectedClasses[scheduleId];
              
              const lowestFare = schedule.faresByClass && Array.isArray(schedule.faresByClass) && schedule.faresByClass.length > 0
                ? Math.min(...schedule.faresByClass.map((f: any) => f.baseFareMinor).filter((fare: number) => fare > 0))
                : null;
              
              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 group">
                <div className="flex flex-col gap-6">
                  <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-primary-100 dark:bg-primary-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>
                            <div className="absolute right-0 top-1/2 -translate-y-1/2 w-2 h-2 bg-primary rounded-full"></div>
                          </div>
                          <div className="flex items-center gap-2 mt-2 text-sm text-gray-600 dark:text-gray-400">
                            {schedule.stops && schedule.stops.length > 0 && (
                              <>
                                <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-600 dark:text-orange-400 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 dark:text-white">
                          {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>
                        <button
                          onClick={() => toggleExpanded(scheduleId)}
                          className="btn-secondary w-full flex items-center justify-center gap-2"
                        >
                          <span>View Classes</span>
                          {isExpanded ? (
                            <ChevronUp className="w-4 h-4" />
                          ) : (
                            <ChevronDown className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>
                  </div>

                  {isExpanded && (
                    <div className="mt-6 pt-6 border-t dark:border-gray-700">
                      <h4 className="font-semibold text-gray-900 dark:text-gray-100 mb-3">Select Seat Class</h4>
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                        {schedule.faresByClass && Array.isArray(schedule.faresByClass) && schedule.faresByClass.length > 0 ? (
                          schedule.faresByClass.map((fareClass: any) => {
                            const isSelected = selectedClass === fareClass.seatClassName;
                            const availableSeats = schedule.availabilityByClass?.[fareClass.seatClassName] || 0;
                            const isAvailable = availableSeats > 0;
                            
                            return (
                              <button
                                key={fareClass.seatClassName}
                                onClick={() => isAvailable && handleSelectClass(scheduleId, fareClass.seatClassName)}
                                disabled={!isAvailable}
                                className={`relative p-4 rounded-lg border-2 text-left transition-all ${
                                  isSelected
                                    ? 'border-primary bg-primary-50 dark:bg-primary-900/20 shadow-md'
                                    : isAvailable
                                    ? 'border-gray-200 dark:border-gray-700 hover:border-primary-300 hover:shadow-sm'
                                    : 'border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-800 opacity-60 cursor-not-allowed'
                                }`}
                              >
                                {isSelected && (
                                  <div className="absolute top-2 right-2 w-6 h-6 bg-primary rounded-full flex items-center justify-center">
                                    <Check className="w-4 h-4 text-white" />
                                  </div>
                                )}
                                <div className="font-semibold text-gray-900 dark:text-gray-100 mb-1">
                                  {fareClass.seatClassName.replace(/_/g, ' ')}
                                </div>
                                <div className="text-2xl font-bold text-primary dark:text-white mb-1">
                                  ETB {((fareClass.baseFareMinor || 0) / 100).toFixed(2)}
                                </div>
                                <div className="text-xs text-gray-600 dark:text-gray-400">
                                  {isAvailable ? (
                                    <span className="text-green-600 dark:text-green-400 font-medium">
                                      {availableSeats} seat{availableSeats !== 1 ? 's' : ''} available
                                    </span>
                                  ) : (
                                    <span className="text-red-600 dark:text-red-400 font-medium">Sold out</span>
                                  )}
                                </div>
                              </button>
                            );
                          })
                        ) : (
                          <div className="col-span-3 text-center py-4 text-gray-500 dark:text-gray-400">
                            No seat classes available
                          </div>
                        )}
                      </div>
                      
                      <div className="mt-4 flex justify-end">
                        <button 
                          onClick={() => handleSelect(schedule)} 
                          disabled={!selectedClass}
                          className={`btn-primary flex items-center justify-center gap-2 ${
                            !selectedClass
                              ? 'opacity-50 cursor-not-allowed'
                              : 'group-hover:shadow-xl'
                          }`}
                        >
                          <span>Continue</span>
                          <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )})}
          </div>
        </div>
      </div>
    </div>
  );
}
