import { 
  Bookmark, 
  Eye,
  FolderPlus,
  Heart,
  MapPin, 
  MoreVertical, 
  Plus, 
  Star, 
  Trash2 
} from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { useAuth } from '@/contexts/AuthContext';
import { useCurrentTrip } from '@/contexts/CurrentTripContext';
import { bookmarksApi, collectionsApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';

interface Collection {
  id: string;
  name: string;
  icon: string;
  created_at: string;
}

interface BookmarkedPlace {
  id: string;
  place_id: string;
  is_favorite: boolean;
  created_at: string;
  places: {
    id: string;
    name: string;
    description: string | null;
    type: string | null;
    city: string | null;
    country: string | null;
    rating: number | null;
    image_url: string | null;
  };
}

const Bookmarks = () => {
  const { user } = useAuth();
  const { toast } = useToast();
  const navigate = useNavigate();
  const { activeDayId, setActiveDayId } = useCurrentTrip();
  const [collections, setCollections] = useState<Collection[]>([]);
  const [bookmarks, setBookmarks] = useState<BookmarkedPlace[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedCollection, setSelectedCollection] = useState<string | null>(null);
  const [isNewCollectionOpen, setIsNewCollectionOpen] = useState(false);
  const [newCollectionName, setNewCollectionName] = useState('');

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

  const loadData = async () => {
    try {
      setLoading(true);
      const [collectionsData, bookmarksData] = await Promise.all([
        collectionsApi.getUserCollections(),
        bookmarksApi.getUserBookmarks(),
      ]);
      setCollections(collectionsData);
      setBookmarks(bookmarksData);
    } catch (error) {
      console.error('Veri yüklenirken hata:', error);
      toast({
        title: 'Hata',
        description: 'Veriler yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteBookmark = async (placeId: string) => {
    try {
      await bookmarksApi.unbookmark(placeId);
      toast({
        title: 'Başarılı',
        description: 'Yer kayıtlardan kaldırıldı.',
      });
      loadData();
    } catch (error) {
      console.error('Silme hatası:', error);
      toast({
        title: 'Hata',
        description: 'Yer silinemedi.',
        variant: 'destructive',
      });
    }
  };

  const handleCreateCollection = async () => {
    if (!newCollectionName.trim()) return;

    try {
      await collectionsApi.create({ name: newCollectionName, icon: 'folder' });
      toast({
        title: 'Başarılı',
        description: 'Koleksiyon oluşturuldu.',
      });
      setIsNewCollectionOpen(false);
      setNewCollectionName('');
      loadData();
    } catch (error) {
      console.error('Koleksiyon oluşturma hatası:', error);
      toast({
        title: 'Hata',
        description: 'Koleksiyon oluşturulamadı.',
        variant: 'destructive',
      });
    }
  };

  // Add to Trip button handler - KRİTİK FONKSİYON
  const handleAddToTrip = async (place: any) => {
    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 trip 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 trip YOKSA → /create-trip'e yönlendir (place bilgisini state ile gönder)
      if (!activeTrip || tripError) {
        navigate('/create-trip', {
          state: { pendingPlaceId: place.id }
        });
        return;
      }

      // 3. Aktif trip VARSA → place'i ekle ve /planner'a yönlendir
      const tripId = activeTrip.id;
      
      // Context'ten aktif günü al, yoksa ilk günü kullan
      const tripDays = activeTrip.trip_days;
      let targetDayId = activeDayId;
      
      // Eğer context'te activeDayId yoksa veya bu trip'in günleri arasında değilse, ilk günü kullan
      if (!targetDayId || !tripDays?.some((day: any) => day.id === targetDayId)) {
        // trip_days'i order_index'e göre sırala (Supabase sırası garanti değil)
        const sortedDays = [...(tripDays || [])].sort(
          (a: any, b: any) => a.order_index - b.order_index
        );
        targetDayId = sortedDays[0]?.id;
        // İlk günü context'e de kaydet
        if (targetDayId) {
          setActiveDayId(targetDayId);
        }
      }

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

      // 4. Aynı place'in 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;
      }

      // 5. Aktif gündeki son order_index'i al
      const { data: existingPlaces } = await (supabase as any)
        .from('trip_places')
        .select('order_index')
        .eq('trip_day_id', targetDayId)
        .order('order_index', { ascending: false })
        .limit(1);

      const existingPlacesArray = existingPlaces || [];
      const lastOrderIndex = existingPlacesArray?.[0]?.order_index || 0;

      // 6. trip_places tablosuna kayıt ekle
      const { error: insertError } = await (supabase as any)
        .from('trip_places')
        .insert([{
          place_id: place.id,
          trip_day_id: targetDayId,
          order_index: lastOrderIndex + 1,
          duration: place.duration || '2 saat', // places.duration'dan al
        }]);

      if (insertError) {
        console.error('Insert error:', insertError);
        toast({
          title: 'Hata',
          description: 'Yer seyahate eklenemedi.',
          variant: 'destructive',
        });
        return;
      }

      // 7. /planner'a yönlendir
      navigate(`/planner?trip_id=${tripId}`);
      toast({
        title: 'Başarılı',
        description: `${place.name} seyahatinize eklendi!`,
      });
    } catch (error) {
      console.error('Add to trip error:', error);
      toast({
        title: 'Hata',
        description: 'Bir şeyler yanlış gitti.',
        variant: 'destructive',
      });
    }
  };

  const getIconComponent = (iconName: string) => {
    switch (iconName) {
      case 'heart': return Heart;
      case 'eye': return Eye;
      case 'bookmark': return Bookmark;
      default: return Star;
    }
  };

  const filteredBookmarks = selectedCollection
    ? bookmarks.filter(b => b.places && (
        selectedCollection === 'favorites' ? b.is_favorite : true
      ))
    : bookmarks.filter(b => b.places);

  const getCollectionCount = (collectionId: string) => {
    if (collectionId === 'all') return bookmarks.filter(b => b.places).length;
    if (collectionId === 'favorites') return bookmarks.filter(b => b.places && b.is_favorite).length;
    return bookmarks.filter(b => b.places).length;
  };

  if (!user) {
    return (
      <div className="container mx-auto px-4 py-16 text-center">
        <h2 className="text-2xl font-bold mb-4">Giriş Yapmanız Gerekiyor</h2>
        <p className="text-muted-foreground mb-8">Yerleri kaydetmek için lütfen giriş yapın.</p>
        <Button onClick={() => navigate('/')}>Ana Sayfaya Dön</Button>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex flex-col md:flex-row gap-8">
        {/* Sidebar */}
        <div className="w-full md:w-64 shrink-0">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-bold">Koleksiyonlarım</h2>
            <Button 
              variant="ghost" 
              size="icon" 
              className="h-8 w-8 text-primary"
              onClick={() => setIsNewCollectionOpen(true)}
            >
              <Plus className="h-5 w-5" />
            </Button>
          </div>
          <div className="space-y-1">
            <Button
              variant={selectedCollection === null ? "secondary" : "ghost"}
              className={"w-full justify-start rounded-xl " + (selectedCollection === null ? "bg-primary/10 text-primary hover:bg-primary/20" : "")}
              onClick={() => setSelectedCollection(null)}
            >
              <Bookmark className="mr-3 h-4 w-4" />
              <span className="flex-1 text-left">Tüm Kaydedilenler</span>
              <span className="text-xs text-muted-foreground">{getCollectionCount('all')}</span>
            </Button>
            <Button
              variant={selectedCollection === 'favorites' ? "secondary" : "ghost"}
              className={"w-full justify-start rounded-xl " + (selectedCollection === 'favorites' ? "bg-primary/10 text-primary hover:bg-primary/20" : "")}
              onClick={() => setSelectedCollection('favorites')}
            >
              <Heart className="mr-3 h-4 w-4" />
              <span className="flex-1 text-left">Favoriler</span>
              <span className="text-xs text-muted-foreground">{getCollectionCount('favorites')}</span>
            </Button>
            {collections.filter(c => !['Tüm Kaydedilenler', 'Favoriler'].includes(c.name)).map((col) => {
              const IconComponent = getIconComponent(col.icon);
              return (
                <Button
                  key={col.id}
                  variant={selectedCollection === col.id ? "secondary" : "ghost"}
                  className={"w-full justify-start rounded-xl " + (selectedCollection === col.id ? "bg-primary/10 text-primary hover:bg-primary/20" : "")}
                  onClick={() => setSelectedCollection(col.id)}
                >
                  <IconComponent className="mr-3 h-4 w-4" />
                  <span className="flex-1 text-left">{col.name}</span>
                  <span className="text-xs text-muted-foreground">{getCollectionCount(col.id)}</span>
                </Button>
              );
            })}
          </div>
          <Button 
            variant="outline" 
            className="w-full mt-6 border-dashed rounded-xl gap-2"
            onClick={() => setIsNewCollectionOpen(true)}
          >
            <FolderPlus className="h-4 w-4" /> Yeni Koleksiyon
          </Button>
        </div>

        {/* Content */}
        <div className="flex-1">
          <div className="flex items-center justify-between mb-8">
            <h1 className="text-3xl font-bold">
              {selectedCollection === 'favorites' ? 'Favoriler' : 'Tüm Kaydedilenler'}
            </h1>
            <div className="flex items-center gap-2 text-sm text-muted-foreground bg-muted px-4 py-2 rounded-full">
              <span>Sırala: <b>En Yeni</b></span>
            </div>
          </div>

          {loading ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {Array.from({ length: 6 }).map((_, i) => (
                <Card key={i} className="overflow-hidden rounded-2xl border">
                  <Skeleton className="aspect-video w-full bg-muted" />
                  <CardContent className="p-4 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>
              ))}
            </div>
          ) : filteredBookmarks.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredBookmarks.map((bookmark) => {
                const place = bookmark.places;
                return (
                  <Card key={bookmark.id} className="overflow-hidden rounded-2xl border shadow-sm 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>
                      )}
                      <div className="absolute top-3 right-3 flex gap-2">
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          className="h-8 w-8 rounded-full bg-white/50 backdrop-blur text-foreground hover:bg-white transition-colors"
                        >
                          <MoreVertical className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    <CardContent className="p-4">
                      <div className="flex justify-between items-start mb-1">
                        <h3 className="font-bold truncate pr-4">{place.name}</h3>
                        {place.rating && (
                          <div className="flex items-center gap-1 text-xs font-bold text-primary">
                            <Star className="h-3 w-3 fill-primary" /> {place.rating}
                          </div>
                        )}
                      </div>
                      {(place.city || place.country) && (
                        <div className="flex items-center text-xs text-muted-foreground mb-4">
                          <MapPin className="h-3 w-3 mr-1" /> 
                          {[place.city, place.country].filter(Boolean).join(', ')}
                        </div>
                      )}
                      <div className="flex gap-2">
                        <Button 
                          size="sm" 
                          className="flex-1 rounded-full bg-primary text-xs font-bold"
                          onClick={() => handleAddToTrip(place)}
                        >
                          Seyahate Ekle
                        </Button>
                        <Button 
                          size="sm" 
                          variant="ghost" 
                          className="rounded-full text-destructive hover:text-destructive hover:bg-destructive/10 px-3"
                          onClick={() => handleDeleteBookmark(place.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
              <div 
                className="border-2 border-dashed rounded-2xl flex flex-col items-center justify-center p-8 text-center text-muted-foreground hover:border-primary/50 transition-colors cursor-pointer bg-muted/20"
                onClick={() => navigate('/explore')}
              >
                <Bookmark className="h-10 w-10 mb-4 opacity-20" />
                <h4 className="font-bold mb-1">Daha fazla yer kaydet</h4>
                <p className="text-sm">Keşfet sayfasından yeni yerler ekle</p>
              </div>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-32 text-center">
              <div className="w-20 h-20 rounded-full bg-muted flex items-center justify-center mb-6">
                <Bookmark className="h-10 w-10 text-muted-foreground opacity-30" />
              </div>
              <h2 className="text-2xl font-bold mb-2">Henüz kaydedilmiş yer yok</h2>
              <p className="text-muted-foreground max-w-sm mb-8">
                Gezmek istediğiniz yerleri kaydederek kendi seyahat listelerinizi oluşturun.
              </p>
              <Button 
                className="rounded-full bg-primary px-8 h-12 text-lg font-bold"
                onClick={() => navigate('/explore')}
              >
                Keşfetmeye Başla
              </Button>
            </div>
          )}
        </div>
      </div>

      {/* Yeni Koleksiyon Dialog */}
      <Dialog open={isNewCollectionOpen} onOpenChange={setIsNewCollectionOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Yeni Koleksiyon Oluştur</DialogTitle>
            <DialogDescription>
              Kaydettiğiniz yerleri organize etmek için yeni bir koleksiyon oluşturun.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="collection-name">Koleksiyon Adı</Label>
              <Input
                id="collection-name"
                placeholder="Örn: Yaz Tatili 2026"
                value={newCollectionName}
                onChange={(e) => setNewCollectionName(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleCreateCollection()}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsNewCollectionOpen(false)}>
              İptal
            </Button>
            <Button onClick={handleCreateCollection} disabled={!newCollectionName.trim()}>
              Oluştur
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default Bookmarks;
