'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRouter, useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { useBookingStore } from '@/lib/booking-store';
import { Station } from '@/types';
import { Train, MapPin, Calendar, ArrowRight, ArrowLeftRight, Plus, Minus, Search } from 'lucide-react';
import { useEffect } from 'react';
import ModernDatePicker from '@/components/ModernDatePicker';

const searchSchema = z.object({
  originStationId: z.string().min(1, 'Please select origin station'),
  destinationStationId: z.string().min(1, 'Please select destination station'),
  departureDate: z.string().min(1, 'Please select departure date'),
  adultCount: z.number().min(1).max(9),
  childCount: z.number().min(0).max(9),
  nationality: z.enum(['ETHIOPIAN', 'DJIBOUTIAN', 'OTHER']),
}).refine((data) => data.originStationId !== data.destinationStationId, {
  message: 'Origin and destination must be different',
  path: ['destinationStationId'],
});

type SearchForm = z.infer<typeof searchSchema>;

export default function SearchPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const setSearchCriteria = useBookingStore((s) => s.setSearchCriteria);

  const { data: stations, isLoading, error } = useQuery<Station[]>({
    queryKey: ['stations'],
    queryFn: async (): Promise<Station[]> => {
      const response = await apiClient.get('/stations') as Station[];
      return response;
    },
  });

  const { register, handleSubmit, watch, setValue, formState: { errors } } = useForm<SearchForm>({
    resolver: zodResolver(searchSchema),
    defaultValues: {
      adultCount: 1,
      childCount: 0,
      nationality: 'ETHIOPIAN',
      departureDate: new Date().toISOString().split('T')[0],
    },
  });

  // Restore previous search values from URL params
  useEffect(() => {
    const origin = searchParams.get('origin');
    const destination = searchParams.get('destination');
    const date = searchParams.get('date');
    const adults = searchParams.get('adults');
    const children = searchParams.get('children');
    const nationality = searchParams.get('nationality');

    if (origin) setValue('originStationId', origin);
    if (destination) setValue('destinationStationId', destination);
    if (date) setValue('departureDate', date);
    if (adults) setValue('adultCount', parseInt(adults));
    if (children) setValue('childCount', parseInt(children));
    if (nationality) setValue('nationality', nationality as 'ETHIOPIAN' | 'DJIBOUTIAN' | 'OTHER');
  }, [searchParams, setValue]);

  const originId = watch('originStationId');
  const destinationId = watch('destinationStationId');
  const adultCount = watch('adultCount');
  const childCount = watch('childCount');

  const swapStations = () => {
    if (originId && destinationId) {
      const tempOrigin = originId;
      const tempDestination = destinationId;
      setValue('originStationId', tempDestination);
      setValue('destinationStationId', tempOrigin);
    }
  };

  const onSubmit = (data: SearchForm) => {
    setSearchCriteria(data);
    const params = new URLSearchParams({
      origin: data.originStationId,
      destination: data.destinationStationId,
      date: data.departureDate,
      adults: data.adultCount.toString(),
      children: data.childCount.toString(),
      nationality: data.nationality,
    });
    router.push(`/booking/results?${params}`);
  };

  const getStationByName = (name: string) => {
    if (!stations) return null;
    const exactMatch = stations.find(s => s.name.toLowerCase() === name.toLowerCase());
    if (exactMatch) return exactMatch;
    return stations.find(s => s.name.toLowerCase().includes(name.toLowerCase()));
  };

  const handlePopularRoute = (fromName: string, toName: string) => {
    const origin = getStationByName(fromName);
    const destination = getStationByName(toName);
    
    if (origin && destination) {
      setValue('originStationId', origin.id);
      setValue('destinationStationId', destination.id);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const popularRoutes = [
    { from: 'Sebeta', to: 'Nagad', duration: '12h' },
    { from: 'Sebeta', to: 'Diredawa', duration: '8h' },
    { from: 'Diredawa', to: 'Nagad', duration: '4h' },
  ];

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* Search Section */}
      <div className="container mx-auto px-4 py-8 md:py-12">
        <div className="max-w-5xl mx-auto">
          {/* Search Card */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-visible">
            {/* Header inside card */}
            <div className="bg-gradient-to-r from-primary/5 to-primary/10 dark:from-primary/10 dark:to-primary/20 px-6 md:px-8 py-6 border-b border-gray-200 dark:border-gray-700">
              <h1 className="text-2xl md:text-3xl font-bold text-gray-900 dark:text-gray-100">
                Start booking
              </h1>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                Search for available trains and book your journey
              </p>
            </div>
            {error && (
              <div className="bg-red-50 dark:bg-red-900/20 border-l-4 border-red-500 text-red-700 dark:text-red-400 px-6 py-4 flex items-start gap-3">
                <div className="flex-shrink-0 mt-0.5">⚠️</div>
                <div>
                  <p className="font-semibold">Connection Error</p>
                  <p className="text-sm mt-1">Unable to load stations. Please check your connection and try again.</p>
                </div>
              </div>
            )}
            
            <form onSubmit={handleSubmit(onSubmit)} className="p-6 md:p-8">
              <div className="grid md:grid-cols-[1fr_auto_1fr] gap-4 items-end mb-6">
                <div className="space-y-2">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">From</label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />
                    <select 
                      {...register('originStationId')} 
                      className="w-full pl-11 pr-4 py-3.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent disabled:bg-gray-50 dark:disabled:bg-gray-800 disabled:cursor-not-allowed text-base bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                      disabled={isLoading}
                    >
                      <option value="">Select departure station</option>
                      {stations?.map((s) => (
                        <option key={s.id} value={s.id}>{s.name}</option>
                      ))}
                    </select>
                  </div>
                  {errors.originStationId && (
                    <p className="text-red-600 dark:text-red-400 text-sm">{errors.originStationId.message}</p>
                  )}
                </div>

                <button
                  type="button"
                  onClick={swapStations}
                  className="hidden md:flex items-center justify-center w-10 h-10 rounded-full border-2 border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 hover:border-primary transition-all mb-2"
                  title="Swap stations"
                >
                  <ArrowLeftRight className="w-5 h-5 text-gray-600 dark:text-gray-300" />
                </button>

                <div className="space-y-2">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">To</label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />
                    <select 
                      {...register('destinationStationId')} 
                      className="w-full pl-11 pr-4 py-3.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent disabled:bg-gray-50 dark:disabled:bg-gray-800 disabled:cursor-not-allowed text-base bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                      disabled={isLoading}
                    >
                      <option value="">Select arrival station</option>
                      {stations?.map((s) => (
                        <option key={s.id} value={s.id} disabled={s.id === originId}>{s.name}</option>
                      ))}
                    </select>
                  </div>
                  {errors.destinationStationId && (
                    <p className="text-red-600 dark:text-red-400 text-sm">{errors.destinationStationId.message}</p>
                  )}
                </div>
              </div>

              <div className="grid md:grid-cols-2 gap-6 mb-6">
                <div className="space-y-2 relative z-10">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">Departure Date</label>
                  <ModernDatePicker
                    value={watch('departureDate') ? new Date(watch('departureDate') + 'T00:00:00') : undefined}
                    onChange={(date) => {
                      const year = date.getFullYear();
                      const month = String(date.getMonth() + 1).padStart(2, '0');
                      const day = String(date.getDate()).padStart(2, '0');
                      setValue('departureDate', `${year}-${month}-${day}`);
                    }}
                    minDate={new Date()}
                    placeholder="Select departure date"
                  />
                  {errors.departureDate && (
                    <p className="text-red-600 dark:text-red-400 text-sm">{errors.departureDate.message}</p>
                  )}
                </div>

                <div className="space-y-2">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">Passengers</label>
                  <div className="border border-gray-300 dark:border-gray-600 rounded-lg p-3 bg-white dark:bg-gray-700">
                    <div className="flex items-center justify-between mb-3">
                      <div>
                        <div className="text-sm font-medium text-gray-900 dark:text-gray-100">Adults</div>
                        <div className="text-xs text-gray-500 dark:text-gray-400">≥5 years</div>
                      </div>
                      <div className="flex items-center gap-3">
                        <button
                          type="button"
                          onClick={() => {
                            const current = adultCount || 1;
                            if (current > 1) setValue('adultCount', current - 1);
                          }}
                          className="w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 flex items-center justify-center hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50"
                          disabled={(adultCount || 1) <= 1}
                        >
                          <Minus className="w-4 h-4 text-gray-700 dark:text-gray-300" />
                        </button>
                        <span className="w-8 text-center font-semibold text-gray-900 dark:text-gray-100">{adultCount || 1}</span>
                        <button
                          type="button"
                          onClick={() => {
                            const current = adultCount || 1;
                            if (current < 9) setValue('adultCount', current + 1);
                          }}
                          className="w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 flex items-center justify-center hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50"
                          disabled={(adultCount || 1) >= 9}
                        >
                          <Plus className="w-4 h-4 text-gray-700 dark:text-gray-300" />
                        </button>
                      </div>
                    </div>
                    <div className="flex items-center justify-between pt-3 border-t border-gray-200 dark:border-gray-600">
                      <div>
                        <div className="text-sm font-medium text-gray-900 dark:text-gray-100">Children</div>
                        <div className="text-xs text-gray-500 dark:text-gray-400">&lt;5 years • First child free</div>
                      </div>
                      <div className="flex items-center gap-3">
                        <button
                          type="button"
                          onClick={() => {
                            const current = childCount || 0;
                            if (current > 0) setValue('childCount', current - 1);
                          }}
                          className="w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 flex items-center justify-center hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50"
                          disabled={(childCount || 0) <= 0}
                        >
                          <Minus className="w-4 h-4 text-gray-700 dark:text-gray-300" />
                        </button>
                        <span className="w-8 text-center font-semibold text-gray-900 dark:text-gray-100">{childCount || 0}</span>
                        <button
                          type="button"
                          onClick={() => {
                            const current = childCount || 0;
                            if (current < 9) setValue('childCount', current + 1);
                          }}
                          className="w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 flex items-center justify-center hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50"
                          disabled={(childCount || 0) >= 9}
                        >
                          <Plus className="w-4 h-4 text-gray-700 dark:text-gray-300" />
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div className="space-y-2 mb-6">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">Nationality</label>
                <select {...register('nationality')} className="w-full px-4 py-3.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-base bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
                  <option value="ETHIOPIAN">Ethiopian</option>
                  <option value="DJIBOUTIAN">Djiboutian</option>
                  <option value="OTHER">Other</option>
                </select>
              </div>

              <button type="submit" className="w-full bg-primary hover:bg-primary-700 text-white font-semibold py-4 px-6 rounded-lg transition-all duration-200 flex items-center justify-center gap-2 text-lg shadow-lg hover:shadow-xl">
                <Search className="w-5 h-5" />
                <span>Search Trains</span>
              </button>
            </form>
          </div>

          <div className="mt-12">
            <h2 className="text-xl font-bold text-gray-900 dark:text-gray-100 mb-6">Popular Routes</h2>
            <div className="grid md:grid-cols-3 gap-4">
              {popularRoutes.map((route, idx) => (
                <button
                  key={idx}
                  type="button"
                  onClick={() => handlePopularRoute(route.from, route.to)}
                  className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-5 hover:border-primary hover:shadow-md transition-all text-left group"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1">
                      <div className="font-semibold text-gray-900 dark:text-gray-100 mb-1">{route.from}</div>
                      <ArrowRight className="w-4 h-4 text-gray-400 dark:text-gray-500 my-2" />
                      <div className="font-semibold text-gray-900 dark:text-gray-100">{route.to}</div>
                    </div>
                    <Train className="w-5 h-5 text-primary opacity-0 group-hover:opacity-100 transition-opacity" />
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">{route.duration} journey</div>
                </button>
              ))}
            </div>
          </div>

          <div className="mt-12 grid md:grid-cols-3 gap-6">
            <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-6">
              <div className="w-12 h-12 bg-primary-100 dark:bg-primary-900/30 rounded-lg flex items-center justify-center mb-4">
                <Train className="w-6 h-6 text-primary" />
              </div>
              <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-2">Modern Fleet</h3>
              <p className="text-sm text-gray-600 dark:text-gray-400">Comfortable trains with modern amenities</p>
            </div>
            <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-6">
              <div className="w-12 h-12 bg-primary-100 dark:bg-primary-900/30 rounded-lg flex items-center justify-center mb-4">
                <MapPin className="w-6 h-6 text-primary" />
              </div>
              <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-2">21 Stations</h3>
              <p className="text-sm text-gray-600 dark:text-gray-400">Connecting Ethiopia and Djibouti</p>
            </div>
            <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-6">
              <div className="w-12 h-12 bg-primary-100 dark:bg-primary-900/30 rounded-lg flex items-center justify-center mb-4">
                <Calendar className="w-6 h-6 text-primary" />
              </div>
              <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-2">Easy Booking</h3>
              <p className="text-sm text-gray-600 dark:text-gray-400">Book tickets in just a few clicks</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
