import React, { useState } from 'react';
import { MapTilerMap } from '@/components/TripPlanner/Map/MapTilerMap';
import AITourRecommendation from '@/components/planner/AITourRecommendation';
import { AISuggestions } from '@/components/planner/AISuggestions';
import { WeatherDisplay } from '@/components/planner/WeatherDisplay';
import { HistoricalWeatherDisplay } from '@/components/planner/HistoricalWeatherDisplay';
import { useWeatherForecast } from './hooks/useWeatherForecast';
import { useHistoricalWeather } from './hooks/useHistoricalWeather';
import { useRouteStore } from '@/store/route-store';
import { RouteGeneratorWizard } from '@/components/planner/RouteGeneratorWizard';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useToast } from '@/hooks/use-toast';

import { cn } from '@/lib/utils';
import { 
  Plus, 
  MapPin, 
  Navigation,
  Sparkles
} from 'lucide-react';
import { 
  DragOverlay,
  DragStartEvent,
  DragEndEvent
} from '@dnd-kit/core';
import { 
  SortableContext, 
  verticalListSortingStrategy 
} from '@dnd-kit/sortable';
import { SortablePlaceItem } from './components/SortablePlaceItem';
import { getTimeBlockLabel } from '@/lib/time-blocks';
import { Button } from '@/components/ui/button';
import type { Trip, TripDay, TripPlace, TimelineBlock } from '@/types/trip-ui';
import type { AISuggestion, TourRecommendation } from '@/types';
import type { SensorDescriptor } from '@dnd-kit/core';

import type { MapMarker } from '@/types/trip-ui';

interface TimelineViewProps {
  trip: Trip;
  loading: boolean;
  activeDayId: string | null;
  setActiveDayId: (id: string) => void;
  activeDay: TripDay | null;
  activeDayPlaces: TripPlace[];
  activeDayTimelineBlocks: TimelineBlock[];
  hoveredPlaceId: string | null;
  selectedPlaceId: string | null;
  highlightedPlaceId: string | null;
  onPlaceClick: (id: string) => void;
  onPlaceHover: (id: string | null) => void;
  onRemovePlace: (id: string, name: string, type?: string) => void;
  onAddPlaceClick: () => void;
  onGetAISuggestions: () => void;
  isLoadingAISuggestions: boolean;
  aiSuggestions: AISuggestion[];
  showAISuggestions: boolean;
  setShowAISuggestions: (show: boolean) => void;
  onAddAISuggestion: (id: string, timeBlock: string) => void;
  placeRefs: React.MutableRefObject<Map<string, HTMLDivElement>>;
  timelineScrollRef: React.RefObject<HTMLDivElement | null>;
  sensors: SensorDescriptor<any>[];
  handleDragStart: (event: DragStartEvent) => void;
  handleDragEnd: (event: DragEndEvent) => void;
  activeId: string | null;
  showTourRecommendation?: boolean;
  tourRecommendation?: any;
  onViewTours?: () => void;
  onDismissTourRecommendation?: () => void;
  onRouteComplete: (route: any) => void;
}

interface MapViewProps {
  markers: MapMarker[];
  onMarkerClick: (id: string) => void;
  onMarkerHover: (id: string | null) => void;
  hoveredPlaceId: string | null;
  selectedPlaceId: string | null;
}

interface TripPlannerDesktopProps {
  timelineProps: TimelineViewProps;
  mapProps: MapViewProps;
}

import { 
  useTripStore, 
  useActiveDay, 
  useActiveDayTimelineBlocks 
} from '@/store/useTripStore';

import { tripPlaceToPlace } from '@/utils/place-adapter';

