/**
 * Store Finder Component
 * 
 * Modern store locator with advanced features:
 * - Real-time search with autocomplete
 * - Distance-based filtering
 * - Interactive map view
 * - List/Map toggle
 * - Current location detection
 */

import { useState, useEffect, useCallback, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { 
    Search, 
    MapPin, 
    Navigation, 
    Phone, 
    Mail, 
    Globe, 
    Clock,
    Filter,
    ChevronRight,
    Map,
    List,
    Star,
    Car,
    Wifi,
    Zap,
    Coffee
} from 'lucide-react';

interface Location {
    id: string;
    name: string;
    address: string;
    city: string;
    state: string;
    postalCode: string;
    country: string;
    phone: string;
    email: string;
    website: string;
    latitude: number;
    longitude: number;
    distance?: number;
    hours?: any;
    amenities?: {
        wifi?: boolean;
        parking?: boolean;
        wheelchair?: boolean;
        evCharging?: boolean;
        delivery?: boolean;
    };
    rating?: number;
    reviewCount?: number;
}

interface StoreFinderProps {
    maxResults?: number;
    defaultRadius?: number;
    showMap?: boolean;
    showFilters?: boolean;
    categories?: string[];
    mapHeight?: string;
}

const StoreFinder: React.FC<StoreFinderProps> = ({
    maxResults = 10,
    defaultRadius = 25,
    showMap = true,
    showFilters = true,
    categories = [],
    mapHeight = '400px'
}) => {
    const [locations, setLocations] = useState<Location[]>([]);
    const [filteredLocations, setFilteredLocations] = useState<Location[]>([]);
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedLocation, setSelectedLocation] = useState<Location | null>(null);
    const [viewMode, setViewMode] = useState<'list' | 'map'>(showMap ? 'map' : 'list');
    const [loading, setLoading] = useState(false);
    const [userLocation, setUserLocation] = useState<{ lat: number; lng: number } | null>(null);
    const [radius, setRadius] = useState(defaultRadius);
    const [filters, setFilters] = useState({
        openNow: false,
        hasParking: false,
        hasWifi: false,
        hasEvCharging: false,
        wheelchairAccessible: false
    });
    const [suggestions, setSuggestions] = useState<string[]>([]);
    const [showSuggestions, setShowSuggestions] = useState(false);
    const searchInputRef = useRef<HTMLInputElement>(null);
    const mapRef = useRef<any>(null);
    const markersRef = useRef<any[]>([]);

    useEffect(() => {
        loadLocations();
        detectUserLocation();
    }, []);

    useEffect(() => {
        filterLocations();
    }, [searchQuery, radius, filters, locations, userLocation]);

    const loadLocations = async () => {
        setLoading(true);
        try {
            const response = await apiFetch({
                path: '/prorank-seo/v1/local-seo/locations',
                method: 'GET'
            });
            setLocations(response.data || []);
        } catch (error) {
            console.error('Failed to load locations:', error);
        } finally {
            setLoading(false);
        }
    };

    const detectUserLocation = () => {
        if ('geolocation' in navigator) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    setUserLocation({
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    });
                },
                () => {
                    // Ignore geolocation failures (user may deny permission).
                }
            );
        }
    };

    const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
        const R = 3959; // Earth's radius in miles
        const dLat = (lat2 - lat1) * Math.PI / 180;
        const dLon = (lon2 - lon1) * Math.PI / 180;
        const a = 
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
            Math.sin(dLon/2) * Math.sin(dLon/2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return R * c;
    };

    const filterLocations = () => {
        let filtered = [...locations];

        // Search filter
        if (searchQuery) {
            const query = searchQuery.toLowerCase();
            filtered = filtered.filter(loc => 
                loc.name.toLowerCase().includes(query) ||
                loc.address.toLowerCase().includes(query) ||
                loc.city.toLowerCase().includes(query) ||
                loc.state.toLowerCase().includes(query) ||
                loc.postalCode.includes(query)
            );
        }

        // Distance filter
        if (userLocation) {
            filtered = filtered.map(loc => ({
                ...loc,
                distance: calculateDistance(
                    userLocation.lat,
                    userLocation.lng,
                    loc.latitude || 0,
                    loc.longitude || 0
                )
            }));

            filtered = filtered.filter(loc => (loc.distance || 0) <= radius);
            filtered.sort((a, b) => (a.distance || 0) - (b.distance || 0));
        }

        // Amenity filters
        if (filters.hasParking) {
            filtered = filtered.filter(loc => loc.amenities?.parking);
        }
        if (filters.hasWifi) {
            filtered = filtered.filter(loc => loc.amenities?.wifi);
        }
        if (filters.hasEvCharging) {
            filtered = filtered.filter(loc => loc.amenities?.evCharging);
        }
        if (filters.wheelchairAccessible) {
            filtered = filtered.filter(loc => loc.amenities?.wheelchair);
        }

        // Open now filter
        if (filters.openNow) {
            filtered = filtered.filter(loc => isOpenNow(loc));
        }

        // Limit results
        filtered = filtered.slice(0, maxResults);

        setFilteredLocations(filtered);
    };

    const isOpenNow = (location: Location): boolean => {
        if (!location.hours) return false;
        
        const now = new Date();
        const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        const currentDay = dayNames[now.getDay()];
        const currentTime = now.getHours() * 60 + now.getMinutes();
        
        const todayHours = location.hours[currentDay];
        if (!todayHours || todayHours === 'Closed') return false;
        
        // Parse hours like "9:00 AM - 5:00 PM"
        const match = todayHours.match(/(\d{1,2}):(\d{2})\s*(AM|PM)\s*-\s*(\d{1,2}):(\d{2})\s*(AM|PM)/i);
        if (!match) return false;
        
        let openHour = parseInt(match[1]);
        const openMin = parseInt(match[2]);
        if (match[3].toUpperCase() === 'PM' && openHour !== 12) openHour += 12;
        if (match[3].toUpperCase() === 'AM' && openHour === 12) openHour = 0;
        
        let closeHour = parseInt(match[4]);
        const closeMin = parseInt(match[5]);
        if (match[6].toUpperCase() === 'PM' && closeHour !== 12) closeHour += 12;
        if (match[6].toUpperCase() === 'AM' && closeHour === 12) closeHour = 0;
        
        const openTime = openHour * 60 + openMin;
        const closeTime = closeHour * 60 + closeMin;
        
        return currentTime >= openTime && currentTime <= closeTime;
    };

    const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        setSearchQuery(value);
        
        // Generate suggestions
        if (value.length > 2) {
            const cities = [...new Set(locations.map(l => l.city))];
            const states = [...new Set(locations.map(l => l.state))];
            const allSuggestions = [...cities, ...states].filter(s => 
                s.toLowerCase().includes(value.toLowerCase())
            );
            setSuggestions(allSuggestions.slice(0, 5));
            setShowSuggestions(true);
        } else {
            setShowSuggestions(false);
        }
    };

    const handleSuggestionClick = (suggestion: string) => {
        setSearchQuery(suggestion);
        setShowSuggestions(false);
    };

    const getDirections = (location: Location) => {
        const destination = encodeURIComponent(
            `${location.address}, ${location.city}, ${location.state} ${location.postalCode}`
        );
        
        if (userLocation) {
            const origin = `${userLocation.lat},${userLocation.lng}`;
            window.open(
                `https://www.google.com/maps/dir/${origin}/${destination}`,
                '_blank'
            );
        } else {
            window.open(
                `https://www.google.com/maps/search/${destination}`,
                '_blank'
            );
        }
    };

    const LocationCard = ({ location }: { location: Location }) => (
        <div 
            className="prorank-location-card"
            onClick={() => setSelectedLocation(location)}
        >
            <div className="location-header">
                <h3>{location.name}</h3>
                {location.distance && (
                    <span className="distance-badge">
                        {location.distance.toFixed(1)} mi
                    </span>
                )}
            </div>
            
            <div className="location-address">
                <MapPin className="pr:w-4 pr:h-4" />
                <div>
                    <p>{location.address}</p>
                    <p>{location.city}, {location.state} {location.postalCode}</p>
                </div>
            </div>

            {location.phone && (
                <div className="location-contact">
                    <Phone className="pr:w-4 pr:h-4" />
                    <a href={`tel:${location.phone}`}>{location.phone}</a>
                </div>
            )}

            {location.rating && (
                <div className="location-rating">
                    <Star className="pr:w-4 pr:h-4 pr:fill-current pr:text-yellow-500" />
                    <span>{location.rating.toFixed(1)}</span>
                    <span className="review-count">({location.reviewCount} reviews)</span>
                </div>
            )}

            <div className="location-amenities">
                {location.amenities?.wifi && (
                    <span className="amenity-badge" title="WiFi Available">
                        <Wifi className="pr:w-4 pr:h-4" />
                    </span>
                )}
                {location.amenities?.parking && (
                    <span className="amenity-badge" title="Parking Available">
                        <Car className="pr:w-4 pr:h-4" />
                    </span>
                )}
                {location.amenities?.evCharging && (
                    <span className="amenity-badge" title="EV Charging">
                        <Zap className="pr:w-4 pr:h-4" />
                    </span>
                )}
            </div>

            <div className="location-actions">
                <button 
                    className="prorank-btn-small"
                    onClick={(e) => {
                        e.stopPropagation();
                        getDirections(location);
                    }}
                >
                    <Navigation className="pr:w-4 pr:h-4" />
                    Get Directions
                </button>
                {location.website && (
                    <a 
                        href={location.website}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="prorank-btn-small secondary"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <Globe className="pr:w-4 pr:h-4" />
                        Website
                    </a>
                )}
            </div>
        </div>
    );

    return (
        <div className="prorank-store-finder">
            {/* Search Bar */}
            <div className="store-finder-search">
                <div className="search-input-wrapper">
                    <Search className="search-icon" />
                    <input
                        ref={searchInputRef}
                        type="text"
                        placeholder={__('Search by city, state, or zip code...', 'prorank-seo')}
                        value={searchQuery}
                        onChange={handleSearchChange}
                        className="search-input"
                    />
                    {userLocation && (
                        <button 
                            className="location-btn"
                            onClick={detectUserLocation}
                            title="Use my location"
                        >
                            <Navigation className="pr:w-5 pr:h-5" />
                        </button>
                    )}
                </div>
                
                {showSuggestions && suggestions.length > 0 && (
                    <div className="search-suggestions">
                        {suggestions.map((suggestion, index) => (
                            <div
                                key={index}
                                className="suggestion-item"
                                onClick={() => handleSuggestionClick(suggestion)}
                            >
                                <MapPin className="pr:w-4 pr:h-4" />
                                {suggestion}
                            </div>
                        ))}
                    </div>
                )}
            </div>

            {/* Filters */}
            {showFilters && (
                <div className="store-finder-filters">
                    <div className="filter-group">
                        <label>
                            {__('Within', 'prorank-seo')}
                            <select 
                                value={radius} 
                                onChange={(e) => setRadius(Number(e.target.value))}
                                className="radius-select"
                            >
                                <option value="5">5 miles</option>
                                <option value="10">10 miles</option>
                                <option value="25">25 miles</option>
                                <option value="50">50 miles</option>
                                <option value="100">100 miles</option>
                            </select>
                        </label>
                    </div>

                    <div className="filter-group">
                        <label className="filter-checkbox">
                              <input
                                type="checkbox"
                                checked={filters.openNow}
                                onChange={(value) => setFilters({...filters, openNow: value?.target ? value.target.checked : !!value})}
                              />
                            <Clock className="pr:w-4 pr:h-4" />
                            {__('Open Now', 'prorank-seo')}
                        </label>
                    </div>

                    <div className="filter-group">
                        <label className="filter-checkbox">
                              <input
                                type="checkbox"
                                checked={filters.hasWifi}
                                onChange={(value) => setFilters({...filters, hasWifi: value?.target ? value.target.checked : !!value})}
                              />
                            <Wifi className="pr:w-4 pr:h-4" />
                            {__('WiFi', 'prorank-seo')}
                        </label>
                    </div>

                    <div className="filter-group">
                        <label className="filter-checkbox">
                              <input
                                type="checkbox"
                                checked={filters.hasParking}
                                onChange={(value) => setFilters({...filters, hasParking: value?.target ? value.target.checked : !!value})}
                              />
                            <Car className="pr:w-4 pr:h-4" />
                            {__('Parking', 'prorank-seo')}
                        </label>
                    </div>

                    <div className="filter-group">
                        <label className="filter-checkbox">
                              <input
                                type="checkbox"
                                checked={filters.hasEvCharging}
                                onChange={(value) => setFilters({...filters, hasEvCharging: value?.target ? value.target.checked : !!value})}
                              />
                            <Zap className="pr:w-4 pr:h-4" />
                            {__('EV Charging', 'prorank-seo')}
                        </label>
                    </div>
                </div>
            )}

            {/* View Mode Toggle */}
            {showMap && (
                <div className="view-mode-toggle">
                    <button
                        className={`view-btn ${viewMode === 'list' ? 'active' : ''}`}
                        onClick={() => setViewMode('list')}
                    >
                        <List className="pr:w-4 pr:h-4" />
                        {__('List', 'prorank-seo')}
                    </button>
                    <button
                        className={`view-btn ${viewMode === 'map' ? 'active' : ''}`}
                        onClick={() => setViewMode('map')}
                    >
                        <Map className="pr:w-4 pr:h-4" />
                        {__('Map', 'prorank-seo')}
                    </button>
                </div>
            )}

            {/* Results */}
            <div className="store-finder-results">
                {loading ? (
                    <div className="loading-spinner">
                        {__('Loading locations...', 'prorank-seo')}
                    </div>
                ) : filteredLocations.length === 0 ? (
                    <div className="no-results">
                        <MapPin className="pr:w-12 pr:h-12 pr:text-gray-400" />
                        <p>{__('No locations found matching your criteria', 'prorank-seo')}</p>
                        <button 
                            onClick={() => {
                                setSearchQuery('');
                                setFilters({
                                    openNow: false,
                                    hasParking: false,
                                    hasWifi: false,
                                    hasEvCharging: false,
                                    wheelchairAccessible: false
                                });
                            }}
                            className="reset-btn"
                        >
                            {__('Clear Filters', 'prorank-seo')}
                        </button>
                    </div>
                ) : viewMode === 'list' ? (
                    <div className="locations-list">
                        {filteredLocations.map((location) => (
                            <LocationCard key={location.id} location={location} />
                        ))}
                    </div>
                ) : (
                    <div className="locations-map" style={{ height: mapHeight }}>
                        <div ref={mapRef} className="map-container" />
                        {selectedLocation && (
                            <div className="map-info-panel">
                                <LocationCard location={selectedLocation} />
                            </div>
                        )}
                    </div>
                )}
            </div>

            <style jsx>{`
                .prorank-store-finder {
                    max-width: 1200px;
                    margin: 0 auto;
                    padding: 20px;
                }

                .store-finder-search {
                    position: relative;
                    margin-bottom: 20px;
                }

                .search-input-wrapper {
                    position: relative;
                    display: flex;
                    align-items: center;
                }

                .search-icon {
                    position: absolute;
                    left: 15px;
                    width: 20px;
                    height: 20px;
                    color: #6b7280;
                }

                .search-input {
                    width: 100%;
                    padding: 12px 50px 12px 45px;
                    border: 2px solid #e5e7eb;
                    border-radius: 8px;
                    font-size: 16px;
                    transition: all 0.3s;
                }

                .search-input:focus {
                    outline: none;
                    border-color: var(--prorank-primary);
                    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
                }

                .location-btn {
                    position: absolute;
                    right: 10px;
                    padding: 8px;
                    background: var(--prorank-primary);
                    color: white;
                    border: none;
                    border-radius: 6px;
                    cursor: pointer;
                }

                .search-suggestions {
                    position: absolute;
                    top: 100%;
                    left: 0;
                    right: 0;
                    background: white;
                    border: 1px solid #e5e7eb;
                    border-radius: 8px;
                    margin-top: 4px;
                    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                    z-index: 10;
                }

                .suggestion-item {
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    padding: 12px 15px;
                    cursor: pointer;
                    transition: background 0.2s;
                }

                .suggestion-item:hover {
                    background: #f3f4f6;
                }

                .store-finder-filters {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 15px;
                    margin-bottom: 20px;
                    padding: 15px;
                    background: #f9fafb;
                    border-radius: 8px;
                }

                .filter-group label {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    cursor: pointer;
                }

                .filter-checkbox {
                    display: flex;
                    align-items: center;
                    gap: 5px;
                }

                .radius-select {
                    margin-left: 8px;
                    padding: 5px 10px;
                    border: 1px solid #d1d5db;
                    border-radius: 4px;
                }

                .view-mode-toggle {
                    display: flex;
                    gap: 10px;
                    margin-bottom: 20px;
                }

                .view-btn {
                    display: flex;
                    align-items: center;
                    gap: 5px;
                    padding: 8px 16px;
                    background: white;
                    border: 2px solid #e5e7eb;
                    border-radius: 6px;
                    cursor: pointer;
                    transition: all 0.3s;
                }

                .view-btn.active {
                    background: var(--prorank-primary);
                    color: white;
                    border-color: var(--prorank-primary);
                }

                .locations-list {
                    display: grid;
                    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
                    gap: 20px;
                }

                .prorank-location-card {
                    background: white;
                    border: 1px solid #e5e7eb;
                    border-radius: 8px;
                    padding: 20px;
                    cursor: pointer;
                    transition: all 0.3s;
                }

                .prorank-location-card:hover {
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                    transform: translateY(-2px);
                }

                .location-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: start;
                    margin-bottom: 15px;
                }

                .location-header h3 {
                    margin: 0;
                    font-size: 18px;
                    font-weight: 600;
                }

                .distance-badge {
                    background: var(--prorank-primary);
                    color: white;
                    padding: 4px 8px;
                    border-radius: 4px;
                    font-size: 12px;
                    font-weight: 500;
                }

                .location-address,
                .location-contact {
                    display: flex;
                    gap: 10px;
                    margin-bottom: 10px;
                    color: #6b7280;
                }

                .location-rating {
                    display: flex;
                    align-items: center;
                    gap: 5px;
                    margin-bottom: 10px;
                }

                .review-count {
                    color: #6b7280;
                    font-size: 14px;
                }

                .location-amenities {
                    display: flex;
                    gap: 8px;
                    margin-bottom: 15px;
                }

                .amenity-badge {
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    width: 32px;
                    height: 32px;
                    background: #f3f4f6;
                    border-radius: 6px;
                    color: #4b5563;
                }

                .location-actions {
                    display: flex;
                    gap: 10px;
                }

                .prorank-btn-small {
                    display: inline-flex;
                    align-items: center;
                    gap: 5px;
                    padding: 8px 12px;
                    background: var(--prorank-primary);
                    color: white;
                    border: none;
                    border-radius: 6px;
                    font-size: 14px;
                    cursor: pointer;
                    text-decoration: none;
                    transition: opacity 0.3s;
                }

                .prorank-btn-small:hover {
                    opacity: 0.9;
                }

                .prorank-btn-small.secondary {
                    background: white;
                    color: var(--prorank-primary);
                    border: 1px solid var(--prorank-primary);
                }

                .map-container {
                    width: 100%;
                    height: 100%;
                    border-radius: 8px;
                    overflow: hidden;
                }

                .map-info-panel {
                    position: absolute;
                    top: 20px;
                    right: 20px;
                    width: 350px;
                    max-height: 80%;
                    overflow-y: auto;
                    background: white;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                }

                .loading-spinner,
                .no-results {
                    text-align: center;
                    padding: 60px 20px;
                }

                .reset-btn {
                    margin-top: 20px;
                    padding: 10px 20px;
                    background: var(--prorank-primary);
                    color: white;
                    border: none;
                    border-radius: 6px;
                    cursor: pointer;
                }

                @media (max-width: 768px) {
                    .locations-list {
                        grid-template-columns: 1fr;
                    }

                    .map-info-panel {
                        position: relative;
                        top: auto;
                        right: auto;
                        width: 100%;
                        margin-top: 20px;
                    }
                }
            `}</style>
        </div>
    );
};

export default StoreFinder;
