import { arrayMove } from '@dnd-kit/sortable';
import { useCurrentTrip } from '@/contexts/CurrentTripContext';
import { useToast } from '@/hooks/use-toast';
import { useUndoRedo } from '@/hooks/useUndoRedo';
import { SavePlanDialog } from './components/SavePlanDialog';
import { useTripDragDrop } from './hooks/useTripDragDrop';
import { useTripEvents } from './hooks/useTripEvents';
import { useTripPlaces } from './hooks/useTripPlaces';
import { useTripSearch } from './hooks/useTripSearch';
import { TripPlannerDesktop } from './TripPlannerDesktop';
import { TripPlannerMobile } from './TripPlannerMobile';

import { 
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { 
  Calendar, 
  FileDown, 
  MoreHorizontal,
  Redo2, 
  Search, 
  StickyNote, 
  Undo2,
  Share2,
  Settings,
  Download,
  Zap,
  Sparkles
} from 'lucide-react';
import { supabase } from '@/db/supabase';
import { useRouteStore } from '@/store/route-store';

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { OptimizePreviewModal } from '@/components/OptimizePreviewModal';
import { AddPlaceSheet } from '@/components/planner/AddPlaceSheet';
import { LeadCaptureModal } from '@/components/planner/LeadCaptureModal';
import { SyncedViews } from '@/components/planner/SyncedViews';
import TourModal from '@/components/planner/TourModal';
import { ShareDialog } from '@/components/ShareDialog';
import { RouteGeneratorWizard } from '@/components/planner/RouteGeneratorWizard';

// Components
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from '@/components/ui/input';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from '@/components/ui/skeleton';
import { Textarea } from '@/components/ui/textarea';
import { 
  useTripStore, 
  useActiveDay, 
  useActiveDayTimelineBlocks, 
  useActiveDayMapMarkers 
} from '@/store/useTripStore';

const TripPlanner = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { toast } = useToast();
  const { setCurrentTripId } = useCurrentTrip();
  
  // Zustand Store
  const trip = useTripStore(state => state.trip);
  const loading = useTripStore(state => state.loading);
  const activeDayId = useTripStore(state => state.activeDayId);
  const setActiveDayId = useTripStore(state => state.setActiveDayId);
  const hoveredPlaceId = useTripStore(state => state.hoveredPlaceId);
  const selectedPlaceId = useTripStore(state => state.selectedPlaceId);
  const highlightedPlaceId = useTripStore(state => state.highlightedPlaceId);
  const setHoveredPlaceId = useTripStore(state => state.setHoveredPlaceId);
  const setSelectedPlaceId = useTripStore(state => state.setSelectedPlaceId);
  const setHighlightedPlaceId = useTripStore(state => state.setHighlightedPlaceId);
  const setNewlyAddedPlaceId = useTripStore(state => state.setNewlyAddedPlaceId);
  const loadTrip = useTripStore(state => state.loadTrip);
  const updateTripData = useTripStore(state => state.updateTrip);
  const reorderPlacesData = useTripStore(state => state.reorderPlaces);
  const removePlaceFromDay = useTripStore(state => state.removePlaceFromDay);
  const activeTab = useTripStore(state => state.activeTab);
  const setActiveTab = useTripStore(state => state.setActiveTab);
  
  // Computed values from selectors
  const activeDay = useActiveDay();
  const activeDayPlaces = activeDay?.places || [];
  const activeDayMapMarkers = useActiveDayMapMarkers();
  const activeDayTimelineBlocks = useActiveDayTimelineBlocks();

  // Refs
  const placeRefs = useRef<Map<string, HTMLDivElement>>(new Map());
  const timelineScrollRef = useRef<HTMLDivElement>(null);

  const handleReorderPlaces = async (activeId: string, overId: string) => {
    if (!activeDayId || !activeDayPlaces) return;
    
    const oldIndex = activeDayPlaces.findIndex(p => p.tripPlaceId === activeId);
    const newIndex = activeDayPlaces.findIndex(p => p.tripPlaceId === overId);
    
    if (oldIndex !== -1 && newIndex !== -1) {
      const newPlaces = arrayMove(activeDayPlaces, oldIndex, newIndex);
      await reorderPlacesData(activeDayId, newPlaces);
    }
  };

  // Custom Hooks
  // HOOKS: Veri yönetimi, Sürükle-Bırak, Arama ve Olay Yönetimi
  const {
    activeDayPlaces: currentDayPlaces,
    addPlace,
    removePlace: removePlaceItem,
    reorderPlaces: handleReorderPlacesNew,
  } = useTripPlaces();

  const {
    searchQuery,
    setSearchQuery,
    searchResults,
    isSearching,
    isAddPlaceOpen,
    setIsAddPlaceOpen,
    handleSearch,
    aiSuggestions,
    isLoadingAISuggestions,
    showAISuggestions,
    setShowAISuggestions,
    handleGetAISuggestions
  } = useTripSearch();

  const {
    activeId,
    sensors,
    handleDragStart,
    handleDragEnd,
  } = useTripDragDrop();

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

  const [isSavePlanOpen, setIsSavePlanOpen] = useState(false);
  const [showRouteGenerator, setShowRouteGenerator] = useState(false);
  const [globalRemovePlace, setGlobalRemovePlace] = useState<{ id: string, name: string } | null>(null);
  const { setAllPOIs } = useRouteStore();

  useEffect(() => {
    const loadPOIs = async () => {
      try {
        const { data, error } = await supabase
          .from('places')
          .select('*')
          .eq('region', 'Cappadocia')
          .order('rating', { ascending: false });

        if (error) throw error;
        if (data) setAllPOIs(data);
      } catch (error) {
        console.error('POI yükleme hatası:', error);
      }
    };
    loadPOIs();
  }, [setAllPOIs]);

  // useUndoRedo Entegrasyonu: Plan Notları için
  const { 
    state: plannerNotes, 
    setState: setPlannerNotes, 
    undo, 
    redo, 
    canUndo, 
    canRedo,
    reset
  } = useUndoRedo('', { 
    storageKey: trip ? `trip_notes_${trip.id}` : undefined,
    debounceMs: 1000 
  });

  // Trip yüklendiğinde notları LocalStorage'dan tekrar yükle
  useEffect(() => {
    if (trip?.id) {
      const saved = localStorage.getItem(`trip_notes_${trip.id}`);
      if (saved) {
        try {
          reset(JSON.parse(saved));
        } catch (e) {
          reset(saved); // String olarak dene
        }
      }
    }
  }, [trip?.id, reset]);

  // Effects
  useEffect(() => {
    const tripId = searchParams.get('trip_id');
    if (tripId) {
      setCurrentTripId(tripId);
      loadTrip(tripId);
    }
  }, [searchParams, loadTrip, setCurrentTripId]);

  useEffect(() => {
    const placeId = searchParams.get('selectedPlaceId');
    if (placeId) {
      setSelectedPlaceId(placeId);
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('selectedPlaceId');
      navigate(`?${newParams.toString()}`, { replace: true });
    }
  }, [searchParams, navigate, setSelectedPlaceId]);

  useEffect(() => {
    setSelectedPlaceId(null);
    setHoveredPlaceId(null);
    setHighlightedPlaceId(null);
  }, [activeDayId, setSelectedPlaceId, setHoveredPlaceId, setHighlightedPlaceId]);

  // Global functions for Map interactions
  useEffect(() => {
    (window as any).addPOIToRoute = async (poiId: string) => {
      try {
        const { data, error } = await supabase
          .from('places')
          .select('*')
          .eq('id', poiId)
          .single();

        if (error) throw error;
        if (data) {
          // Add to current active day
          if (activeDayId) {
            await addPlace((data as any).id, 'morning'); // Default to morning or user's choice
            toast({
              title: 'Başarılı',
              description: `${(data as any).name} seyahat planına eklendi.`,
            });
          } else {
            toast({
              title: 'Hata',
              description: 'Lütfen önce bir gün seçin.',
              variant: 'destructive',
            });
          }
        }
      } catch (error) {
        console.error('Error adding place to route:', error);
        toast({
          title: 'Hata',
          description: 'Yer eklenirken bir hata oluştu.',
          variant: 'destructive',
        });
      }
    };

    (window as any).removePlaceFromRoute = async (tripPlaceId: string) => {
      try {
        const place = activeDayPlaces?.find(p => p.tripPlaceId === tripPlaceId);
        if (place) {
          setGlobalRemovePlace({ id: tripPlaceId, name: place.name });
        }
      } catch (error) {
        console.error('Error removing place from route:', error);
      }
    };
  }, [activeDayId, activeDayPlaces, addPlace, toast]);

  const confirmGlobalRemove = async () => {
    if (!globalRemovePlace) return;
    try {
      await removePlaceItem(globalRemovePlace.id);
      toast({
        title: 'Başarılı',
        description: `${globalRemovePlace.name} seyahat planından çıkarıldı.`,
      });
    } catch (error) {
      console.error('Error removing place:', error);
    } finally {
      setGlobalRemovePlace(null);
    }
  };

  const handleRouteComplete = async (route: any) => {
    try {
      // Clear current trip places for the days involved? Or just add?
      // For now, let's just toast and log, as full implementation of applying route needs logic to match days.
      console.log('Generated route to apply:', route);
      toast({
        title: 'Rota Hazır',
        description: 'Kişiselleştirilmiş rotanız başarıyla oluşturuldu.',
      });
      setShowRouteGenerator(false);
      // Logic to actually insert generated places into trip days...
    } catch (error) {
      toast({
        title: 'Hata',
        description: 'Rota uygulanırken bir hata oluştu.',
        variant: 'destructive',
      });
    }
  };

  // Handlers
  const handleMarkerClick = useCallback((placeId: string) => {
    setSelectedPlaceId(placeId);
    const placeElement = placeRefs.current.get(placeId);
    if (placeElement) {
      placeElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }, [setSelectedPlaceId]);

  const handleMarkerHover = useCallback((placeId: string | null) => {
    setHoveredPlaceId(placeId);
  }, [setHoveredPlaceId]);

  const handleCreateLeadClick = async () => {
    const success = await handleCreateLead('save_modal');
    if (success) {
      setIsSavePlanOpen(false);
    }
  };

  if (loading) {
    return (
      <div className="flex h-screen bg-background">
        <div className="flex-1 p-6">
          <Skeleton className="h-12 w-64 mb-6" />
          <Skeleton className="h-96 w-full" />
        </div>
      </div>
    );
  }

  if (!trip) {
    return (
      <div className="flex h-screen items-center justify-center bg-background">
        <div className="text-center">
          <h2 className="text-2xl font-bold mb-2">Seyahat bulunamadı</h2>
          <p className="text-muted-foreground">Lütfen geçerli bir seyahat seçin.</p>
        </div>
      </div>
    );
  }

  const timelineProps = {
    trip,
    loading,
    activeDayId,
    setActiveDayId,
    activeDay,
    activeDayPlaces,
    activeDayTimelineBlocks,
    hoveredPlaceId,
    selectedPlaceId,
    highlightedPlaceId,
    onPlaceClick: setSelectedPlaceId,
    onPlaceHover: setHoveredPlaceId,
    onRemovePlace: handleDeletePlace,
    onAddPlaceClick: () => setIsAddPlaceOpen(true),
    onGetAISuggestions: handleGetAISuggestions,
    isLoadingAISuggestions,
    aiSuggestions,
    showAISuggestions,
    setShowAISuggestions,
    onAddAISuggestion: addPlace,
    placeRefs,
    timelineScrollRef,
    sensors,
    handleDragStart,
    handleDragEnd,
    activeId,
    showTourRecommendation,
    tourRecommendation: tourRecommendation as any,
    onViewTours: () => setIsTourModalOpen(true),
    onDismissTourRecommendation: () => setShowTourRecommendation(false),
    onRouteComplete: handleRouteComplete,
  };

  const mapProps = {
    markers: activeDayMapMarkers,
    onMarkerClick: handleMarkerClick,
    onMarkerHover: handleMarkerHover,
    hoveredPlaceId,
    selectedPlaceId,
  };

  return (
    <div className="flex flex-col h-[calc(100vh-64px)] overflow-hidden w-full max-w-full">
      {/* Header */}
      <div className="h-14 border-b-2 border-border bg-white dark:bg-background flex items-center justify-between px-2 sm:px-4 z-20">
        <div className="flex items-center gap-1 sm:gap-4 min-w-0">
          <div className="flex items-center bg-muted/50 rounded-lg p-0.5">
            <Button 
              variant="ghost" 
              size="icon" 
              className="h-8 w-8 shrink-0 text-foreground hover:bg-muted rounded-md"
              onClick={undo}
              disabled={!canUndo}
              title="Geri Al"
            >
              <Undo2 className="h-4 w-4" />
            </Button>
            <Button 
              variant="ghost" 
              size="icon" 
              className="h-8 w-8 shrink-0 text-foreground hover:bg-muted rounded-md"
              onClick={redo}
              disabled={!canRedo}
              title="İleri Al"
            >
              <Redo2 className="h-4 w-4" />
            </Button>
          </div>
          
          <div className="h-4 w-px bg-border mx-1 sm:mx-2 shrink-0 hidden xs:block" />
          <span className="text-sm font-semibold truncate max-w-[120px] sm:max-w-[200px]">{trip.title}</span>
          
          <Popover>
            <PopoverTrigger asChild>
              <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0 text-foreground relative hover:bg-muted">
                <StickyNote className="h-4 w-4" />
                {plannerNotes && (
                  <span className="absolute top-1 right-1 w-2 h-2 bg-primary rounded-full" />
                )}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-80">
              <div className="space-y-4">
                <h4 className="font-medium leading-none">Plan Notları</h4>
                <p className="text-sm text-muted-foreground">
                  Gezinizle ilgili özel notlar alın.
                </p>
                <Textarea 
                  placeholder="Notlarınızı buraya yazın..."
                  value={plannerNotes}
                  onChange={(e) => setPlannerNotes(e.target.value)}
                  className="min-h-[100px]"
                />
              </div>
            </PopoverContent>
          </Popover>
        </div>

        <div className="flex items-center gap-1 sm:gap-2">
          {/* Main Actions - Always Visible */}
          <SavePlanDialog
            open={isSavePlanOpen}
            onOpenChange={setIsSavePlanOpen}
            leadEmail={leadEmail}
            setLeadEmail={setLeadEmail}
            leadWhatsApp={leadWhatsApp}
            setLeadWhatsApp={setLeadWhatsApp}
            leadCountryCode={leadCountryCode}
            setLeadCountryCode={setLeadCountryCode}
            leadCountry={leadCountry}
            setLeadCountry={setLeadCountry}
            leadConsent={leadConsent}
            setLeadConsent={setLeadConsent}
            isCreatingLead={isCreatingLead}
            onSubmit={handleCreateLeadClick}
          />
          
          <ShareDialog trip={trip} onTripUpdate={updateTripData} />

          {/* Delete Place Confirmation Dialog */}
          <AlertDialog open={!!placeToDelete} onOpenChange={(open) => !open && setPlaceToDelete(null)}>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Emin misiniz?</AlertDialogTitle>
                <AlertDialogDescription>
                  &quot;{placeToDelete?.name}&quot; planınızdan kaldırılsın mı?
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>İptal</AlertDialogCancel>
                <AlertDialogAction 
                  onClick={confirmDeletePlace}
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                >
                  Kaldır
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>

          {/* Global Remove Place Confirmation Dialog */}
          <AlertDialog open={!!globalRemovePlace} onOpenChange={(open) => !open && setGlobalRemovePlace(null)}>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Emin misiniz?</AlertDialogTitle>
                <AlertDialogDescription>
                  &quot;{globalRemovePlace?.name}&quot; seyahat planından çıkarılsın mı?
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>İptal</AlertDialogCancel>
                <AlertDialogAction 
                  onClick={confirmGlobalRemove}
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                >
                  Çıkar
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
          
          <Button 
            variant="ghost" 
            size="icon" 
            className="h-9 w-9 text-foreground"
            onClick={handleExportPDF}
            title="PDF İndir"
          >
            <FileDown className="h-4 w-4" />
          </Button>

          {/* Secondary Actions - Collapsed on small screens */}
          <div className="hidden md:flex items-center gap-2">
            <Button 
              variant="outline" 
              size="sm" 
              className="h-9 px-3"
              onClick={() => setShowRouteGenerator(true)}
            >
              <Sparkles className="h-4 w-4 mr-2" />
              AI Route
            </Button>
            <Button 
              variant="outline" 
              size="sm" 
              className="h-9 px-3"
              onClick={handleOptimizeRoute}
            >
              <Zap className="h-4 w-4 mr-2" />
              Optimize
            </Button>
          </div>

          {/* More Menu */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon" className="h-9 w-9 text-foreground">
                <MoreHorizontal className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-56">
              <DropdownMenuLabel>Actions</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => navigate('/explore')}>
                <Search className="mr-2 h-4 w-4" />
                <span>Explore Places</span>
              </DropdownMenuItem>
              <DropdownMenuItem className="md:hidden" onClick={() => setShowRouteGenerator(true)}>
                <Sparkles className="mr-2 h-4 w-4" />
                <span>AI Route Generator</span>
              </DropdownMenuItem>
              <DropdownMenuItem className="md:hidden" onClick={handleOptimizeRoute}>
                <Zap className="mr-2 h-4 w-4" />
                <span>Optimize Route</span>
              </DropdownMenuItem>
              <DropdownMenuItem className="md:hidden" onClick={handleExportPDF}>
                <FileDown className="mr-2 h-4 w-4" />
                <span>Download PDF</span>
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => window.open(window.location.href, '_blank')}>
                <Share2 className="mr-2 h-4 w-4" />
                <span>Open in New Tab</span>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      <SyncedViews
        activeTab={activeTab}
        setActiveTab={setActiveTab}
        timelineRef={timelineScrollRef}
        placeRefs={placeRefs}
      >
        <TripPlannerDesktop 
          timelineProps={timelineProps}
          mapProps={mapProps}
        />
        <TripPlannerMobile 
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          timelineProps={timelineProps}
          mapProps={mapProps}
        />
      </SyncedViews>

      <OptimizePreviewModal
        open={isOptimizeModalOpen}
        onOpenChange={setIsOptimizeModalOpen}
        originalPlaces={activeDayPlaces}
        optimizationResult={optimizationResult}
        onConfirm={handleApplyOptimization}
        isApplying={isApplyingOptimization}
      />

      <TourModal
        open={isTourModalOpen}
        onOpenChange={setIsTourModalOpen}
        analysis={tourRecommendation || {} as any}
        destination={trip.destination}
        placeTypes={[]}
        travelers={trip.travelers || 2}
        onTourSelect={(tour) => {
          setIsTourModalOpen(false);
          setSelectedTourForLead(tour);
          setIsLeadCaptureOpen(true);
        }}
      />

      <LeadCaptureModal
        open={isLeadCaptureOpen}
        onOpenChange={setIsLeadCaptureOpen}
        selectedTour={selectedTourForLead}
        tripData={trip as any}
        onSubmit={handleLeadSubmit}
      />

      <AddPlaceSheet
        dayNumber={activeDay?.dayNumber || 1}
        open={isAddPlaceOpen}
        onOpenChange={setIsAddPlaceOpen}
        searchQuery={searchQuery}
        searchResults={searchResults}
        isSearching={isSearching}
        onSearchChange={setSearchQuery}
        onAddPlace={handleAddPlace}
      />

      {/* Route Generator Modal */}
      <Dialog open={showRouteGenerator} onOpenChange={setShowRouteGenerator}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <RouteGeneratorWizard
            onComplete={(route) => {
              console.log('Generated route:', route);
              // TODO: Integrate route into trip
              setShowRouteGenerator(false);
              toast({
                title: 'Route Generated',
                description: 'Your personalized route has been created!',
              });
            }}
            onCancel={() => setShowRouteGenerator(false)}
          />
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default TripPlanner;
