import React, { useState, useEffect, useRef } from "react";
import AddressAutocomplete from "./AddressAutocomplete";
import { PlaceDetails } from "../services/placesService";

interface FilterPanelProps {
  show: boolean;
  onClose: () => void;
  currentFilters: {
    lat: string;
    lng: string;
    radius: string;
    locationName?: string;
  };
  onApplyFilters: (filters: {
    lat: string;
    lng: string;
    radius: string;
    locationName: string;
  }) => void;
}

const RADIUS_OPTIONS = [
  { value: "5", label: "5 miles" },
  { value: "10", label: "10 miles" },
  { value: "25", label: "25 miles" },
  { value: "50", label: "50 miles" },
  { value: "100", label: "100 miles" },
];

const FilterPanel: React.FC<FilterPanelProps> = ({
  show,
  onClose,
  currentFilters,
  onApplyFilters,
}) => {
  const [locationInput, setLocationInput] = useState("");
  const [selectedLocation, setSelectedLocation] = useState<{
    lat: number;
    lng: number;
    name: string;
  } | null>(null);
  const [radius, setRadius] = useState(currentFilters.radius || "25");
  const panelRef = useRef<HTMLDivElement>(null);

  // Initialize from current filters
  useEffect(() => {
    if (currentFilters.locationName) {
      setLocationInput(currentFilters.locationName);
      if (currentFilters.lat && currentFilters.lng) {
        setSelectedLocation({
          lat: parseFloat(currentFilters.lat),
          lng: parseFloat(currentFilters.lng),
          name: currentFilters.locationName,
        });
      }
    }
    setRadius(currentFilters.radius || "25");
  }, [currentFilters]);

  // Close on click outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        panelRef.current &&
        !panelRef.current.contains(event.target as Node)
      ) {
        // Check if click is on the filter button (parent handles this)
        const target = event.target as HTMLElement;
        if (!target.closest("[data-filter-button]")) {
          onClose();
        }
      }
    };

    if (show) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [show, onClose]);

  const handlePlaceSelect = (place: PlaceDetails) => {
    if (place.geometry?.latitude && place.geometry?.longitude) {
      const locationName = place.formattedAddress || locationInput;
      setSelectedLocation({
        lat: place.geometry.latitude,
        lng: place.geometry.longitude,
        name: locationName,
      });
      setLocationInput(locationName);
    }
  };

  const handleApply = () => {
    if (selectedLocation) {
      onApplyFilters({
        lat: selectedLocation.lat.toString(),
        lng: selectedLocation.lng.toString(),
        radius,
        locationName: selectedLocation.name,
      });
    }
    onClose();
  };

  const handleClear = () => {
    setLocationInput("");
    setSelectedLocation(null);
    setRadius("25");
    onApplyFilters({
      lat: "",
      lng: "",
      radius: "",
      locationName: "",
    });
    onClose();
  };

  if (!show) return null;

  return (
    <>
      <style>{`
        .filter-panel {
          position: absolute;
          top: 100%;
          right: 0;
          width: 320px;
          min-width: 320px;
          background: white;
          border: 1px solid rgba(0, 0, 0, 0.15);
          border-radius: 0.5rem;
          box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
          z-index: 1050;
          margin-top: 0.5rem;
          opacity: 0;
          transform: translateY(-10px);
          animation: filterPanelSlideDown 0.2s ease forwards;
        }

        @keyframes filterPanelSlideDown {
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        @media (max-width: 576px) {
          .filter-panel {
            position: fixed;
            width: calc(100vw - 2rem);
            min-width: unset;
            left: 1rem;
            right: 1rem;
            top: auto;
            margin-top: 0.5rem;
          }
        }
      `}</style>

      <div ref={panelRef} className="filter-panel">
        <div className="p-3">
          <div className="mb-3">
            <label className="form-label fw-medium mb-2">Location</label>
            <AddressAutocomplete
              value={locationInput}
              onChange={setLocationInput}
              onPlaceSelect={handlePlaceSelect}
              placeholder="City, ZIP Code, or Address"
              types={["(regions)"]}
              countryRestriction="us"
              id="filter-location"
            />
            {selectedLocation && (
              <div className="mt-2 small text-muted d-flex align-items-center">
                <i className="bi bi-check-circle text-success me-1"></i>
                {selectedLocation.name}
              </div>
            )}
          </div>

          <div className="mb-3">
            <label className="form-label fw-medium mb-2">Search Radius</label>
            <select
              className="form-select"
              value={radius}
              onChange={(e) => setRadius(e.target.value)}
            >
              {RADIUS_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
        </div>

        <div className="border-top p-3 d-flex justify-content-between">
          <button
            type="button"
            className="btn btn-link text-muted text-decoration-none px-0"
            onClick={handleClear}
          >
            Clear all
          </button>
          <button
            type="button"
            className="btn btn-primary"
            onClick={handleApply}
            disabled={!selectedLocation}
          >
            Apply
          </button>
        </div>
      </div>
    </>
  );
};

export default FilterPanel;
