import { useCallback, useEffect, useState } from 'react';
import { placesApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';
import { detectFreeTimeBlocks } from '@/lib/time-blocks';
import { useTripStore } from '@/store/useTripStore';

/**
 * Yer arama ve AI önerileri işlemleri için kullanılan hook
 */
export const useTripSearch = () => {
  const { toast } = useToast();
  const trip = useTripStore(state => state.trip);
  const activeDayId = useTripStore(state => state.activeDayId);
  const isAddPlaceOpen = useTripStore(state => state.isAddPlaceOpen);
  const setIsAddPlaceOpen = useTripStore(state => state.setIsAddPlaceOpen);

  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  
  // AI Önerileri state'leri
  const [aiSuggestions, setAiSuggestions] = useState<any[]>([]);
  const [isLoadingAISuggestions, setIsLoadingAISuggestions] = useState(false);
  const [showAISuggestions, setShowAISuggestions] = useState(false);

  // Arama işlemini gerçekleştiren fonksiyon
  const handleSearch = useCallback(async (query: string) => {
    if (!query.trim()) {
      setSearchResults([]);
      return;
    }

    setIsSearching(true);
    try {
      const results = await placesApi.search(query);
      setSearchResults(results);
    } catch (error) {
      console.error('Arama hatası:', error);
      toast({
        title: 'Hata',
        description: 'Yerler aranırken bir hata oluştu.',
        variant: 'destructive',
      });
    } finally {
      setIsSearching(false);
    }
  }, [toast]);

  // Debounced search logic
  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchQuery) {
        handleSearch(searchQuery);
      } else {
        setSearchResults([]);
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [searchQuery, handleSearch]);

  // AI Önerilerini getirme fonksiyonu
  const handleGetAISuggestions = useCallback(async () => {
    if (!trip || !activeDayId) return;

    try {
      setIsLoadingAISuggestions(true);
      setShowAISuggestions(true);

      const activeDay = trip.days.find((d) => d.id === activeDayId);
      if (!activeDay) return;

      const existingPlaces = (activeDay.places || []).map((p) => ({
        placeId: p.id,
        name: p.name,
        lat: p.position?.lat || 0,
        lng: p.position?.lng || 0,
        duration: p.duration || '2 saat',
        order_index: p.order_index || 0,
      }));

      const freeTimeBlocks = detectFreeTimeBlocks(activeDay.places || []);
      const tripHasBalloon = trip.has_balloon || false;

      const { data, error } = await supabase.functions.invoke('suggest-places', {
        body: {
          destination: trip.destination || trip.title,
          dayDate: activeDay.date,
          dayNumber: activeDay.dayNumber || 1,
          existingPlaces,
          freeTimeBlocks,
          interests: trip.interests || [],
          tripHasBalloon,
        },
      });

      if (error) throw error;

      // Suggestions now come with placeId from the Edge Function
      const validSuggestions = (data.suggestions || []).filter((s: any) => s.placeId);
      setAiSuggestions(validSuggestions);

      if (validSuggestions.length === 0) {
        toast({
          title: 'Öneri Bulunamadı',
          description: 'Şu anda öneri bulunamadı. Lütfen manuel olarak yer ekleyin.',
        });
      }
    } catch (error) {
      console.error('AI öneri hatası:', error);
      toast({
        title: 'Hata',
        description: 'AI önerileri alınırken bir hata oluştu.',
        variant: 'destructive',
      });
      setShowAISuggestions(false);
    } finally {
      setIsLoadingAISuggestions(false);
    }
  }, [trip, activeDayId, toast]);

  return {
    searchQuery,
    setSearchQuery,
    searchResults,
    setSearchResults,
    isSearching,
    isAddPlaceOpen,
    setIsAddPlaceOpen,
    handleSearch,
    aiSuggestions,
    isLoadingAISuggestions,
    showAISuggestions,
    setShowAISuggestions,
    handleGetAISuggestions
  };
};
