import { Home, Hotel, MapPin, MapPinned } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { cn } from '@/lib/utils';
import type { PlaceAutocompleteResult } from '@/types';

interface HotelSearchProps {
  value: {
    type: 'hotel' | 'custom' | 'city_center';
    name?: string;
    lat?: number;
    lng?: number;
  };
  onChange: (value: {
    type: 'hotel' | 'custom' | 'city_center';
    name?: string;
    lat?: number;
    lng?: number;
  }) => void;
}

export const HotelSearch: React.FC<HotelSearchProps> = ({ value, onChange }) => {
  const [searchQuery, setSearchQuery] = useState(value.name || '');
  const [predictions, setPredictions] = useState<PlaceAutocompleteResult[]>([]);
  const [showPredictions, setShowPredictions] = useState(false);
  const autocompleteService = useRef<google.maps.places.AutocompleteService | null>(null);
  const placesService = useRef<google.maps.places.PlacesService | null>(null);
  const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // Google Places API'yi başlat
  useEffect(() => {
    if (window.google?.maps?.places) {
      autocompleteService.current = new google.maps.places.AutocompleteService();
      const mapDiv = document.createElement('div');
      placesService.current = new google.maps.places.PlacesService(mapDiv);
    }
  }, []);

  // Arama sorgusu değiştiğinde otomatik tamamlama
  useEffect(() => {
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    if (!searchQuery || searchQuery.length < 3 || value.type === 'city_center') {
      setPredictions([]);
      setShowPredictions(false);
      return;
    }

    searchTimeoutRef.current = setTimeout(() => {
      if (!autocompleteService.current) return;

      const request: google.maps.places.AutocompletionRequest = {
        input: searchQuery,
        componentRestrictions: { country: 'tr' },
        location: new google.maps.LatLng(38.6431, 34.8289), // Göreme merkezi
        radius: 50000, // 50km yarıçap
        types: value.type === 'hotel' ? ['lodging'] : ['address'],
      };

      autocompleteService.current.getPlacePredictions(
        request,
        (predictions, status) => {
          if (status === google.maps.places.PlacesServiceStatus.OK && predictions) {
            setPredictions(
              predictions.map((p) => ({
                place_id: p.place_id,
                name: p.structured_formatting.main_text,
                formatted_address: p.description,
                lat: 0,
                lng: 0,
                types: p.types,
              }))
            );
            setShowPredictions(true);
          } else {
            setPredictions([]);
            setShowPredictions(false);
          }
        }
      );
    }, 300);

    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, [searchQuery, value.type]);

  // Yer seçildiğinde detayları al
  const handleSelectPlace = (prediction: PlaceAutocompleteResult) => {
    if (!placesService.current) return;

    const request: google.maps.places.PlaceDetailsRequest = {
      placeId: prediction.place_id,
      fields: ['name', 'geometry', 'formatted_address'],
    };

    placesService.current.getDetails(request, (place, status) => {
      if (status === google.maps.places.PlacesServiceStatus.OK && place?.geometry?.location) {
        const lat = place.geometry.location.lat();
        const lng = place.geometry.location.lng();
        const name = place.name || prediction.name;

        setSearchQuery(name);
        onChange({
          type: value.type,
          name,
          lat,
          lng,
        });
        setShowPredictions(false);
      }
    });
  };

  // Konaklama türü değiştiğinde
  const handleTypeChange = (newType: 'hotel' | 'custom' | 'city_center') => {
    if (newType === 'city_center') {
      // Göreme merkezi
      onChange({
        type: 'city_center',
        name: 'Göreme Merkez',
        lat: 38.6431,
        lng: 34.8289,
      });
      setSearchQuery('');
      setPredictions([]);
      setShowPredictions(false);
    } else {
      onChange({
        type: newType,
        name: undefined,
        lat: undefined,
        lng: undefined,
      });
      setSearchQuery('');
    }
  };

  return (
    <div className="space-y-4">
      <div className="space-y-3">
        <Label>Konaklama Başlangıç Noktası</Label>
        <RadioGroup
          value={value.type}
          onValueChange={(v) => handleTypeChange(v as 'hotel' | 'custom' | 'city_center')}
          className="grid grid-cols-1 sm:grid-cols-3 gap-3"
        >
          <div>
            <RadioGroupItem value="hotel" id="hotel" className="peer sr-only" />
            <Label
              htmlFor="hotel"
              className={cn(
                "flex flex-col items-center justify-center rounded-lg border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground cursor-pointer transition-all",
                "peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5"
              )}
            >
              <Hotel className="mb-2 h-6 w-6" />
              <span className="text-sm font-medium">Otel</span>
            </Label>
          </div>

          <div>
            <RadioGroupItem value="custom" id="custom" className="peer sr-only" />
            <Label
              htmlFor="custom"
              className={cn(
                "flex flex-col items-center justify-center rounded-lg border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground cursor-pointer transition-all",
                "peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5"
              )}
            >
              <Home className="mb-2 h-6 w-6" />
              <span className="text-sm font-medium">Airbnb / Adres</span>
            </Label>
          </div>

          <div>
            <RadioGroupItem value="city_center" id="city_center" className="peer sr-only" />
            <Label
              htmlFor="city_center"
              className={cn(
                "flex flex-col items-center justify-center rounded-lg border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground cursor-pointer transition-all",
                "peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5"
              )}
            >
              <MapPinned className="mb-2 h-6 w-6" />
              <span className="text-sm font-medium">Merkezden Başla</span>
            </Label>
          </div>
        </RadioGroup>
      </div>

      {/* Arama kutusu (sadece hotel veya custom seçiliyse) */}
      {(value.type === 'hotel' || value.type === 'custom') && (
        <div className="space-y-2 relative">
          <Label htmlFor="location-search">
            {value.type === 'hotel' ? 'Otel Ara' : 'Adres Ara'}
          </Label>
          <div className="relative">
            <MapPin className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <Input
              id="location-search"
              placeholder={
                value.type === 'hotel'
                  ? 'Örn: Sultan Cave Suites'
                  : 'Örn: Göreme, Müze Caddesi No:5'
              }
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onFocus={() => predictions.length > 0 && setShowPredictions(true)}
              className="pl-10 h-12"
            />
          </div>

          {/* Otomatik tamamlama sonuçları */}
          {showPredictions && predictions.length > 0 && (
            <div className="absolute z-50 w-full mt-1 bg-popover border border-border rounded-lg shadow-lg max-h-60 overflow-y-auto">
              {predictions.map((prediction) => (
                <button
                  key={prediction.place_id}
                  type="button"
                  onClick={() => handleSelectPlace(prediction)}
                  className="w-full text-left px-4 py-3 hover:bg-accent transition-colors flex items-start gap-3 border-b border-border last:border-b-0"
                >
                  <MapPin className="h-4 w-4 text-muted-foreground mt-1 shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-sm">{prediction.name}</div>
                    <div className="text-xs text-muted-foreground truncate">
                      {prediction.formatted_address}
                    </div>
                  </div>
                </button>
              ))}
            </div>
          )}

          {/* Seçili konum gösterimi */}
          {value.name && value.lat && value.lng && (
            <div className="flex items-center gap-2 p-3 bg-primary/5 border border-primary/20 rounded-lg">
              <MapPin className="h-4 w-4 text-primary shrink-0" />
              <div className="flex-1 min-w-0">
                <div className="text-sm font-medium truncate">{value.name}</div>
                <div className="text-xs text-muted-foreground">
                  {value.lat.toFixed(4)}, {value.lng.toFixed(4)}
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Göreme merkezi seçiliyse bilgi */}
      {value.type === 'city_center' && (
        <div className="flex items-center gap-2 p-3 bg-muted rounded-lg">
          <MapPinned className="h-4 w-4 text-muted-foreground shrink-0" />
          <div className="text-sm text-muted-foreground">
            Rotanız Göreme şehir merkezinden başlayacak
          </div>
        </div>
      )}
    </div>
  );
};
