"use client"

import { useState, useRef, useEffect } from "react"
import { MapPin, Search, Target, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent } from "@/components/ui/card"

interface LocationPickerProps {
  onLocationSelect: (location: {
    address: string
    city?: string
    state?: string
    zipCode?: string
    coordinates?: { lat: number; lng: number }
  }) => void
  onCurrentLocation?: () => void
  placeholder?: string
  value?: string
  className?: string
}

interface LocationSuggestion {
  address: string
  city?: string
  state?: string
  zipCode?: string
  coordinates?: { lat: number; lng: number }
  type: 'city' | 'zipcode' | 'address' | 'current'
}

export function LocationPicker({
  onLocationSelect,
  onCurrentLocation,
  placeholder = "Enter city, state, or ZIP code",
  value = "",
  className = ""
}: LocationPickerProps) {
  const [inputValue, setInputValue] = useState(value)
  const [suggestions, setSuggestions] = useState<LocationSuggestion[]>([])
  const [showSuggestions, setShowSuggestions] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)

  // Mock suggestions based on your Texas data
  const mockSuggestions: LocationSuggestion[] = [
    // Major Texas Cities
    { address: "Houston, TX", city: "Houston", state: "TX", type: "city", coordinates: { lat: 29.7604, lng: -95.3698 } },
    { address: "Dallas, TX", city: "Dallas", state: "TX", type: "city", coordinates: { lat: 32.7767, lng: -96.7970 } },
    { address: "Austin, TX", city: "Austin", state: "TX", type: "city", coordinates: { lat: 30.2672, lng: -97.7431 } },
    { address: "San Antonio, TX", city: "San Antonio", state: "TX", type: "city", coordinates: { lat: 29.4241, lng: -98.4936 } },
    { address: "Fort Worth, TX", city: "Fort Worth", state: "TX", type: "city", coordinates: { lat: 32.7555, lng: -97.3308 } },
    { address: "McKinney, TX", city: "McKinney", state: "TX", type: "city", coordinates: { lat: 33.1972, lng: -96.6397 } },
    { address: "Conroe, TX", city: "Conroe", state: "TX", type: "city", coordinates: { lat: 30.3119, lng: -95.4560 } },
    { address: "Allen, TX", city: "Allen", state: "TX", type: "city", coordinates: { lat: 33.1031, lng: -96.6706 } },
    { address: "Keller, TX", city: "Keller", state: "TX", type: "city", coordinates: { lat: 32.9342, lng: -97.2297 } },
    { address: "Tyler, TX", city: "Tyler", state: "TX", type: "city", coordinates: { lat: 32.3513, lng: -95.3011 } },
    { address: "Plano, TX", city: "Plano", state: "TX", type: "city", coordinates: { lat: 33.0198, lng: -96.6989 } },
    { address: "Carrollton, TX", city: "Carrollton", state: "TX", type: "city", coordinates: { lat: 32.9537, lng: -96.8903 } },
    { address: "Katy, TX", city: "Katy", state: "TX", type: "city", coordinates: { lat: 29.7858, lng: -95.8244 } },
    { address: "Round Rock, TX", city: "Round Rock", state: "TX", type: "city", coordinates: { lat: 30.5083, lng: -97.6789 } },

    // Popular ZIP Codes from your data
    { address: "75070 - McKinney, TX", zipCode: "75070", city: "McKinney", state: "TX", type: "zipcode", coordinates: { lat: 33.1972, lng: -96.6397 } },
    { address: "77304 - Conroe, TX", zipCode: "77304", city: "Conroe", state: "TX", type: "zipcode", coordinates: { lat: 30.3119, lng: -95.4560 } },
    { address: "75002 - Allen, TX", zipCode: "75002", city: "Allen", state: "TX", type: "zipcode", coordinates: { lat: 33.1031, lng: -96.6706 } },
    { address: "78240 - San Antonio, TX", zipCode: "78240", city: "San Antonio", state: "TX", type: "zipcode", coordinates: { lat: 29.4241, lng: -98.4936 } },
    { address: "75248 - Dallas, TX", zipCode: "75248", city: "Dallas", state: "TX", type: "zipcode", coordinates: { lat: 32.7767, lng: -96.7970 } },
    { address: "76248 - Keller, TX", zipCode: "76248", city: "Keller", state: "TX", type: "zipcode", coordinates: { lat: 32.9342, lng: -97.2297 } },
    { address: "75007 - Carrollton, TX", zipCode: "75007", city: "Carrollton", state: "TX", type: "zipcode", coordinates: { lat: 32.9537, lng: -96.8903 } },
    { address: "77494 - Katy, TX", zipCode: "77494", city: "Katy", state: "TX", type: "zipcode", coordinates: { lat: 29.7858, lng: -95.8244 } },
    { address: "75703 - Tyler, TX", zipCode: "75703", city: "Tyler", state: "TX", type: "zipcode", coordinates: { lat: 32.3513, lng: -95.3011 } },
    { address: "78665 - Round Rock, TX", zipCode: "78665", city: "Round Rock", state: "TX", type: "zipcode", coordinates: { lat: 30.5083, lng: -97.6789 } },
  ]

  // Filter suggestions based on input
  const filterSuggestions = (query: string): LocationSuggestion[] => {
    if (!query || query.length < 2) return []

    const lowerQuery = query.toLowerCase()

    return mockSuggestions.filter(suggestion =>
      suggestion.address.toLowerCase().includes(lowerQuery) ||
      suggestion.city?.toLowerCase().includes(lowerQuery) ||
      suggestion.zipCode?.includes(query) ||
      suggestion.state?.toLowerCase().includes(lowerQuery)
    ).slice(0, 8) // Limit to 8 suggestions
  }

  // Handle input change
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setInputValue(value)

    if (value.length >= 2) {
      const filtered = filterSuggestions(value)
      setSuggestions(filtered)
      setShowSuggestions(true)
    } else {
      setSuggestions([])
      setShowSuggestions(false)
    }
  }

  // Handle suggestion selection
  const handleSuggestionSelect = (suggestion: LocationSuggestion) => {
    setInputValue(suggestion.address)
    setShowSuggestions(false)
    onLocationSelect({
      address: suggestion.address,
      city: suggestion.city,
      state: suggestion.state,
      zipCode: suggestion.zipCode,
      coordinates: suggestion.coordinates
    })
  }

  // Handle current location
  const handleCurrentLocation = () => {
    if (onCurrentLocation) {
      setIsLoading(true)
      onCurrentLocation()

      // Simulate loading
      setTimeout(() => {
        setIsLoading(false)
        setInputValue("Current Location")
      }, 1000)
    }
  }

  // Clear input
  const handleClear = () => {
    setInputValue("")
    setSuggestions([])
    setShowSuggestions(false)
    onLocationSelect({ address: "" })
  }

  // Close suggestions when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (inputRef.current && !inputRef.current.contains(event.target as Node)) {
        setShowSuggestions(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  const getSuggestionIcon = (type: string) => {
    switch (type) {
      case 'city': return '🏙️'
      case 'zipcode': return '📍'
      case 'address': return '🏠'
      case 'current': return '📍'
      default: return '📍'
    }
  }

  return (
    <div className={`relative ${className}`} ref={inputRef}>
      <div className="relative">
        <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
        <Input
          type="text"
          placeholder={placeholder}
          value={inputValue}
          onChange={handleInputChange}
          onFocus={() => {
            if (suggestions.length > 0) {
              setShowSuggestions(true)
            }
          }}
          className="pl-10 pr-20 h-12 text-lg"
        />

        <div className="absolute right-2 top-1/2 transform -translate-y-1/2 flex gap-1">
          {inputValue && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={handleClear}
              className="h-8 w-8 p-0 hover:bg-gray-100 text-gray-500 hover:text-gray-900"
            >
              <X className="h-4 w-4" />
            </Button>
          )}

          {onCurrentLocation && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={handleCurrentLocation}
              disabled={isLoading}
              className="h-8 w-8 p-0 hover:bg-blue-100"
              title="Use current location"
            >
              {isLoading ? (
                <div className="h-4 w-4 border-2 border-blue-600 border-t-transparent rounded-full animate-spin" />
              ) : (
                <Target className="h-4 w-4 text-blue-600" />
              )}
            </Button>
          )}
        </div>
      </div>

      {/* Suggestions Dropdown */}
      {showSuggestions && suggestions.length > 0 && (
        <Card className="absolute top-full left-0 right-0 mt-1 z-50 shadow-lg border">
          <CardContent className="p-0">
            <div className="max-h-64 overflow-y-auto">
              {suggestions.map((suggestion, index) => (
                <button
                  key={index}
                  type="button"
                  onClick={() => handleSuggestionSelect(suggestion)}
                  className="w-full text-left px-4 py-3 hover:bg-gray-50 border-b border-gray-100 last:border-b-0 flex items-center gap-3 transition-colors"
                >
                  <span className="text-lg">{getSuggestionIcon(suggestion.type)}</span>
                  <div className="flex-1">
                    <div className="font-medium text-gray-900">{suggestion.address}</div>
                    {suggestion.type === 'zipcode' && (
                      <div className="text-sm text-gray-500">ZIP Code</div>
                    )}
                    {suggestion.type === 'city' && (
                      <div className="text-sm text-gray-500">City</div>
                    )}
                  </div>
                </button>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
