import { CheckCircle2, List, Map as MapIcon } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { useTrip } from '@/hooks/useTrip';
import { cn } from '@/lib/utils';

/**
 * SyncedViews Bileşeni
 * Trip Planner'daki Liste (Timeline) ve Harita görünümleri arasındaki senkronizasyonu yönetir.
 * 
 * Özellikler:
 * - activeDayId doğrulaması ve hatalı durumların otomatik düzeltilmesi.
 * - Seçilen yerin (selectedPlaceId) otomatik olarak görünür alana kaydırılması (Scroll to place).
 * - Mobilde Liste/Harita geçişi için tab göstergesi.
 * - Senkronizasyon durumunda görsel geri bildirim.
 */

interface SyncedViewsProps {
  children: React.ReactNode;
  activeTab: 'timeline' | 'map';
  setActiveTab: (tab: 'timeline' | 'map') => void;
  timelineRef: React.RefObject<HTMLDivElement | null>;
  placeRefs: React.RefObject<Map<string, HTMLDivElement>>;
}

export const SyncedViews: React.FC<SyncedViewsProps> = ({
  children,
  activeTab,
  setActiveTab,
  timelineRef,
  placeRefs
}) => {
  const { 
    activeDayId, 
    trip, 
    setActiveDayId, 
    selectedPlaceId,
    newlyAddedPlaceId,
    setHighlightedPlaceId,
    setNewlyAddedPlaceId,
    loading
  } = useTrip();

  const [isSynced, setIsSynced] = useState(false);

  // 1. activeDayId Doğrulaması & Otomatik Düzeltme
  useEffect(() => {
    if (loading || !trip || !trip.days || trip.days.length === 0) return;

    const isValid = trip.days.some(day => day.id === activeDayId);
    
    if (!activeDayId || !isValid) {
      if (import.meta.env.DEV) {
        console.warn('[SyncedViews] Geçersiz activeDayId tespit edildi, ilk güne dönülüyor.');
      }
      setActiveDayId(trip.days[0].id);
    } else {
      // Gün değiştiğinde en üste kaydır
      if (timelineRef.current) {
        const scrollContainer = timelineRef.current.querySelector('[data-radix-scroll-area-viewport]');
        if (scrollContainer) {
          scrollContainer.scrollTo({ top: 0, behavior: 'smooth' });
        }
      }

      // Senkronizasyon başarılı görsel geri bildirimi
      setIsSynced(true);
      const timer = setTimeout(() => setIsSynced(false), 2000);
      return () => clearTimeout(timer);
    }
  }, [activeDayId, trip, setActiveDayId, loading, timelineRef]);

  // 2. Highlight ve Otomatik Kaydırma (Scroll to Place)
  useEffect(() => {
    const targetId = newlyAddedPlaceId || selectedPlaceId;
    if (!targetId || activeTab !== 'timeline') return;

    const scrollToPlace = () => {
      const placeElement = placeRefs.current?.get(targetId);
      
      if (placeElement && timelineRef.current) {
        const scrollContainer = timelineRef.current.querySelector('[data-radix-scroll-area-viewport]');
        
        if (scrollContainer) {
          const containerRect = scrollContainer.getBoundingClientRect();
          const elementRect = placeElement.getBoundingClientRect();
          const scrollTop = scrollContainer.scrollTop;
          
          // Elemanı ekranın ortasına getir
          const targetScroll = scrollTop + elementRect.top - containerRect.top - (containerRect.height / 2) + (elementRect.height / 2);

          scrollContainer.scrollTo({
            top: Math.max(0, targetScroll),
            behavior: 'smooth'
          });

          // Vurgu efekti uygula
          setHighlightedPlaceId(targetId);
          
          if (import.meta.env.DEV) {
            console.debug(`[SyncedViews] ${targetId} ID'li yere kaydırıldı.`);
          }

          // 2 saniye sonra vurguyu kaldır
          const highlightTimer = setTimeout(() => {
            setHighlightedPlaceId(null);
            if (newlyAddedPlaceId) setNewlyAddedPlaceId(null);
          }, 2000);

          return () => clearTimeout(highlightTimer);
        }
      } else {
        // Render gecikmesi durumunda tekrar dene
        const retryTimer = setTimeout(scrollToPlace, 100);
        return () => clearTimeout(retryTimer);
      }
    };

    scrollToPlace();
  }, [selectedPlaceId, newlyAddedPlaceId, activeTab, placeRefs, timelineRef, setHighlightedPlaceId, setNewlyAddedPlaceId]);

  return (
    <div className="flex-1 flex flex-col overflow-hidden relative">
      {/* Senkronizasyon Durum Göstergesi (Opsiyonel/Hafif) */}
      {isSynced && (
        <div className="absolute top-4 left-1/2 -translate-x-1/2 z-40 bg-green-500/90 text-white px-3 py-1 rounded-full text-xs font-medium flex items-center gap-1.5 shadow-sm animate-in fade-in zoom-in duration-300 pointer-events-none">
          <CheckCircle2 className="h-3.5 w-3.5" />
          <span>Senkronize Edildi</span>
        </div>
      )}

      {/* Görünüm Değiştirici (Mobilde Alt Bar - Sadece md altı ekranlarda) */}
      <div className="md:hidden fixed bottom-[calc(1.5rem+env(safe-area-inset-bottom,0px))] left-1/2 -translate-x-1/2 z-[100] bg-white dark:bg-zinc-900 border-2 border-primary/30 rounded-full p-1 shadow-2xl flex items-center gap-0.5 w-[calc(100%-48px)] max-w-[280px]">
        <Button
          variant={activeTab === 'timeline' ? 'default' : 'ghost'}
          size="sm"
          className={cn(
            "flex-1 rounded-full h-11 px-4 flex items-center justify-center gap-2 transition-all",
            activeTab === 'timeline' 
              ? "bg-primary text-white shadow-md font-bold" 
              : "text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 font-semibold"
          )}
          onClick={() => setActiveTab('timeline')}
        >
          <List className="h-5 w-5 shrink-0" />
          <span className="text-sm">Zaman Tüneli</span>
        </Button>
        <Button
          variant={activeTab === 'map' ? 'default' : 'ghost'}
          size="sm"
          className={cn(
            "flex-1 rounded-full h-11 px-4 flex items-center justify-center gap-2 transition-all",
            activeTab === 'map' 
              ? "bg-primary text-white shadow-md font-bold" 
              : "text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 font-semibold"
          )}
          onClick={() => setActiveTab('map')}
        >
          <MapIcon className="h-5 w-5 shrink-0" />
          <span className="text-sm">Harita</span>
        </Button>
      </div>

      {children}
    </div>
  );
};
