import { Bookmark, ChevronRight, Filter, MapPin, Search, Star } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { useAuth } from '@/contexts/AuthContext';
import { useCurrentTrip } from '@/contexts/CurrentTripContext';
import { popularDestinations } from '@/data/sampleData';
import { bookmarksApi, placesApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';
import { useTripStore } from '@/store/useTripStore';

interface Place {
  id: string;
  name: string;
  description: string | null;
  type: string | null;
  city: string | null;
  country: string | null;
  rating: number | null;
  image_url: string | null;
  duration: string | null;
}

// Category mapping: Frontend label → Backend type
const CATEGORY_MAPPING: Record<string, string> = {
  'All': 'ALL',
  'Museum': 'museum',
  'Restaurant': 'restaurant',
  'Hotel': 'hotel',
  'Historical': 'historical',
};

const Explore = () => {
  const [places, setPlaces] = useState<Place[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('All');
  const [bookmarkedPlaces, setBookmarkedPlaces] = useState<Set<string>>(new Set());
  const { toast } = useToast();
  const { user } = useAuth();
  const navigate = useNavigate();
  const { activeDayId, setActiveDayId } = useCurrentTrip();

  // useTripStore hooks
  const storeTrip = useTripStore(state => state.trip);
  const loadTrip = useTripStore(state => state.loadTrip);
  const addPlaceToDay = useTripStore(state => state.addPlaceToDay);

  // Only categories with backend equivalents
  const categories = Object.keys(CATEGORY_MAPPING);
  const destinations = popularDestinations;

  useEffect(() => {
    loadPlaces();
    if (user) {
      loadBookmarks();
    }
  }, [user]);

  const loadBookmarks = async () => {
    try {
      const bookmarks = await bookmarksApi.getUserBookmarks();
      const bookmarkedIds = new Set(bookmarks.map(b => b.place_id));
      setBookmarkedPlaces(bookmarkedIds);
    } catch (error) {
      console.error('Error loading bookmarks:', error);
    }
  };

  const handleToggleBookmark = async (placeId: string) => {
    // Giriş kontrolü - kullanıcı giriş yapmamışsa bookmark işlemi engellenir
    if (!user) {
      toast({
        title: 'Giriş Gerekli',
        description: 'Yer işaretlemek için lütfen giriş yapın.',
        variant: 'destructive',
      });
      return;
    }

    try {
      const isBookmarked = bookmarkedPlaces.has(placeId);
      
      if (isBookmarked) {
        // Server-side API çağrısı
        await bookmarksApi.unbookmark(placeId);
        // Yerel state senkronizasyonu
        setBookmarkedPlaces(prev => {
          const newSet = new Set(prev);
          newSet.delete(placeId);
          return newSet;
        });
        toast({
          title: 'Başarılı',
          description: 'Yer işaretlerden kaldırıldı.',
        });
      } else {
        // Server-side API çağrısı
        await bookmarksApi.bookmark(placeId);
        // Yerel state senkronizasyonu
        setBookmarkedPlaces(prev => new Set(prev).add(placeId));
        toast({
          title: 'Başarılı',
          description: 'Yer işaretlendi.',
        });
      }
    } catch (error) {
      console.error('Bookmark error:', error);
      toast({
        title: 'Hata',
        description: 'İşlem başarısız oldu.',
        variant: 'destructive',
      });
    }
  };

  const loadPlaces = async () => {
    try {
      setLoading(true);
      // Tüm yerleri backend'den dinamik olarak yükle (pagination ile)
      const result = await placesApi.getAll();
      setPlaces(result.places);
    } catch (error) {
      console.error('Places loading error:', error);
      toast({
        title: 'Hata',
        description: 'Yerler yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async () => {
    // Arama boşsa tüm yerleri yükle
    if (!searchQuery.trim()) {
      loadPlaces();
      return;
    }

    try {
      setLoading(true);
      // Server-side arama - placesApi.search() kullanılır
      const data = await placesApi.search(searchQuery);
      setPlaces(data);
    } catch (error) {
      console.error('Search error:', error);
      toast({
        title: 'Hata',
        description: 'Arama başarısız oldu.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleCategoryChange = async (category: string) => {
    setSelectedCategory(category);
    setSearchQuery('');
    
    // Get backend type from mapping
    const backendType = CATEGORY_MAPPING[category];
    
    if (backendType === 'ALL') {
      loadPlaces();
      return;
    }

    try {
      setLoading(true);
      // Call API with backend type value (e.g., 'museum', not 'Museum')
      const data = await placesApi.getByType(backendType);
      setPlaces(data);
    } catch (error) {
      console.error('Category filtering error:', error);
    } finally {
      setLoading(false);
    }
  };

  // Add to Trip button handler - useTripStore.addPlaceToDay() ile güncellendi
  const handleAddToTrip = async (place: Place) => {
    try {
      // Kullanıcı kontrolü
      if (!user?.id) {
        toast({
          title: 'Giriş Gerekli',
          description: 'Seyahate yer eklemek için lütfen giriş yapın.',
          variant: 'destructive',
        });
        return;
      }

      // 1. Aktif seyahat kontrolü yap
      const { data: activeTrip, error: tripError } = await (supabase as any)
        .from('trips')
        .select('id, trip_days!trip_days_trip_id_fkey(id, date, order_index)')
        .eq('user_id', user.id)
        .order('created_at', { ascending: false })
        .limit(1)
        .maybeSingle();

      // 2. Aktif seyahat YOKSA → /create-trip'e yönlendir
      if (!activeTrip || tripError) {
        navigate('/create-trip', {
          state: { pendingPlaceId: place.id }
        });
        return;
      }

      const tripId = activeTrip.id;
      
      // 3. Mağazadaki seyahat verisi güncel değilse yükle
      if (!storeTrip || storeTrip.id !== tripId) {
        await loadTrip(tripId);
      }
      
      // 4. Hedef günü belirle
      const tripDays = activeTrip.trip_days;
      let targetDayId = activeDayId;
      
      // Eğer aktif gün yoksa veya bu seyahate ait değilse, ilk günü seç
      if (!targetDayId || !tripDays?.some((day: any) => day.id === targetDayId)) {
        const sortedDays = [...(tripDays || [])].sort(
          (a: any, b: any) => a.order_index - b.order_index
        );
        targetDayId = sortedDays[0]?.id;
        if (targetDayId) {
          setActiveDayId(targetDayId);
        }
      }

      if (!targetDayId) {
        toast({
          title: 'Hata',
          description: 'Hedef gün belirlenemedi.',
          variant: 'destructive',
        });
        return;
      }

      // 5. Aynı yerin bu günde zaten var olup olmadığını kontrol et
      const { data: exists } = await (supabase as any)
        .from('trip_places')
        .select('id')
        .eq('trip_day_id', targetDayId)
        .eq('place_id', place.id)
        .maybeSingle();

      if (exists) {
        toast({
          title: 'Zaten Eklendi',
          description: 'Bu yer bugünün planında zaten mevcut.',
          variant: 'destructive',
        });
        navigate(`/planner?trip_id=${tripId}`);
        return;
      }

      // 6. useTripStore.addPlaceToDay kullanarak yer ekle (Optimistik UI ve Rollback desteği)
      await addPlaceToDay(place.id, targetDayId);

      // 7. Planner sayfasına yönlendir
      navigate(`/planner?trip_id=${tripId}&selectedPlaceId=${place.id}`);
      toast({
        title: 'Başarılı',
        description: `${place.name} seyahatinize eklendi!`,
      });
    } catch (error) {
      console.error('Add to trip error:', error);
      toast({
        title: 'Hata',
        description: 'Yer seyahate eklenirken bir sorun oluştu.',
        variant: 'destructive',
      });
    }
  };

  const filteredPlaces = places;

  return (
    <div className="flex flex-col">
      {/* Hero Search Section */}
      <section className="from-cyan-50 to-teal-50 dark:from-slate-900 dark:to-slate-950 py-20 bg-inherit bg-cover bg-center bg-no-repeat bg-[url(https://miaoda-edit-image.s3cdn.medo.dev/9jd6q07lo4xs/IMG-9jl76jriwr9c.jpg)]">
        <div className="container mx-auto px-4 text-center">
          <h1 className="text-4xl md:text-5xl font-bold mb-8">Discover New Worlds</h1>
          <div className="max-w-2xl mx-auto relative">
            <Search className="absolute left-4 top-4 h-6 w-6 text-muted-foreground" />
            <Input 
              placeholder="Where do you want to go?" 
              className="h-14 pl-12 pr-32 rounded-full shadow-lg border-none bg-white dark:bg-slate-800 text-lg"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            />
            <Button 
              className="absolute right-2 top-2 h-10 rounded-full bg-primary px-6"
              onClick={handleSearch}
            >
              Explore
            </Button>
          </div>
          <div className="flex flex-wrap justify-center gap-2 mt-6">
            <span className="text-sm text-muted-foreground mr-2 self-center">Popular:</span>
            {["London", "Istanbul", "New York", "Dubai", "Bangkok"].map(city => (
              <Badge 
                key={city} 
                variant="outline" 
                className="rounded-full bg-white/50 backdrop-blur cursor-pointer hover:bg-white transition-colors"
                onClick={() => {
                  setSearchQuery(city);
                  // Trigger search immediately when clicking a popular city
                  setTimeout(async () => {
                    try {
                      setLoading(true);
                      const data = await placesApi.search(city);
                      setPlaces(data);
                    } catch (error) {
                      console.error('Search error:', error);
                    } finally {
                      setLoading(false);
                    }
                  }, 0);
                }}
              >
                {city}
              </Badge>
            ))}
          </div>
        </div>
      </section>
      {/* Popular Destinations - Hero Showcase Only */}
      <section className="py-16 bg-white dark:bg-background">
        <div className="container mx-auto px-4">
          <div className="flex items-center justify-between mb-8">
            <h2 className="text-2xl font-bold">Popular Destinations</h2>
            <Button variant="ghost" className="text-primary gap-1">View All <ChevronRight className="h-4 w-4" /></Button>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {destinations.map((dest, i) => (
              <Card key={i} className="group overflow-hidden rounded-2xl border-none shadow-sm cursor-pointer">
                <div className="relative aspect-[4/5]">
                  <img src={dest.image} alt={dest.name} className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110" />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
                  <div className="absolute bottom-4 left-4 text-white">
                    <h3 className="text-xl font-bold">{dest.name}</h3>
                    <p className="text-sm text-white/80">{dest.country}</p>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </div>
      </section>
      {/* Categories & Dynamic Places List */}
      <section className="py-16 bg-muted/20">
        <div className="container mx-auto px-4">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
            <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide">
              {categories.map((cat, i) => (
                <Badge 
                  key={i} 
                  variant={selectedCategory === cat ? "default" : "outline"} 
                  className={selectedCategory === cat ? "bg-primary rounded-full px-5 py-1.5 cursor-pointer" : "rounded-full px-5 py-1.5 cursor-pointer bg-white dark:bg-slate-900 hover:bg-muted"}
                  onClick={() => handleCategoryChange(cat)}
                >
                  {cat}
                </Badge>
              ))}
            </div>
            <Button variant="outline" className="rounded-full gap-2 shrink-0">
              <Filter className="h-4 w-4" /> Filters
            </Button>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
            {loading ? (
              Array.from({ length: 6 }).map((_, i) => (
                <Card key={i} className="overflow-hidden rounded-2xl border bg-white dark:bg-slate-900">
                  <Skeleton className="aspect-video w-full bg-muted" />
                  <CardContent className="p-5 space-y-3">
                    <Skeleton className="h-6 w-3/4 bg-muted" />
                    <Skeleton className="h-4 w-1/2 bg-muted" />
                    <Skeleton className="h-10 w-full bg-muted" />
                  </CardContent>
                </Card>
              ))
            ) : filteredPlaces.length === 0 ? (
              <div className="col-span-full text-center py-12">
                <p className="text-muted-foreground text-lg">Yer bulunamadı.</p>
                <p className="text-sm text-muted-foreground mt-2">Arama veya filtreleri ayarlamayı deneyin.</p>
              </div>
            ) : (
              filteredPlaces.map((place) => (
                <Card key={place.id} className="overflow-hidden rounded-2xl border bg-white dark:bg-slate-900 shadow-sm hover:shadow-md transition-shadow group">
                  <div className="relative aspect-video">
                    {place.image_url ? (
                      <img src={place.image_url} alt={place.name} className="w-full h-full object-cover" />
                    ) : (
                      <div className="w-full h-full bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center">
                        <MapPin className="h-12 w-12 text-primary/40" />
                      </div>
                    )}
                    <Button 
                      variant="ghost" 
                      size="icon" 
                      className={`absolute top-3 right-3 rounded-full backdrop-blur transition-colors ${
                        bookmarkedPlaces.has(place.id)
                          ? 'bg-primary text-white hover:bg-primary/90'
                          : 'bg-white/20 text-white hover:bg-white hover:text-primary'
                      }`}
                      onClick={() => handleToggleBookmark(place.id)}
                    >
                      <Bookmark className={`h-4 w-4 ${bookmarkedPlaces.has(place.id) ? 'fill-current' : ''}`} />
                    </Button>
                    {/* Place Type Badge - place.type null ise gösterilmez */}
                    {place.type && (
                      <div className="absolute bottom-3 left-3">
                        <Badge className="bg-accent text-white border-none">{place.type}</Badge>
                      </div>
                    )}
                  </div>
                  <CardContent className="p-5">
                    <div className="flex justify-between items-start mb-2">
                      <h3 className="text-lg font-bold group-hover:text-primary transition-colors">{place.name}</h3>
                      {place.rating && (
                        <div className="flex items-center gap-1 text-sm font-bold">
                          <Star className="h-4 w-4 fill-primary text-primary" /> {place.rating}
                        </div>
                      )}
                    </div>
                    {(place.city || place.country) && (
                      <div className="flex items-center text-sm text-muted-foreground mb-4">
                        <MapPin className="h-3 w-3 mr-1" /> 
                        {[place.city, place.country].filter(Boolean).join(', ')}
                      </div>
                    )}
                    {place.description && (
                      <p className="text-sm text-muted-foreground mb-4 line-clamp-2">{place.description}</p>
                    )}
                    {/* Add to Trip Button - KRİTİK: ASLA pasif olmamalı */}
                    <Button 
                      variant="outline" 
                      className="w-full rounded-full border-primary/20 text-primary hover:bg-primary hover:text-white transition-colors shadow-none"
                      onClick={() => handleAddToTrip(place)}
                    >
                      Seyahate Ekle
                    </Button>
                  </CardContent>
                </Card>
              ))
            )}
          </div>
          
          {!loading && filteredPlaces.length > 0 && (
            <div className="mt-12 text-center">
              <Button variant="outline" size="lg" className="rounded-full px-10">Daha Fazla Göster</Button>
            </div>
          )}
        </div>
      </section>
    </div>
  );
};

export default Explore;
