import { Loader2, MapPin, Search, Star } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { adminAdvancedApi } from '@/db/api';
import { useDebounce } from '@/hooks/use-debounce';
import { cn } from '@/lib/utils';

interface PlaceSearchStepProps {
  initialQuery?: string;
  selectedPlace?: any;
  onSelect: (place: any) => void;
}

export const PlaceSearchStep: React.FC<PlaceSearchStepProps> = ({ initialQuery = '', selectedPlace, onSelect }) => {
  const [query, setQuery] = useState(initialQuery);
  const [results, setResults] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const debouncedQuery = useDebounce(query, 500);

  useEffect(() => {
    if (debouncedQuery && debouncedQuery.length > 2) {
      handleSearch(debouncedQuery);
    }
  }, [debouncedQuery]);

  const handleSearch = async (searchQuery: string) => {
    setIsLoading(true);
    try {
      const data = await adminAdvancedApi.smartSearch({ query: searchQuery });
      const places = data.webPages?.value || [];
      // Map results to a more standard format if needed
      setResults(places.map((p: any) => ({
        id: p.url, // Using URL as a temporary ID
        name: p.name,
        address: p.displayUrl,
        image_url: p.thumbnailUrl,
        snippet: p.snippet,
        source_url: p.url
      })));
    } catch (error) {
      console.error('Arama hatası:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-4">
      <h3 className="text-lg font-medium text-center">Nereye gitmek istersiniz?</h3>
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <Input
          placeholder="Yer adı veya kategori arayın..."
          className="pl-10"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
      </div>

      <ScrollArea className="h-[300px] rounded-md border p-2">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center h-full space-y-2 py-10">
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
            <p className="text-sm text-muted-foreground">Aranıyor...</p>
          </div>
        ) : results.length > 0 ? (
          <div className="space-y-2">
            {results.map((result) => (
              <Card
                key={result.id}
                className={cn(
                  "cursor-pointer transition-all hover:border-primary/50",
                  selectedPlace?.source_url === result.source_url ? "border-primary bg-primary/5" : "border-border"
                )}
                onClick={() => onSelect(result)}
              >
                <CardContent className="p-3 flex items-start space-x-3">
                  {result.image_url && (
                    <img
                      src={result.image_url}
                      alt={result.name}
                      className="w-16 h-16 rounded-md object-cover flex-shrink-0"
                    />
                  )}
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-sm truncate">{result.name}</p>
                    <p className="text-xs text-muted-foreground line-clamp-2 mt-1">{result.snippet}</p>
                    <div className="flex items-center mt-1 space-x-2">
                      <MapPin className="w-3 h-3 text-muted-foreground" />
                      <span className="text-[10px] text-muted-foreground truncate">{result.address}</span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : query.length > 2 ? (
          <div className="flex flex-col items-center justify-center h-full py-10">
            <p className="text-sm text-muted-foreground">Sonuç bulunamadı.</p>
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center h-full py-10">
            <p className="text-sm text-muted-foreground">Aramaya başlayın...</p>
          </div>
        )}
      </ScrollArea>
    </div>
  );
};
