'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, X, MapPin, Gift, Train } 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 = useBookingStore((s) => s.setSelectedSchedule);
  const [selectedClasses, setSelectedClasses] = useState<Record<string, string>>({});
  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);

  // Prefer URL params; fall back to persisted store values
  const searchData = {
    originStationId: searchParams.get('origin') || searchCriteria?.originStationId || '',
    destinationStationId: searchParams.get('destination') || searchCriteria?.destinationStationId || '',
    date: searchParams.get('date') || searchCriteria?.departureDate || '',
    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 || '',
  };

  // Sync URL params back into store whenever they are present in the URL
  useEffect(() => {
    if (searchParams.get('origin')) {
      setSearchCriteria({
        originStationId: searchParams.get('origin')!,
        destinationStationId: searchParams.get('destination')!,
        departureDate: searchParams.get('date')!,
        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') || '',
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  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((err) => {
          console.error('Promo validation failed:', err);
        });
    }
  }, [searchData.promoCode]);

  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,
      ...(searchData.promoCode && { promoCode: searchData.promoCode }),
    });
    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);
      if (response?.length > 0) {
        console.log('First schedule availabilityByClass:', response[0].availabilityByClass);
      }
      return response;
    },
    enabled: !!searchData.originStationId && !!searchData.destinationStationId,
  });

  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. <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">

          {/* Class selection modal */}
          {classModal && (() => {
            const scheduleId = classModal.scheduleId || classModal.id || '';
            const selectedClass = selectedClasses[scheduleId];
            return (
              <>
                {/* Backdrop */}
                <div className="fixed inset-0 z-[99] bg-black/50 backdrop-blur-sm" onClick={() => setClassModal(null)} />
                {/* Drawer */}
                <div className="fixed inset-y-0 right-0 z-[100] w-full sm:w-[640px] bg-white dark:bg-gray-900 shadow-2xl flex flex-col"
                  style={{ animation: 'drawer-slide-in 0.25s cubic-bezier(0.32,0.72,0,1)' }}
                >
                    {/* Header */}
                    <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100 dark:border-gray-800 flex-shrink-0">
                      <div>
                        <h2 className="text-base font-bold text-gray-900 dark:text-white">Select Class</h2>
                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 flex items-center gap-1">
                          <Train className="w-3 h-3" />
                          {classModal.trainNumber} · {classModal.origin?.name} → {classModal.destination?.name}
                        </p>
                      </div>
                      <button
                        type="button"
                        onClick={() => setClassModal(null)}
                        className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                      >
                        <X className="w-5 h-5 text-gray-500" />
                      </button>
                    </div>

                    {/* Class grid */}
                    <div className="flex-1 overflow-y-auto p-4">
                      {classModal.faresByClass && Array.isArray(classModal.faresByClass) && classModal.faresByClass.length > 0 ? (
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                          {classModal.faresByClass.map((fareClass: any) => {
                            const isSelected = selectedClass === fareClass.seatClassName;
                            const availableSeats = classModal.availabilityByClass?.[fareClass.seatClassName] || 0;
                            const isAvailable = availableSeats > 0;
                            const isBedClass = fareClass.seatClassName.toLowerCase().includes('bed');
                            return (
                              <button
                                key={fareClass.seatClassName}
                                onClick={() => isAvailable && handleSelectClass(scheduleId, fareClass.seatClassName)}
                                disabled={!isAvailable}
                                className={`relative w-full p-4 rounded-xl border-2 text-left transition-all ${
                                  isSelected
                                    ? 'border-primary bg-primary/5 dark:bg-primary/10 shadow-sm'
                                    : isAvailable
                                    ? 'border-gray-200 dark:border-gray-700 hover:border-primary/50 hover:shadow-sm'
                                    : 'border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-800 opacity-50 cursor-not-allowed'
                                }`}
                              >
                                {isSelected && (
                                  <div className="absolute top-3 right-3 w-6 h-6 bg-primary rounded-full flex items-center justify-center">
                                    <Check className="w-3.5 h-3.5 text-white" />
                                  </div>
                                )}
                                <p className="font-semibold text-gray-900 dark:text-white pr-8">
                                  {fareClass.seatClassName.replace(/_/g, ' ')}
                                </p>
                                <p className="text-xl font-bold text-primary dark:text-white mt-2">
                                  ETB {((fareClass.baseFareMinor || 0) / 100).toFixed(2)}
                                </p>
                                <p className="text-xs text-gray-400 mt-0.5">per adult</p>
                                <p className={`text-xs mt-2 font-medium ${
                                  isAvailable ? 'text-green-600 dark:text-green-400' : 'text-red-500'
                                }`}>
                                  {isAvailable
                                    ? `${availableSeats} ${isBedClass ? 'bed' : 'seat'}${availableSeats !== 1 ? 's' : ''} available`
                                    : 'Sold out'}
                                </p>
                              </button>
                            );
                          })}
                        </div>
                      ) : (
                        <p className="text-center py-8 text-gray-400 text-sm">No seat classes available</p>
                      )}
                    </div>

                    {/* Footer */}
                    <div className="px-5 py-4 border-t border-gray-100 dark:border-gray-800 flex-shrink-0">
                      <button
                        onClick={() => { if (selectedClass) { handleSelect(classModal); setClassModal(null); } }}
                        disabled={!selectedClass}
                        className="w-full flex items-center justify-center gap-2 py-3.5 bg-[rgb(20,113,76)] hover:bg-[rgb(16,89,60)] text-white font-bold text-sm rounded-xl transition-all disabled:opacity-40 disabled:cursor-not-allowed shadow-lg"
                      >
                        <span>Continue</span>
                        <ArrowRight className="w-4 h-4" />
                      </button>
                      {!selectedClass && (
                        <p className="text-center text-xs text-gray-400 mt-2">Please select a class to continue</p>
                      )}
                    </div>
                </div>
                <style>{`@keyframes drawer-slide-in{from{transform:translateX(100%)}to{transform:translateX(0)}}`}</style>
              </>
            );
          })()}

          {/* Promo Notification */}
          {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-4">
            {results.map((schedule) => {
              const scheduleId = schedule.scheduleId || schedule.id || '';
              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">
                  <div className="flex flex-col lg:flex-row lg:items-center gap-6">
                    {/* Train info */}
                    <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>

                    {/* Fare + action */}
                    <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>
                        {selectedClass && (
                          <p className="text-xs text-primary font-semibold mb-2">
                            {selectedClass.replace(/_/g, ' ')} selected
                          </p>
                        )}
                        <button
                          onClick={() => setClassModal(schedule)}
                          className="btn-secondary w-full flex items-center justify-center gap-2"
                        >
                          {selectedClass ? 'Change class' : 'Select class'}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}
