import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Map, MapMarker } from './Map';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useGeolocation } from '@/hooks/useGeolocation';
import { geolocationService } from '@/services/geolocationService';
import { MapPin, Navigation, Phone, Clock, Star } from 'lucide-react';

interface Pharmacy {
  id: string;
  name: string;
  address: string;
  phone: string;
  lat: number;
  lng: number;
  isOpen: boolean;
  rating: number;
  distance?: number;
  duration?: number;
  hasStock?: boolean;
  medicines?: string[];
}

interface PharmacyMapProps {
  medicineName?: string;
  userLocation?: { lat: number; lng: number };
  onPharmacySelect?: (pharmacy: Pharmacy) => void;
  selectedPharmacyId?: string;
  height?: string;
  showFilters?: boolean;
}

export function PharmacyMap({ 
  medicineName, 
  userLocation, 
  onPharmacySelect,
  selectedPharmacyId,
  height = '400px',
  showFilters = true
}: PharmacyMapProps) {
  const [radius, setRadius] = useState(5); // km
  const [showOpenOnly, setShowOpenOnly] = useState(false);
  const [showStockOnly, setShowStockOnly] = useState(false);
  
  const { location: currentLocation, getCurrentLocation, isLoading: isGettingLocation } = useGeolocation();
  
  const centerLocation = userLocation || currentLocation || geolocationService.getAbidjanCenter();

  // Fetch nearby pharmacies
  const { data: pharmacies = [], isLoading } = useQuery<Pharmacy[]>({
    queryKey: ['/api/pharmacies/nearby', centerLocation, radius, medicineName],
    enabled: !!centerLocation,
  });

  // Filter pharmacies
  const filteredPharmacies = pharmacies.filter(pharmacy => {
    if (showOpenOnly && !pharmacy.isOpen) return false;
    if (showStockOnly && medicineName && !pharmacy.hasStock) return false;
    return true;
  });

  // Add distance calculations to pharmacies
  const pharmaciesWithDistance = filteredPharmacies.map(pharmacy => {
    if (centerLocation) {
      const result = geolocationService.calculateDistance(centerLocation, pharmacy);
      return {
        ...pharmacy,
        distance: result.distance,
        duration: result.duration
      };
    }
    return pharmacy;
  }).sort((a, b) => (a.distance || 0) - (b.distance || 0));

  // Create map markers
  const markers: MapMarker[] = [];

  // Add user location marker
  if (centerLocation) {
    markers.push({
      id: 'user',
      lat: centerLocation.lat,
      lng: centerLocation.lng,
      title: 'Votre position',
      type: 'client',
      info: 'Position actuelle',
      isActive: false
    });
  }

  // Add pharmacy markers
  pharmaciesWithDistance.forEach(pharmacy => {
    markers.push({
      id: pharmacy.id,
      lat: pharmacy.lat,
      lng: pharmacy.lng,
      title: pharmacy.name,
      type: 'pharmacy',
      address: pharmacy.address,
      distance: pharmacy.distance,
      duration: pharmacy.duration,
      info: `${pharmacy.isOpen ? '🟢 Ouverte' : '🔴 Fermée'} • ${pharmacy.rating}⭐`,
      isActive: pharmacy.id === selectedPharmacyId,
      onClick: () => onPharmacySelect?.(pharmacy)
    });
  });

  const handleGetCurrentLocation = async () => {
    try {
      await getCurrentLocation();
    } catch (error) {
      console.error('Failed to get current location:', error);
    }
  };

  return (
    <div className="space-y-4">
      {/* Filters */}
      {showFilters && (
        <Card>
          <CardHeader className="pb-4">
            <CardTitle className="text-lg">Pharmacies à proximité</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex flex-wrap gap-3">
              <Button
                variant="outline"
                size="sm"
                onClick={handleGetCurrentLocation}
                disabled={isGettingLocation}
                className="flex items-center gap-2"
              >
                <Navigation className="h-4 w-4" />
                {isGettingLocation ? 'Localisation...' : 'Ma position'}
              </Button>
              
              <select 
                value={radius} 
                onChange={(e) => setRadius(Number(e.target.value))}
                className="px-3 py-1 border rounded text-sm"
              >
                <option value={2}>2 km</option>
                <option value={5}>5 km</option>
                <option value={10}>10 km</option>
                <option value={20}>20 km</option>
              </select>

              <Button
                variant={showOpenOnly ? "default" : "outline"}
                size="sm"
                onClick={() => setShowOpenOnly(!showOpenOnly)}
              >
                Ouvertes seulement
              </Button>

              {medicineName && (
                <Button
                  variant={showStockOnly ? "default" : "outline"}
                  size="sm"
                  onClick={() => setShowStockOnly(!showStockOnly)}
                >
                  En stock seulement
                </Button>
              )}
            </div>

            {medicineName && (
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium">Recherche:</span>
                <Badge variant="secondary">{medicineName}</Badge>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Map */}
      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <div 
              className="flex items-center justify-center bg-gray-50"
              style={{ height }}
            >
              <div className="text-center">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
                <p className="text-sm text-muted-foreground">Chargement des pharmacies...</p>
              </div>
            </div>
          ) : (
            <Map
              center={[centerLocation.lat, centerLocation.lng]}
              zoom={13}
              markers={markers}
              height={height}
              showUserLocation={false}
              interactive={true}
            />
          )}
        </CardContent>
      </Card>

      {/* Pharmacy List */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <MapPin className="h-5 w-5" />
            Pharmacies trouvées ({pharmaciesWithDistance.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {pharmaciesWithDistance.length === 0 ? (
            <div className="text-center py-8">
              <MapPin className="h-12 w-12 text-gray-300 mx-auto mb-4" />
              <p className="text-gray-500">Aucune pharmacie trouvée dans cette zone</p>
              <Button 
                variant="outline" 
                onClick={() => setRadius(radius * 2)}
                className="mt-2"
              >
                Élargir la recherche
              </Button>
            </div>
          ) : (
            <div className="space-y-3">
              {pharmaciesWithDistance.slice(0, 10).map(pharmacy => (
                <div
                  key={pharmacy.id}
                  className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                    pharmacy.id === selectedPharmacyId 
                      ? 'border-blue-500 bg-blue-50' 
                      : 'hover:bg-gray-50'
                  }`}
                  onClick={() => onPharmacySelect?.(pharmacy)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h3 className="font-medium">{pharmacy.name}</h3>
                        <Badge 
                          variant={pharmacy.isOpen ? "default" : "destructive"}
                          className="text-xs"
                        >
                          {pharmacy.isOpen ? 'Ouverte' : 'Fermée'}
                        </Badge>
                        {pharmacy.hasStock && medicineName && (
                          <Badge variant="secondary" className="text-xs">
                            En stock
                          </Badge>
                        )}
                      </div>
                      
                      <p className="text-sm text-muted-foreground mb-2">
                        📍 {pharmacy.address}
                      </p>
                      
                      <div className="flex items-center gap-4 text-sm">
                        {pharmacy.distance && (
                          <span className="flex items-center gap-1 text-blue-600">
                            📏 {geolocationService.formatDistance(pharmacy.distance)}
                          </span>
                        )}
                        {pharmacy.duration && (
                          <span className="flex items-center gap-1 text-green-600">
                            ⏱️ {geolocationService.formatDuration(pharmacy.duration)}
                          </span>
                        )}
                        <span className="flex items-center gap-1 text-yellow-600">
                          <Star className="h-3 w-3 fill-current" />
                          {pharmacy.rating}
                        </span>
                      </div>
                    </div>
                    
                    <div className="flex flex-col gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        className="flex items-center gap-1"
                        onClick={(e) => {
                          e.stopPropagation();
                          window.open(`tel:${pharmacy.phone}`, '_self');
                        }}
                      >
                        <Phone className="h-3 w-3" />
                        Appeler
                      </Button>
                      
                      {pharmacy.id === selectedPharmacyId && (
                        <Badge variant="default" className="text-xs text-center">
                          Sélectionnée
                        </Badge>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}