import React, { useState } from 'react';
import { MapTilerMap } from '@/components/TripPlanner/Map/MapTilerMap';
import { TimelineView } from './TimelineView';
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 { tripPlaceToPlace } from '@/utils/place-adapter';
import { 
  Sheet, 
  SheetContent, 
  SheetHeader, 
  SheetTitle, 
  SheetTrigger 
} from "@/components/ui/sheet";
import { Button } from '@/components/ui/button';
import { Calendar, Plus } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { Trip, TripDay, TripPlace, TimelineBlock } from '@/types/trip-ui';
import type { AISuggestion, TourRecommendation } from '@/types';
import type { SensorDescriptor, DragStartEvent, DragEndEvent } 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;
}

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

interface TripPlannerMobileProps {
  activeTab: 'timeline' | 'map';
  setActiveTab: (tab: 'timeline' | 'map') => void;
  timelineProps: TimelineViewProps;
  mapProps: MapViewProps;
}

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

export const TripPlannerMobile: React.FC<TripPlannerMobileProps> = ({
  activeTab,
  setActiveTab,
  timelineProps,
  mapProps,
}) => {
  // Use store directly
  const trip = useTripStore(state => state.trip);
  const activeDayId = useTripStore(state => state.activeDayId);
  const setActiveDayId = useTripStore(state => state.setActiveDayId);
  const activeDay = useActiveDay();
  const { allPOIs } = useRouteStore();
  
  const [isDayDrawerOpen, setIsDayDrawerOpen] = useState(false);

  // 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
  );

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

  return (
    // ✅ Mobile only (<md), full height flex container
    <div className="flex md:hidden flex-col flex-1 relative overflow-hidden bg-background">
      {/* Mobile Top Bar */}
      <div className="h-14 border-b-2 border-border bg-white dark:bg-background flex items-center justify-between px-4 shrink-0">
        <div className="flex items-center gap-2 min-w-0">
          <div className="flex flex-col">
            <span className="font-bold text-sm text-foreground">Gün {activeDay?.dayNumber}</span>
            <span className="text-[10px] text-muted-foreground truncate">{activeDay?.date}</span>
          </div>
        </div>
        
        <div className="flex items-center gap-2">
          <Button 
            variant="default" 
            size="sm" 
            className="h-9 px-4 gap-2 rounded-full shadow-lg bg-primary hover:bg-primary/90 transition-all active:scale-95 text-white border-none"
            onClick={timelineProps.onAddPlaceClick}
          >
            <Plus className="h-4 w-4" />
            <span className="text-xs font-bold">Yer Ekle</span>
          </Button>

          <Sheet open={isDayDrawerOpen} onOpenChange={setIsDayDrawerOpen}>
            <SheetTrigger asChild>
              <Button variant="outline" size="sm" className="h-9 w-9 p-0 rounded-full border-solid border-primary/20 border-[1.25px] text-primary">
                <Calendar className="h-4 w-4" />
              </Button>
            </SheetTrigger>
            <SheetContent side="bottom" className="h-[70vh] rounded-t-[20px] px-0">
              <SheetHeader className="px-6 pb-2">
                <SheetTitle>Seyahat Programı</SheetTitle>
              </SheetHeader>
              <div className="overflow-y-auto px-6 py-4 space-y-2">
                {trip?.days?.map((day: any) => (
                  <button
                    key={day.id}
                    onClick={() => {
                      setActiveDayId(day.id);
                      setIsDayDrawerOpen(false);
                    }}
                    className={cn(
                      "w-full p-4 rounded-xl text-left transition-colors flex items-center justify-between",
                      activeDayId === day.id 
                        ? "bg-primary text-primary-foreground" 
                        : "bg-muted hover:bg-muted/80"
                    )}
                  >
                    <div className="flex flex-col">
                      <span className="font-bold text-base">Gün {day.dayNumber}</span>
                      <span className="text-xs opacity-80">{day.date}</span>
                    </div>
                    {activeDayId === day.id && (
                      <div className="w-2 h-2 rounded-full bg-primary-foreground" />
                    )}
                  </button>
                ))}
              </div>
            </SheetContent>
          </Sheet>
        </div>
      </div>
      {/* ✅ Tab content - Flex-1 to fill space */}
      <div className="flex-1 min-h-0 overflow-hidden">
        {activeTab === 'timeline' ? (
          <div className="w-full h-full flex flex-col">
            {/* Weather Display for Mobile */}
            {trip && (
              <div className="p-4 pb-0 space-y-3">
                <WeatherDisplay 
                  forecasts={forecasts}
                  loading={weatherLoading}
                  error={weatherError || undefined}
                  units="metric"
                />
                <HistoricalWeatherDisplay
                  analyses={historicalAnalyses}
                  loading={historicalLoading}
                  error={historicalError || undefined}
                  units="metric"
                  yearsAnalyzed={5}
                />
              </div>
            )}
            <div className="flex-1 overflow-hidden">
              <TimelineView {...timelineProps} hideSelectors={true} />
            </div>
          </div>
        ) : (
          <div className="w-full h-full relative">
            <MapTilerMap 
              places={mapPlaces} 
              allPOIs={allPOIs}
              onPlaceClick={(place) => timelineProps.onPlaceClick(place.id)}
            />
          </div>
        )}
      </div>
    </div>
  );
};
