/**
 * Address Autocomplete Component
 *
 * Provides autocomplete functionality for address input with geocoding
 */

import React, { useRef, useEffect, useState } from 'react';
import { MapPin, Loader2, X, Check } from 'lucide-react';
import { Input, Button, Card, CardBody } from '@/components/ui';
import { useAddressAutocomplete } from '@/hooks/useAddressAutocomplete';
import { AddressResult } from '@/services/api/geocodingApi';

interface AddressAutocompleteProps {
  value?: string;
  placeholder?: string;
  onAddressSelect?: (address: AddressResult) => void;
  onCoordinatesChange?: (lat: number, lon: number) => void;
  className?: string;
  disabled?: boolean;
  countryCode?: string;
  required?: boolean;
}

export const AddressAutocomplete: React.FC<AddressAutocompleteProps> = ({
  value,
  placeholder = 'Enter bakery address...',
  onAddressSelect,
  onCoordinatesChange,
  className = '',
  disabled = false,
  countryCode = 'es',
  required = false
}) => {
  const {
    query,
    setQuery,
    results,
    isLoading,
    error,
    selectedAddress,
    selectAddress,
    clearSelection
  } = useAddressAutocomplete({ countryCode });

  const [showResults, setShowResults] = useState(false);
  const wrapperRef = useRef<HTMLDivElement>(null);

  // Initialize query from value prop
  useEffect(() => {
    if (value && !query) {
      setQuery(value);
    }
  }, [value, query, setQuery]);

  // Close results dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
        setShowResults(false);
      }
    }

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

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newQuery = e.target.value;
    setQuery(newQuery);
    setShowResults(true);
  };

  const handleSelectAddress = (address: AddressResult) => {
    selectAddress(address);
    setShowResults(false);

    // Notify parent components
    if (onAddressSelect) {
      onAddressSelect(address);
    }
    if (onCoordinatesChange) {
      onCoordinatesChange(address.lat, address.lon);
    }
  };

  const handleClear = () => {
    clearSelection();
    setShowResults(false);
  };

  const handleInputFocus = () => {
    if (results.length > 0) {
      setShowResults(true);
    }
  };

  return (
    <div ref={wrapperRef} className={`relative ${className}`}>
      <div className="relative">
        <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-[var(--text-secondary)]" />

        <Input
          type="text"
          value={query}
          onChange={handleInputChange}
          onFocus={handleInputFocus}
          placeholder={placeholder}
          disabled={disabled}
          required={required}
          className={`pl-10 pr-10 ${selectedAddress ? 'border-[var(--color-success)]' : ''}`}
        />

        <div className="absolute right-3 top-1/2 transform -translate-y-1/2 flex items-center gap-1">
          {isLoading && (
            <Loader2 className="h-4 w-4 animate-spin text-[var(--text-secondary)]" />
          )}
          {selectedAddress && !isLoading && (
            <Check className="h-4 w-4 text-[var(--color-success)]" />
          )}
          {query && !disabled && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={handleClear}
              className="h-6 w-6 p-0 hover:bg-[var(--bg-secondary)]"
            >
              <X className="h-3 w-3" />
            </Button>
          )}
        </div>
      </div>

      {/* Error message */}
      {error && (
        <div className="mt-1 text-sm text-[var(--color-error)]">
          {error}
        </div>
      )}

      {/* Results dropdown */}
      {showResults && results.length > 0 && (
        <Card className="absolute z-50 w-full mt-1 max-h-80 overflow-y-auto shadow-lg bg-[var(--bg-primary)]">
          <CardBody className="p-0">
            <div className="divide-y divide-[var(--border-secondary)]">
              {results.map((result) => (
                <button
                  key={result.place_id}
                  type="button"
                  onClick={() => handleSelectAddress(result)}
                  className="w-full text-left px-4 py-3 hover:bg-[var(--bg-secondary)] focus:bg-[var(--bg-secondary)] focus:outline-none transition-colors"
                >
                  <div className="flex items-start gap-3">
                    <MapPin className="h-4 w-4 text-[var(--color-primary)] mt-1 flex-shrink-0" />
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium text-[var(--text-primary)] truncate">
                        {result.address.road && result.address.house_number
                          ? `${result.address.road}, ${result.address.house_number}`
                          : result.address.road || result.display_name}
                      </div>
                      <div className="text-xs text-[var(--text-secondary)] truncate mt-0.5">
                        {result.address.city || result.address.municipality || result.address.suburb}
                        {result.address.postcode && `, ${result.address.postcode}`}
                      </div>
                      <div className="text-xs text-[var(--text-tertiary)] mt-1">
                        {result.lat.toFixed(6)}, {result.lon.toFixed(6)}
                      </div>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </CardBody>
        </Card>
      )}

      {/* No results message */}
      {showResults && !isLoading && query.length >= 3 && results.length === 0 && !error && (
        <Card className="absolute z-50 w-full mt-1 shadow-lg bg-[var(--bg-primary)]">
          <CardBody className="p-4">
            <div className="text-sm text-[var(--text-secondary)] text-center">
              No addresses found for "{query}"
            </div>
          </CardBody>
        </Card>
      )}
    </div>
  );
};
