import { useState, useEffect } from 'react';
import { MapPin } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';

interface PersonalLocationDisplayProps {
  personalLocation: string;
  userId: string;
  isOwnProfile: boolean;
}

export function PersonalLocationDisplay({ personalLocation, userId, isOwnProfile }: PersonalLocationDisplayProps) {
  const [showLocation, setShowLocation] = useState(false);

  useEffect(() => {
    fetchLocationPrivacy();
  }, [userId, isOwnProfile]);

  const fetchLocationPrivacy = async () => {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      const viewerId = user?.id;

      // Use the secure function to check location visibility
      const { data, error } = await supabase
        .rpc('can_view_user_location', {
          _viewer_id: viewerId,
          _profile_user_id: userId
        });

      if (error) {
        console.error('Error checking location privacy:', error);
        setShowLocation(false);
        return;
      }

      setShowLocation(data || false);
    } catch (error) {
      console.error('Error fetching location privacy:', error);
      setShowLocation(false);
    }
  };

  if (!showLocation || !personalLocation) {
    return null;
  }

  return (
    <div className="flex items-center gap-1">
      <MapPin className="w-4 h-4" />
      {personalLocation}
    </div>
  );
}