import { Lock, MapPin, Plus, Search, Star } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { LazyImage } from '@/components/ui/lazy-image';
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { placesApi } from '@/db/api';
import { useDebounce } from '@/hooks/use-debounce';
import { cn } from '@/lib/utils';


interface AddPlaceSheetProps {
  dayNumber: number;
  searchQuery: string;
  searchResults: any[];
  isSearching: boolean;
  tripHasBalloon?: boolean; // Trip-level constraint
  onSearchChange: (query: string) => void;
  onAddPlace: (placeId: string) => void;
  trigger?: React.ReactNode;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
}

// Kategori tanımları (Türkçe etiketler)
const CATEGORIES = [
  { id: 'all', label: 'Tümü', type: null },
  { id: 'museum', label: 'Müze', type: 'museum' },
  { id: 'historical', label: 'Tarihi', type: 'historical' },
  { id: 'viewpoint', label: 'Manzara', type: 'viewpoint' },
  { id: 'restaurant', label: 'Restoran', type: 'restaurant' },
  { id: 'hotel', label: 'Otel', type: 'hotel' },
  { id: 'hot-air-balloon', label: 'Balon', type: 'hot-air-balloon' },
  { id: 'tour', label: 'Tur', type: 'tour' },
  { id: 'atv', label: 'ATV', type: 'atv' },
  { id: 'horse-riding', label: 'At Binme', type: 'horse-riding' },
];

