import { useCallback, useEffect, useState } from 'react';
import { leadsApi, toursApi, tripPlacesApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';
import { exportMultiPagePDF } from '@/lib/pdf-export';
import { assignTimeBlocks } from '@/lib/time-blocks';
import { analyzeTripPlan, matchDailyTourRuleBased } from '@/lib/tour-matching';
import { useTripStore } from '@/store/useTripStore';
import { detectPersona } from '@/utils/persona-engine';

import type { AITourAnalysis, Tour } from '@/types';

/**
 * Seyahat planlayıcıdaki genel olayları yöneten hook
 */
export const useTripEvents = () => {
  const { toast } = useToast();
  const trip = useTripStore(state => state.trip);
  const activeDayId = useTripStore(state => state.activeDayId);
  const loadTrip = useTripStore(state => state.loadTrip);
  const addPlace = useTripStore(state => state.addPlaceToDay);
  const removePlace = useTripStore(state => state.removePlaceFromDay);
  
  // Tour Recommendation state
  
  // Tour Recommendation state
  const [tourRecommendation, setTourRecommendation] = useState<AITourAnalysis | null>(null);
  const [showTourRecommendation, setShowTourRecommendation] = useState(false);
  const [isTourModalOpen, setIsTourModalOpen] = useState(false);
  const [isAnalyzingTrip, setIsAnalyzingTrip] = useState(false);
  const [savedRecommendationId, setSavedRecommendationId] = useState<string | null>(null);
  
  // Lead Capture state
  const [isLeadCaptureOpen, setIsLeadCaptureOpen] = useState(false);
  const [selectedTourForLead, setSelectedTourForLead] = useState<Tour | null>(null);

  // Route Optimization state
  const [isOptimizeModalOpen, setIsOptimizeModalOpen] = useState(false);
  const [optimizationResult, setOptimizationResult] = useState<any>(null);
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [isApplyingOptimization, setIsApplyingOptimization] = useState(false);

  // Banner state
  const [showContextualBanner, setShowContextualBanner] = useState(false);
  const [bannerDismissed, setBannerDismissed] = useState(false);

  // Delete Place Confirmation state
  const [placeToDelete, setPlaceToDelete] = useState<{ id: string, name: string } | null>(null);

  // Lead fields
  const [leadEmail, setLeadEmail] = useState('');
  const [leadWhatsApp, setLeadWhatsApp] = useState('');
  const [leadCountryCode, setLeadCountryCode] = useState('+90');
  const [leadCountry, setLeadCountry] = useState('tr');
  const [leadConsent, setLeadConsent] = useState(false);
  const [isCreatingLead, setIsCreatingLead] = useState(false);

  const analyzeTripForTourRecommendation = useCallback(async (tripData: any, dayId: string | null) => {
    try {
      const totalDays = tripData.days?.length || 0;
      const totalPlaces = tripData.days?.reduce((sum: number, day: any) => sum + (day.places?.length || 0), 0) || 0;

      if (totalDays < 1 || totalPlaces < 2) return;

      // 1. Önce lokal eşleştirmeyi dene (Red/Green/Blue Tour)
      const localAnalysis = analyzeTripPlan(tripData);
      
      // Eğer spesifik bir gün seçiliyse sadece o günü analiz et
      let activeLocalAnalysis = localAnalysis;
      if (dayId) {
        const dayIndex = tripData.days.findIndex((d: any) => d.id === dayId);
        if (dayIndex !== -1) {
          activeLocalAnalysis = {
            ...localAnalysis,
            placesByDay: [localAnalysis.placesByDay[dayIndex]]
          };
        }
      }

      const localMatch = matchDailyTourRuleBased(activeLocalAnalysis);

      if (localMatch) {
        setTourRecommendation({
          recommend: true,
          reason: localMatch.reasoning,
          recommended_type: 'daily_tour',
          ideal_duration: '7-8 saat',
          best_time: '09:30',
          why_better_than_self: localMatch.why_better,
          confidence: localMatch.confidence,
          comparison_metrics: {
            distance_saved_km: Math.round(localMatch.efficiency_gain_percent * 0.5),
            time_saved_hours: 2,
            logistics_removed: ['Araç kiralama', 'Müze biletleri', 'Öğle yemeği planı'],
            expert_value: ['Profesyonel rehber', 'Tarihi anlatım', 'Gizli noktalar'],
          },
          traveler_profile: {
            group_type: 'friends',
            pace: 'balanced',
            budget_level: 'mid',
          },
          display_metadata: {
            service_type_label: 'Günlük Tur',
            segment_message: 'Bu günü bireysel gezmek yerine profesyonel destek almak daha mantıklı olabilir.',
          },
          daily_tour_slug: localMatch.daily_tour_slug,
        } as any);
        setShowTourRecommendation(true);
        return;
      }

      // 2. Lokal eşleşme yoksa Edge Function'a git
      setIsAnalyzingTrip(true);
      const tripHasBalloon = tripData.has_balloon || false;

      const analysisData = {
        destination: tripData.destination,
        days: tripData.days.map((day: any) => ({
          date: day.date,
          places: day.places.map((place: any) => ({
            name: place.name,
            type: place.type,
            lat: place.position?.lat,
            lng: place.position?.lng,
            duration: place.duration,
          })),
        })),
        startPoint: 'hotel',
        travelers: tripData.travelers || 2,
        interests: tripData.interests || [],
        tripHasBalloon,
      };

      const analysis = await toursApi.analyzeTripForTour(analysisData);

      if (analysis.recommend && analysis.confidence >= 0.6) {
        setTourRecommendation(analysis);
        setShowTourRecommendation(true);

        if (!savedRecommendationId) {
          const savedRec = await toursApi.saveRecommendation({
            trip_id: tripData.id,
            recommend: analysis.recommend,
            reason: analysis.reason,
            recommended_type: analysis.recommended_type,
            ideal_duration: analysis.ideal_duration,
            best_time: analysis.best_time,
            confidence: analysis.confidence,
            why_better_than_self: analysis.why_better_than_self,
            distance_saved_km: analysis.comparison_metrics?.distance_saved_km,
            time_saved_hours: analysis.comparison_metrics?.time_saved_hours,
            logistics_removed: analysis.comparison_metrics?.logistics_removed,
            expert_value: analysis.comparison_metrics?.expert_value,
            traveler_group_type: analysis.traveler_profile?.group_type,
            traveler_pace: analysis.traveler_profile?.pace,
            traveler_budget_level: analysis.traveler_profile?.budget_level,
            daily_tour_slug: (analysis as any).daily_tour_slug,
          });

          if (savedRec?.id) {
            setSavedRecommendationId(savedRec.id);
          }
        }
      }
    } catch (error) {
      console.error('Tur önerisi analiz hatası:', error);
    } finally {
      setIsAnalyzingTrip(false);
    }
  }, [savedRecommendationId]);

  useEffect(() => {
    if (trip?.id) {
      analyzeTripForTourRecommendation(trip, activeDayId);
    }
  }, [trip?.id, activeDayId, analyzeTripForTourRecommendation]);

  const handleAddPlace = useCallback(async (placeId: string) => {
    if (!activeDayId) {
      toast({
        title: 'Uyarı',
        description: 'Lütfen önce bir gün seçin.',
        variant: 'destructive',
      });
      return;
    }
    await addPlace(placeId, activeDayId);
  }, [activeDayId, addPlace, toast]);

  const handleDeletePlace = useCallback(async (tripPlaceId: string, placeName: string) => {
    setPlaceToDelete({ id: tripPlaceId, name: placeName });
  }, []);

  const confirmDeletePlace = useCallback(async () => {
    if (!placeToDelete) return;
    await removePlace(placeToDelete.id);
    setPlaceToDelete(null);
  }, [placeToDelete, removePlace]);

  const handleOptimizeRoute = useCallback(async () => {
    if (!activeDayId || !trip) return;

    try {
      setIsOptimizing(true);
      toast({
        title: 'Optimizasyon',
        description: 'En verimli rota hesaplanıyor...',
      });

      const activeDay = trip.days.find(d => d.id === activeDayId);
      if (!activeDay || !activeDay.places || activeDay.places.length < 2) {
        toast({
          title: 'Bilgi',
          description: 'Optimizasyon için en az 2 yer gereklidir.',
        });
        setIsOptimizing(false);
        return;
      }

      const input = await tripPlacesApi.getRouteOptimizationInput(activeDayId, activeDay.places, trip);
      const result = await tripPlacesApi.optimizeRoute(input);

      if (result && result.optimizedOrder) {
        setOptimizationResult(result);
        setIsOptimizeModalOpen(true);
      }
    } catch (error: any) {
      console.error('Optimizasyon hatası:', error);
      toast({
        title: 'Hata',
        description: 'Rota optimize edilirken bir hata oluştu.',
        variant: 'destructive',
      });
    } finally {
      setIsOptimizing(false);
    }
  }, [activeDayId, trip, toast]);

  const handleApplyOptimization = useCallback(async () => {
    if (!optimizationResult || !activeDayId || !trip) return;

    setIsApplyingOptimization(true);

    try {
      await tripPlacesApi.applyOptimizedOrder(
        activeDayId,
        optimizationResult.optimizedOrder
      );

      await loadTrip(trip.id);
      setIsOptimizeModalOpen(false);
      setOptimizationResult(null);

      toast({
        title: 'Başarılı',
        description: 'Yeni rota planınıza uygulandı.',
      });
    } catch (error) {
      console.error('Optimizasyon uygulama hatası:', error);
      toast({
        title: 'Hata',
        description: 'Rota uygulanırken bir hata oluştu.',
        variant: 'destructive',
      });
    } finally {
      setIsApplyingOptimization(false);
    }
  }, [optimizationResult, activeDayId, trip, loadTrip, toast]);

  const handleShare = useCallback(async () => {
    if (!trip) return;

    try {
      const shareUrl = window.location.href;
      await navigator.clipboard.writeText(shareUrl);
      
      toast({
        title: 'Başarılı',
        description: 'Plan bağlantısı panoya kopyalandı.',
      });
    } catch (error) {
      console.error('Paylaşım hatası:', error);
      toast({
        title: 'Hata',
        description: 'Bağlantı kopyalanamadı.',
        variant: 'destructive',
      });
    }
  }, [trip, toast]);

  const handleExportPDF = async () => {
    if (!trip) return;

    try {
      toast({
        title: 'PDF Hazırlanıyor',
        description: 'Lütfen bekleyin...',
      });

      const pdfData = {
        title: trip.title || 'Seyahat Planı',
        destination: trip.destination || '',
        start_date: trip.startDate || '',
        end_date: trip.endDate || '',
        days: trip.days?.map((day: any) => {
          const timeBlockMap = assignTimeBlocks(day.places || []);
          return {
            date: day.date,
            places: (day.places || []).map((place: any) => {
              const blockInfo = timeBlockMap.get(place.id);
              return {
                name: place.name,
                type: place.type,
                duration: place.duration || '2 saat',
                startTime: blockInfo?.startTime,
                endTime: blockInfo?.endTime,
                timeBlock: blockInfo?.timeBlock || 'morning',
                latitude: place.latitude,
                longitude: place.longitude,
              };
            }),
          };
        }) || [],
      };

      const filename = `${trip.destination || 'seyahat'}-plan.pdf`;
      await exportMultiPagePDF(pdfData, filename);

      toast({
        title: 'Başarılı',
        description: 'PDF başarıyla indirildi.',
      });
    } catch (error) {
      console.error('PDF dışa aktarma hatası:', error);
      toast({
        title: 'Hata',
        description: 'PDF oluşturulurken bir hata oluştu.',
        variant: 'destructive',
      });
    }
  };

  const handleLeadSubmit = async (contactInfo: {
    email: string;
    whatsapp: string;
    country: string;
    consent_given: boolean;
  }) => {
    if (!trip || !selectedTourForLead) return;

    try {
      const plannedActivities = trip.days?.flatMap((day: any) => 
        day.places?.map((place: any) => ({
          name: place.name,
          type: place.type,
          date: day.date,
          time_block: place.time_block,
        })) || []
      ) || [];

      const allTypes = trip.days?.flatMap((day: any) => 
        day.places?.map((place: any) => String(place.type || '')).filter((t: string) => t) || []
      ) || [];
      const interests = Array.from(new Set(allTypes)) as string[];

      // Detect tourist persona
      const personaResult = detectPersona({
        number_of_travelers: trip.travelers || 2,
        interests,
        planned_activities: plannedActivities,
        start_date: trip.startDate || trip.start_date || '',
        end_date: trip.endDate || trip.end_date || ''
      });

      await leadsApi.create({
        trip_id: trip.id,
        destination: trip.destination || 'Destinasyon belirtilmemiş',
        start_date: trip.startDate || trip.start_date || '',
        end_date: trip.endDate || trip.end_date || '',
        number_of_travelers: trip.travelers || 2,
        interests,
        planned_activities: plannedActivities,
        timeline_snapshot: {
          days: trip.days?.length || 0,
          total_places: trip.days?.reduce((sum: number, day: any) => sum + (day.places?.length || 0), 0) || 0,
          tour_recommendation: tourRecommendation,
        },
        tour_selected_id: selectedTourForLead.id,
        trigger_source: 'ai_route_recommendation',
        tourist_persona: personaResult.persona,
        persona_confidence: personaResult.confidence,
        ...contactInfo,
      });

      toast({
        title: 'Talep Alındı ✅',
        description: `Seyahat profiliniz: ${personaResult.persona.emoji} ${personaResult.persona.label}. Tur sağlayıcısı sizinle en kısa sürede iletişime geçecektir.`,
      });

      setIsLeadCaptureOpen(false);
      setSelectedTourForLead(null);
    } catch (error) {
      console.error('Lead hatası:', error);
      toast({
        title: 'Hata',
        description: 'Talebiniz iletilemedi. Lütfen tekrar deneyin.',
        variant: 'destructive',
      });
    }
  };

  const handleCreateLead = async (triggerSource: 'ai_route_recommendation' | 'contextual_banner' | 'planner_cta' | 'save_modal') => {
    if (!leadConsent || !leadEmail || !leadWhatsApp || !trip) return false;

    try {
      setIsCreatingLead(true);

      const timelineSnapshot = {
        days: trip.days?.map((day: any) => ({
          dayNumber: day.dayNumber,
          date: day.date,
          places: day.places?.map((place: any) => ({
            name: place.name,
            type: place.type,
            duration: place.duration,
          }))
        }))
      };

      const plannedActivities = trip.days?.flatMap((day: any) => 
        day.places?.map((place: any) => ({
          name: place.name,
          type: place.type,
          date: day.date,
          time_block: place.time_block,
        })) || []
      ) || [];

      const allTypes = trip.days?.flatMap((day: any) => 
        day.places?.map((place: any) => String(place.type || '')).filter((t: string) => t) || []
      ) || [];
      const interests = Array.from(new Set(allTypes)) as string[];

      // Detect tourist persona
      const personaResult = detectPersona({
        number_of_travelers: trip.travelers || 2,
        interests,
        planned_activities: plannedActivities,
        start_date: trip.startDate || trip.start_date || '',
        end_date: trip.endDate || trip.end_date || ''
      });

      await leadsApi.create({
        trip_id: trip.id,
        destination: trip.destination || 'Destinasyon belirtilmemiş',
        start_date: trip.startDate || trip.start_date || '',
        end_date: trip.endDate || trip.end_date || '',
        number_of_travelers: trip.travelers || 2,
        interests,
        planned_activities: plannedActivities,
        timeline_snapshot: timelineSnapshot,
        email: leadEmail,
        whatsapp: `${leadCountryCode}${leadWhatsApp}`,
        country: leadCountry,
        consent_given: true,
        trigger_source: triggerSource,
        tourist_persona: personaResult.persona,
        persona_confidence: personaResult.confidence,
      });

      toast({
        title: 'Başarılı',
        description: `Seyahat profiliniz: ${personaResult.persona.emoji} ${personaResult.persona.label}. Planınız kaydedildi, yerel firmalar size özel teklifler gönderecek.`,
      });

      setLeadEmail('');
      setLeadWhatsApp('');
      setLeadConsent(false);
      return true;
    } catch (error: any) {
      console.error('Lead oluşturma hatası:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Bir hata oluştu.',
        variant: 'destructive',
      });
      return false;
    } finally {
      setIsCreatingLead(false);
    }
  };

  return {
    handleAddPlace,
    handleDeletePlace,
    confirmDeletePlace,
    placeToDelete,
    setPlaceToDelete,
    handleOptimizeRoute,
    handleShare,
    tourRecommendation,
    showTourRecommendation,
    setShowTourRecommendation,
    isTourModalOpen,
    setIsTourModalOpen,
    isAnalyzingTrip,
    handleLeadSubmit,
    isLeadCaptureOpen,
    setIsLeadCaptureOpen,
    selectedTourForLead,
    setSelectedTourForLead,
    handleExportPDF,
    isOptimizeModalOpen,
    setIsOptimizeModalOpen,
    optimizationResult,
    isOptimizing,
    isApplyingOptimization,
    handleApplyOptimization,
    handleCreateLead,
    showContextualBanner,
    setShowContextualBanner,
    bannerDismissed,
    setBannerDismissed,
    leadEmail,
    setLeadEmail,
    leadWhatsApp,
    setLeadWhatsApp,
    leadCountryCode,
    setLeadCountryCode,
    leadCountry,
    setLeadCountry,
    leadConsent,
    setLeadConsent,
    isCreatingLead,
  };
};