export const TripPlannerDesktop: React.FC<TripPlannerDesktopProps> = ({ 
  timelineProps, 
  mapProps 
}) => {
  const { toast } = useToast();
  const [showRouteGenerator, setShowRouteGenerator] = useState(false);
  const { allPOIs } = useRouteStore();

  // Use store directly for reactive state
  const trip = useTripStore(state => state.trip);
  const activeDayId = useTripStore(state => state.activeDayId);
  const setActiveDayId = useTripStore(state => state.setActiveDayId);
  const activeDay = useActiveDay();
  const activeDayTimelineBlocks = useActiveDayTimelineBlocks();
  const selectedPlaceId = useTripStore(state => state.selectedPlaceId);
  
  // Weather forecast hook
  const { forecasts, loading: weatherLoading, error: weatherError } = useWeatherForecast(
    trip?.start_lat || null,
    trip?.start_lng || null,
    trip?.startDate || trip?.start_date || null,
    trip?.endDate || trip?.end_date || null,
    !!trip // Only fetch when trip is loaded
  );

  // Historical weather analysis hook
  const { analyses: historicalAnalyses, loading: historicalLoading, error: historicalError } = useHistoricalWeather(
    trip?.start_lat || null,
    trip?.start_lng || null,
    trip?.startDate || trip?.start_date || null,
    trip?.endDate || trip?.end_date || null,
    !!trip // Only fetch when trip is loaded
  );
  
  const { 
    activeDayPlaces,
    onPlaceClick,
    onPlaceHover,
    onRemovePlace,
    onAddPlaceClick,
    onGetAISuggestions,
    isLoadingAISuggestions,
    aiSuggestions,
    showAISuggestions,
    onAddAISuggestion,
    placeRefs,
    sensors,
    handleDragStart,
    handleDragEnd,
    activeId,
    showTourRecommendation,
    tourRecommendation,
    onViewTours,
    onDismissTourRecommendation,
    onRouteComplete,
  } = timelineProps;

  // Map activeDayPlaces to the format expected by MapTilerMap using adapter
  const mapPlaces = (activeDayPlaces || []).map(tripPlaceToPlace) as any[];

  const activeDragPlace = activeDayPlaces?.find((p: any) => p.tripPlaceId === activeId);

  return (
    <div className="hidden md:flex flex-1 overflow-hidden bg-background">
      {/* PANEL 1: DayLine (Left) - 80px */}
      <div className="w-[80px] flex flex-col border-r bg-white dark:bg-background shrink-0 h-full overflow-hidden">
        <div className="p-2 border-b shrink-0 flex items-center justify-center">
          <h2 className="text-sm font-bold">Days</h2>
        </div>
        
        {/* Days Grid */}
        <div className="flex-1 overflow-y-auto p-1.5 space-y-1.5">
          {trip?.days?.map((day: any) => (
            <button
              key={day.id}
              onClick={() => setActiveDayId(day.id)}
              className={cn(
                "w-full p-1.5 rounded-lg text-center transition-all group relative",
                activeDayId === day.id
                  ? "bg-primary text-primary-foreground font-semibold ring-2 ring-primary ring-offset-1"
                  : "bg-muted hover:bg-muted/80 text-muted-foreground"
              )}
            >
              <div className="text-sm">Day {day.dayNumber}</div>
              <div className="text-[9px] opacity-80 truncate">{day.date}</div>
              
              <div className={cn(
                "mt-0.5 text-[9px] rounded-full px-1.5 py-0.5 inline-block",
                activeDayId === day.id ? "bg-white/20" : "bg-black/5 dark:bg-white/10"
              )}>
                {day.places?.length || 0}
              </div>
              
              {/* Tour Suggestion Badge */}
              {day.suggested_tour_slug && (
                <div className="absolute top-1 right-1 w-2 h-2 rounded-full bg-primary border border-white shadow-sm" title="AI Tour Suggestion" />
              )}
            </button>
          ))}
        </div>
      </div>

      {/* PANEL 2: Timeline (Middle) - flex-1 */}
      <div className="flex-1 flex flex-col h-full overflow-hidden bg-background relative border-x">
        {/* Timeline Header */}
        <div className="p-4 border-b flex items-center justify-between bg-white dark:bg-background z-10 shrink-0">
          <div>
            <h3 className="font-semibold text-lg flex items-center gap-2">
              Day {activeDay?.dayNumber} - Timeline
              {activeDay?.suggested_tour_slug && (
                <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full font-normal">
                  ✨ {activeDay.suggested_tour_slug === 'red_tour' ? 'Red Tour' : 
                      activeDay.suggested_tour_slug === 'green_tour' ? 'Green Tour' :
                      activeDay.suggested_tour_slug === 'blue_tour' ? 'Blue Tour' : 'Tour Suggestion'}
                </span>
              )}
            </h3>
            <p className="text-xs text-muted-foreground">
              {activeDayPlaces?.length || 0} places selected
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button 
              variant="outline" 
              size="sm" 
              className="gap-2 text-primary"
              onClick={onGetAISuggestions}
              disabled={isLoadingAISuggestions}
            >
              <Sparkles className="h-4 w-4" />
              AI
            </Button>
            <Button 
              size="sm" 
              className="gap-1"
              onClick={onAddPlaceClick}
            >
              <Plus className="h-4 w-4" />
              Yer Ekle
            </Button>
          </div>
        </div>

        {/* Timeline Content - Scrollable */}
        <div className="flex-1 overflow-y-auto p-6 scroll-smooth">
          {/* Weather Forecast Display */}
          {trip && (
            <div className="space-y-4 mb-6">
              {/* Real-time Forecast (if available) */}
              <WeatherDisplay 
                forecasts={forecasts}
                loading={weatherLoading}
                error={weatherError || undefined}
                units="metric"
              />
              
              {/* Historical Analysis */}
              <HistoricalWeatherDisplay
                analyses={historicalAnalyses}
                loading={historicalLoading}
                error={historicalError || undefined}
                units="metric"
                yearsAnalyzed={5}
              />
            </div>
          )}

          {/* AI Tour Recommendation Banner */}
          {showTourRecommendation && tourRecommendation && (
            <div className="mb-6">
              <AITourRecommendation
                analysis={tourRecommendation}
                travelers={trip?.travelers || 2}
                onViewTours={onViewTours || (() => {})}
                onDismiss={onDismissTourRecommendation || (() => {})}
              />
            </div>
          )}

          {/* START POINT CARD */}
          {trip?.start_location_name && (
            <div className="mb-8 p-4 rounded-xl border bg-muted/30 border-dashed relative">
              <div className="absolute -left-[1.25rem] top-1/2 -translate-y-1/2 w-4 h-4 rounded-full bg-primary/20 border-4 border-background flex items-center justify-center">
                <div className="w-1.5 h-1.5 rounded-full bg-primary" />
              </div>
              <div className="flex items-center gap-2 text-primary mb-1">
                <Navigation className="h-4 w-4" />
                <span className="text-xs font-bold uppercase tracking-wider">Başlangıç Noktası</span>
              </div>
              <div className="font-medium text-sm">{trip.start_location_name}</div>
            </div>
          )}

          {activeDayPlaces && activeDayPlaces.length > 0 ? (
            <>
              <SortableContext 
                items={activeDayPlaces.map((p: any) => p.tripPlaceId)}
                strategy={verticalListSortingStrategy}
              >
                <div className="space-y-8 relative ml-4 border-l-2 border-muted pl-8 pb-8">
                  {activeDayTimelineBlocks?.map((block: any) => (
                    <div key={block.timeBlock} className="relative">
                      {/* Time Block Label */}
                      <div className="absolute -left-[2.75rem] top-0 w-8 h-8 rounded-full bg-background border-2 border-muted flex items-center justify-center">
                         <MapPin className="h-4 w-4 text-muted-foreground" />
                      </div>
                      
                      <div className="mb-4">
                        <h4 className="font-bold text-sm text-primary uppercase tracking-widest pt-1">
                          {getTimeBlockLabel(block.timeBlock)}
                        </h4>
                      </div>

                      {/* Places in this time block */}
                      <div className="space-y-4">
                        {block.places?.map((place: any) => (
                          <SortablePlaceItem 
                            key={place.tripPlaceId}
                            place={place}
                            index={activeDayPlaces.findIndex((p: any) => p.tripPlaceId === place.tripPlaceId)}
                            isActiveDay={selectedPlaceId === place.tripPlaceId}
                            onRemove={onRemovePlace}
                            onHover={onPlaceHover}
                            onClick={onPlaceClick}
                            setRef={(id, el) => {
                              if (el) placeRefs.current.set(id, el);
                            }}
                          />
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </SortableContext>

              <DragOverlay>
                {activeId && activeDragPlace ? (
                  <div className="w-[350px] opacity-80 pointer-events-none scale-105 transition-transform">
                    <SortablePlaceItem 
                      place={activeDragPlace}
                      index={activeDayPlaces.findIndex((p: any) => p.tripPlaceId === activeDragPlace.tripPlaceId)}
                      isActiveDay={true}
                      onRemove={() => {}}
                      onHover={() => {}}
                      onClick={() => {}}
                      setRef={() => {}}
                    />
                  </div>
                ) : null}
              </DragOverlay>
            </>
          ) : (
            <div className="flex flex-col items-center justify-center py-20 text-center text-muted-foreground">
              <div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">
                <MapPin className="h-8 w-8 opacity-20" />
              </div>
              <h3 className="text-lg font-medium text-foreground">Henüz yer eklenmemiş</h3>
              <p className="text-sm max-w-[200px] mt-2 mx-auto">
                Bugün için seyahat planınıza yerler eklemeye başlayın.
              </p>
              <Button 
                onClick={onAddPlaceClick}
                className="mt-6"
                variant="outline"
              >
                + Yer Ekle
              </Button>
            </div>
          )}

          {/* AI SUGGESTIONS SECTION */}
          {showAISuggestions && (
            <div className="mt-8 mb-12">
              <AISuggestions 
                suggestions={aiSuggestions}
                onAddSuggestion={onAddAISuggestion}
                dayNumber={activeDay?.dayNumber || 1}
              />
            </div>
          )}
        </div>
      </div>

      {/* PANEL 3: Map (Right) - 40% */}
      <div className="w-[40%] h-full relative border-l">
        <div className="absolute top-4 left-4 z-10 bg-white/90 dark:bg-background/90 backdrop-blur px-3 py-1.5 rounded-full border shadow-sm flex items-center gap-2">
          <Navigation className="h-4 w-4 text-primary" />
          <span className="text-xs font-semibold">🗺️ Selected Day Route</span>
        </div>
        
        {/* Personalized Route Button */}
        <div className="absolute bottom-4 left-4 z-10">
          <Button 
            className="rounded-full shadow-lg bg-primary text-primary-foreground font-bold"
            size="sm"
            onClick={() => setShowRouteGenerator(true)}
          >
            <Sparkles className="h-4 w-4 mr-2" />
            Generate Personalized Route
          </Button>
        </div>

        <MapTilerMap 
          places={mapPlaces} 
          allPOIs={allPOIs}
          onPlaceClick={(place) => onPlaceClick(place.id)}
        />
      </div>

      {/* Route Generator Wizard Modal */}
      <Dialog open={showRouteGenerator} onOpenChange={setShowRouteGenerator}>
        <DialogContent className="max-w-4xl p-0 overflow-hidden bg-background">
          <DialogHeader className="p-6 border-b">
            <DialogTitle>Personalized Route Generator</DialogTitle>
          </DialogHeader>
          <div className="p-6 max-h-[80vh] overflow-y-auto">
            <RouteGeneratorWizard 
              onComplete={onRouteComplete}
              onCancel={() => setShowRouteGenerator(false)}
            />
          </div>

        </DialogContent>
      </Dialog>
    </div>
  );
};