export const AddPlaceSheet: React.FC<AddPlaceSheetProps> = ({
  dayNumber,
  searchQuery,
  searchResults,
  isSearching,
  tripHasBalloon = false,
  onSearchChange,
  onAddPlace,
  trigger,
  open,
  onOpenChange,
}) => {
  const [isMobile, setIsMobile] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [explorePlaces, setExplorePlaces] = useState<any[]>([]);
  const [isLoadingExplore, setIsLoadingExplore] = useState(false);
  const [inputValue, setInputValue] = useState(searchQuery);
  const debouncedValue = useDebounce(inputValue, 300);

  // Mobil ekran kontrolü
  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 768);
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  // Sync internal input with prop if changed from outside
  useEffect(() => {
    setInputValue(searchQuery);
  }, [searchQuery]);

  useEffect(() => {
    onSearchChange(debouncedValue);
  }, [debouncedValue, onSearchChange]);

  // Keşfet modunda yerler yükle
  useEffect(() => {
    if (!searchQuery) {
      loadExplorePlaces();
    }
  }, [selectedCategory, searchQuery]);

  const loadExplorePlaces = async () => {
    setIsLoadingExplore(true);
    try {
      const category = CATEGORIES.find(c => c.id === selectedCategory);
      let places: any[] = [];
      
      if (category?.type) {
        places = await placesApi.getByType(category.type);
      } else {
        const result = await placesApi.getAll(1, 50);
        places = result.places;
      }
      
      setExplorePlaces(places);
    } catch (error) {
      console.error('Yerler yüklenirken hata:', error);
      setExplorePlaces([]);
    } finally {
      setIsLoadingExplore(false);
    }
  };

  // Gösterilecek yerler: arama varsa searchResults, yoksa explorePlaces
  const displayPlaces = searchQuery ? searchResults : explorePlaces;
  const isLoading = searchQuery ? isSearching : isLoadingExplore;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      {trigger && <SheetTrigger asChild>{trigger}</SheetTrigger>}
      <SheetContent 
        side={isMobile ? "bottom" : "right"} 
        className={cn(
          "w-full sm:max-w-2xl",
          isMobile ? "h-[85vh] rounded-t-3xl" : "h-screen"
        )}
      >
        <SheetHeader className={isMobile ? "pt-2 pb-0" : ""}>
          <SheetTitle>Gün {dayNumber} için yer ekle</SheetTitle>
          <SheetDescription>
            Görmek istediğiniz bir yeri arayın ve seyahat programınıza ekleyin.
          </SheetDescription>
        </SheetHeader>
        
        <div className="py-4 space-y-4 h-full flex flex-col overflow-hidden">
          {/* Search Input */}
          <div className="relative shrink-0">
            <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <Input 
              placeholder="Yer veya adres ara..." 
              className="pl-10 rounded-full h-12"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              autoFocus={!isMobile}
            />
          </div>

          {/* Kategori Filtreleri - Sadece keşfet modunda göster */}
          {!searchQuery && (
            <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide shrink-0">
              {CATEGORIES.map((category) => (
                <Badge
                  key={category.id}
                  variant={selectedCategory === category.id ? 'default' : 'outline'}
                  className="cursor-pointer whitespace-nowrap"
                  onClick={() => setSelectedCategory(category.id)}
                >
                  {category.label}
                </Badge>
              ))}
            </div>
          )}

          {/* Places Grid - Keşfet Stili */}
          <div className="flex-1 overflow-y-auto pr-2 pb-24">
            {isLoading ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {[1, 2, 3, 4].map((i) => (
                  <div key={i} className="space-y-2">
                    <Skeleton className="h-40 w-full rounded-xl" />
                    <Skeleton className="h-4 w-3/4" />
                    <Skeleton className="h-3 w-1/2" />
                  </div>
                ))}
              </div>
            ) : displayPlaces.length > 0 ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {displayPlaces.map((place) => {
                  const isBalloon = place.type === 'hot-air-balloon';
                  const isBalloonDisabled = isBalloon && tripHasBalloon;
                  
                  return (
                    <div 
                      key={place.id} 
                      className={`group relative rounded-xl border overflow-hidden transition-all ${
                        isBalloonDisabled 
                          ? 'opacity-50 cursor-not-allowed' 
                          : 'hover:shadow-lg cursor-pointer'
                      }`}
                    >
                      {/* Yer Görseli */}
                      <div className="relative h-40 overflow-hidden">
                        <LazyImage 
                          src={place.image_url || 'https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?q=80&w=400'} 
                          alt={place.name} 
                          className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" 
                        />
                        {/* Kategori Badge */}
                        {place.type && (
                          <Badge 
                            variant="secondary" 
                            className="absolute top-2 left-2 text-xs"
                          >
                            {CATEGORIES.find(c => c.type === place.type)?.label || place.type}
                          </Badge>
                        )}
                        {/* Ekle Butonu */}
                        {!isBalloonDisabled && (
                          <Button
                            size="sm"
                            className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
                            onClick={() => onAddPlace(place.id)}
                          >
                            <Plus className="h-4 w-4 mr-1" />
                            Ekle
                          </Button>
                        )}
                        {isBalloonDisabled && (
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <Button
                                  size="sm"
                                  variant="secondary"
                                  className="absolute top-2 right-2"
                                  disabled
                                >
                                  <Lock className="h-4 w-4" />
                                </Button>
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>Bu seyahatte balon uçuşu zaten planlandı</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        )}
                      </div>
                      
                      {/* Yer Bilgileri */}
                      <div className="p-3 space-y-1">
                        <h4 className="font-semibold text-sm line-clamp-1">{place.name}</h4>
                        
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                          {place.rating && (
                            <div className="flex items-center gap-1">
                              <Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
                              <span>{place.rating}</span>
                            </div>
                          )}
                          {place.city && (
                            <div className="flex items-center gap-1">
                              <MapPin className="h-3 w-3" />
                              <span className="line-clamp-1">
                                {place.city}{place.country ? `, ${place.country}` : ''}
                              </span>
                            </div>
                          )}
                        </div>

                        {place.duration && (
                          <p className="text-xs text-muted-foreground">
                            ⏱️ {place.duration}
                          </p>
                        )}

                        {isBalloonDisabled && (
                          <p className="text-xs text-destructive mt-1">
                            Bu seyahatte balon uçuşu zaten planlandı
                          </p>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : searchQuery ? (
              <div className="text-center py-12 text-muted-foreground">
                <Search className="h-12 w-12 mx-auto mb-3 opacity-20" />
                <p className="text-sm font-medium">Sonuç bulunamadı</p>
                <p className="text-xs mt-1">Farklı bir arama terimi deneyin</p>
              </div>
            ) : (
              <div className="text-center py-12 text-muted-foreground">
                <MapPin className="h-12 w-12 mx-auto mb-3 opacity-20" />
                <p className="text-sm font-medium">Yer bulunamadı</p>
                <p className="text-xs mt-1">Farklı bir kategori seçin veya arama yapın</p>
              </div>
            )}
          </div>
        </div>
      </SheetContent>
    </Sheet>
  );
};
