import React, { useEffect, useRef, useState } from 'react';
import { Modal, Input, Button, Typography, Spin, notification } from 'antd';
import {
  AimOutlined,
  CheckOutlined,
  EnvironmentOutlined,
  FullscreenExitOutlined,
  FullscreenOutlined,
  LoadingOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { useDebounce } from 'use-debounce';

const { Text } = Typography;

export interface LocationPayload {
  latitude: number;
  longitude: number;
  name?: string;
  address?: string;
}

interface SendLocationModalProps {
  open: boolean;
  sending: boolean;
  onCancel: () => void;
  onSend: (location: LocationPayload) => void;
}

interface PlaceOption {
  key: string;
  title: string;
  subtitle: string;
  // Search results only get coordinates once picked (Place Details); the current location has them already
  placeId?: string;
  latitude: number | null;
  longitude: number | null;
  isCurrent?: boolean;
  // A point the user dragged the pin to (or clicked on the map)
  isPin?: boolean;
  // Radius in metres the browser says its position could be off by (current location only)
  accuracy?: number;
}

// Google Maps Platform. The key is a browser key: restrict it by HTTP referrer and to the APIs below in Google Cloud.
//   Places API (New)       - search suggestions + place details
//   Maps JavaScript API    - the interactive map (draggable pin) and the geocoder (the Geocoding web service
//                            rejects website-restricted keys)
//   Geocoding API          - used by the JavaScript geocoder for addresses
const GOOGLE_MAPS_API_KEY = process.env.GOOGLE_MAPS_API_KEY || '';
// Advanced markers need a Map ID. Google's DEMO_MAP_ID works for development; for production create your own
// (Google Cloud Console > Google Maps Platform > Map Management) and set NEXT_PUBLIC_GOOGLE_MAPS_MAP_ID.
const GOOGLE_MAPS_MAP_ID = process.env.NEXT_PUBLIC_GOOGLE_MAPS_MAP_ID || 'DEMO_MAP_ID';
const PLACES_URL = 'https://places.googleapis.com/v1';
const MIN_QUERY_LENGTH = 3;
const BIAS_RADIUS_METERS = 50000; // maximum Google accepts for a circle bias

const newSessionToken = (): string =>
  typeof crypto !== 'undefined' && 'randomUUID' in crypto
    ? crypto.randomUUID()
    : `${Date.now()}-${Math.random().toString(16).slice(2)}`;

const googleErrorText = (data: any, fallback: string): string =>
  data?.error?.message || data?.error_message || fallback;

// Loads the Maps JavaScript API once (needed for the geocoder), using Google's recommended async loading
let googleMapsLoader: Promise<any> | null = null;
const loadGoogleMaps = (): Promise<any> => {
  const w = window as any;
  if (w.google?.maps?.importLibrary) return Promise.resolve(w.google);
  if (googleMapsLoader) return googleMapsLoader;
  googleMapsLoader = new Promise((resolve, reject) => {
    const callbackName = '__googleMapsReady';
    w[callbackName] = () => resolve(w.google);
    const script = document.createElement('script');
    script.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&loading=async&callback=${callbackName}`;
    script.async = true;
    script.onerror = () => {
      googleMapsLoader = null;
      reject(new Error('Could not load Google Maps'));
    };
    document.head.appendChild(script);
  });
  return googleMapsLoader;
};

// Advanced markers hand back either a LatLng object or a plain { lat, lng }; normalise to numbers
const toLatLngLiteral = (point: any): { lat: number; lng: number } => ({
  lat: typeof point.lat === 'function' ? point.lat() : point.lat,
  lng: typeof point.lng === 'function' ? point.lng() : point.lng,
});

// Street address for a coordinate, or null if Google can't resolve it
const reverseGeocode = async (latitude: number, longitude: number): Promise<string | null> => {
  const google = await loadGoogleMaps();
  // With async loading, libraries are fetched on demand
  const { Geocoder } = await google.maps.importLibrary('geocoding');
  const { results } = await new Geocoder().geocode({ location: { lat: latitude, lng: longitude } });
  if (!results?.length) return null;
  // Google lists results from most to least specific, but the first can be a Plus Code or a broad area.
  // Prefer an actual street address, then anything that isn't a Plus Code.
  const streetLevel = ['street_address', 'premise', 'subpremise', 'route', 'intersection'];
  const best =
    results.find((r: any) => r.types?.some((t: string) => streetLevel.includes(t))) ||
    results.find((r: any) => !r.types?.includes('plus_code')) ||
    results[0];
  return best.formatted_address || null;
};

interface LocationMapProps {
  latitude: number;
  longitude: number;
  // Changes when a different place is selected from the list (drag/click moves keep the key 'pin')
  focusKey: string;
  expanded: boolean;
  onToggleExpand: () => void;
  onMove: (latitude: number, longitude: number) => void;
}

// Interactive Google map: drag the pin or click the map to choose a point
function LocationMap({ latitude, longitude, focusKey, expanded, onToggleExpand, onMove }: LocationMapProps) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const mapRef = useRef<any>(null);
  const markerRef = useRef<any>(null);
  const lastFocusKeyRef = useRef<string>(focusKey);
  const latestRef = useRef({ latitude, longitude, focusKey });
  const onMoveRef = useRef(onMove);
  const [error, setError] = useState('');

  latestRef.current = { latitude, longitude, focusKey };
  useEffect(() => {
    onMoveRef.current = onMove;
  }, [onMove]);

  // Create the map once
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const google = await loadGoogleMaps();
        const { Map: GoogleMap } = await google.maps.importLibrary('maps');
        const { AdvancedMarkerElement } = await google.maps.importLibrary('marker');
        if (cancelled || !containerRef.current) return;
        const start = { lat: latestRef.current.latitude, lng: latestRef.current.longitude };
        const map = new GoogleMap(containerRef.current, {
          center: start,
          zoom: 16,
          mapId: GOOGLE_MAPS_MAP_ID,
          // Always let a drag pan the map and the wheel / pinch zoom it. Google's default ('auto') switches to
          // a "cooperative" mode on a scrollable page, where a one-finger drag or a plain scroll does nothing.
          gestureHandling: 'greedy',
          draggable: true,
          scrollwheel: true,
          streetViewControl: false,
          mapTypeControl: false,
          fullscreenControl: false,
          clickableIcons: false,
        });
        const marker = new AdvancedMarkerElement({ position: start, map, gmpDraggable: true });
        // google.maps.event.addListener rather than marker.addListener, which Google warns against on advanced markers
        google.maps.event.addListener(marker, 'dragend', () => {
          if (!marker.position) return;
          const { lat, lng } = toLatLngLiteral(marker.position);
          onMoveRef.current(lat, lng);
        });
        map.addListener('click', (event: any) => {
          if (!event?.latLng) return;
          marker.position = event.latLng;
          onMoveRef.current(event.latLng.lat(), event.latLng.lng());
        });
        mapRef.current = map;
        markerRef.current = marker;
        lastFocusKeyRef.current = latestRef.current.focusKey;
      } catch (err: any) {
        console.warn('Could not load the Google map:', err?.message || err);
        if (!cancelled) setError('The map could not be loaded.');
      }
    })();
    return () => {
      cancelled = true;
      mapRef.current = null;
      markerRef.current = null;
    };
  }, []);

  // Follow the selected location
  useEffect(() => {
    const map = mapRef.current;
    const marker = markerRef.current;
    if (!map || !marker) return;
    const position = { lat: latitude, lng: longitude };
    marker.position = position;
    if (focusKey === 'pin') {
      // The user moved the pin themselves: keep their zoom, only follow if it left the view
      const bounds = map.getBounds();
      if (bounds && !bounds.contains(position)) map.panTo(position);
    } else if (lastFocusKeyRef.current !== focusKey) {
      map.setCenter(position);
      map.setZoom(16);
    }
    lastFocusKeyRef.current = focusKey;
  }, [latitude, longitude, focusKey]);

  // Keep the pin in view when the map is maximized or restored
  useEffect(() => {
    const map = mapRef.current;
    const marker = markerRef.current;
    if (!map || !marker) return;
    const timer = setTimeout(() => {
      (window as any).google?.maps?.event?.trigger(map, 'resize');
      if (marker.position) map.setCenter(toLatLngLiteral(marker.position));
    }, 60);
    return () => clearTimeout(timer);
  }, [expanded]);

  return (
    <div>
      <div style={{ position: 'relative', height: expanded ? 420 : 180, background: '#e9edef' }}>
        <div ref={containerRef} style={{ width: '100%', height: '100%' }} />
        {error && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Text type="secondary">{error}</Text>
          </div>
        )}
        <Button
          size="small"
          icon={expanded ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
          onClick={onToggleExpand}
          title={expanded ? 'Minimize map' : 'Maximize map'}
          style={{ position: 'absolute', top: 8, right: 8, zIndex: 1 }}
        />
      </div>
      <div style={{ padding: '4px 16px', background: '#fafafa', borderBottom: '1px solid #f0f0f0' }}>
        <Text type="secondary" style={{ fontSize: 12 }}>
          Drag the pin or click on the map to adjust the location.
        </Text>
      </div>
    </div>
  );
}

export default function SendLocationModal({ open, sending, onCancel, onSend }: SendLocationModalProps) {
  const [currentPlace, setCurrentPlace] = useState<PlaceOption | null>(null);
  const [locating, setLocating] = useState(false);
  const [locationError, setLocationError] = useState('');

  const [query, setQuery] = useState('');
  const [debouncedQuery] = useDebounce(query.trim(), 500);
  const [results, setResults] = useState<PlaceOption[]>([]);
  const [searching, setSearching] = useState(false);
  const [searchError, setSearchError] = useState('');

  const [selected, setSelected] = useState<PlaceOption | null>(null);
  const [resolvingKey, setResolvingKey] = useState<string | null>(null);
  const [mapExpanded, setMapExpanded] = useState(false);
  const pinRequestRef = useRef(0);
  const searchAbortRef = useRef<AbortController | null>(null);
  // One session per search-then-pick, so Google bills the suggestions + the details together
  const sessionTokenRef = useRef<string>(newSessionToken());

  // Detect the current location whenever the modal opens and make it the default selection
  useEffect(() => {
    if (!open) return;
    setQuery('');
    setResults([]);
    setSearchError('');
    setCurrentPlace(null);
    setSelected(null);
    setResolvingKey(null);
    setMapExpanded(false);
    setLocationError('');
    sessionTokenRef.current = newSessionToken();

    if (!GOOGLE_MAPS_API_KEY) {
      setLocationError('Google Maps is not configured. Please contact admin.');
      return;
    }
    if (!navigator.geolocation) {
      setLocationError('Your browser does not support location access. Search for a place instead.');
      return;
    }

    let cancelled = false;
    setLocating(true);
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        const { latitude, longitude, accuracy } = position.coords;
        console.info(`Browser location: ${latitude}, ${longitude} (accuracy about ${Math.round(accuracy)} m)`);
        let subtitle = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;
        try {
          const address = await reverseGeocode(latitude, longitude);
          if (address) subtitle = address;
        } catch (error: any) {
          // coordinates are enough if the address lookup fails
          console.warn('Google reverse geocoding failed:', error?.code || '', error?.message || error);
        }
        if (cancelled) return;
        const place: PlaceOption = {
          key: 'current',
          title: 'Your current location',
          subtitle,
          latitude,
          longitude,
          isCurrent: true,
          accuracy,
        };
        setCurrentPlace(place);
        setSelected((prev) => prev ?? place);
        setLocating(false);
      },
      (error) => {
        if (cancelled) return;
        setLocating(false);
        setLocationError(
          error.code === error.PERMISSION_DENIED
            ? 'Location permission is blocked. Allow it in your browser, or search for a place instead.'
            : 'Could not get your current location. Search for a place instead.'
        );
      },
      { enableHighAccuracy: true, timeout: 10000 }
    );

    return () => {
      cancelled = true;
    };
  }, [open]);

  // Search suggestions as the user types (Places API New - Autocomplete)
  useEffect(() => {
    searchAbortRef.current?.abort();
    if (!open || !GOOGLE_MAPS_API_KEY || debouncedQuery.length < MIN_QUERY_LENGTH) {
      setResults([]);
      setSearching(false);
      setSearchError('');
      return;
    }

    const controller = new AbortController();
    searchAbortRef.current = controller;
    setSearching(true);
    setSearchError('');

    const body: any = { input: debouncedQuery, sessionToken: sessionTokenRef.current, languageCode: 'en' };
    if (currentPlace?.latitude != null && currentPlace?.longitude != null) {
      body.locationBias = {
        circle: {
          center: { latitude: currentPlace.latitude, longitude: currentPlace.longitude },
          radius: BIAS_RADIUS_METERS,
        },
      };
    }

    fetch(`${PLACES_URL}/places:autocomplete`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-Goog-Api-Key': GOOGLE_MAPS_API_KEY },
      body: JSON.stringify(body),
      signal: controller.signal,
    })
      .then(async (res) => {
        const data = await res.json();
        if (!res.ok) throw new Error(googleErrorText(data, 'Search failed'));
        return data;
      })
      .then((data: any) => {
        const options: PlaceOption[] = (data?.suggestions || [])
          .filter((s: any) => s?.placePrediction?.placeId)
          .map((s: any) => {
            const p = s.placePrediction;
            const fullText: string = p.text?.text || '';
            const title: string = p.structuredFormat?.mainText?.text || fullText.split(',')[0] || 'Location';
            return {
              key: p.placeId,
              placeId: p.placeId,
              title,
              subtitle: p.structuredFormat?.secondaryText?.text || '',
              latitude: null,
              longitude: null,
            };
          });
        setResults(options);
        setSearching(false);
      })
      .catch((error) => {
        if (error?.name === 'AbortError') return;
        console.warn('Google Places search failed:', error?.message);
        setSearching(false);
        setSearchError('Could not search locations right now. Please try again.');
      });

    return () => controller.abort();
  }, [debouncedQuery, open, currentPlace]);

  // Picking a search result: fetch its coordinates and full address (Place Details), then select it
  const handlePick = async (place: PlaceOption) => {
    if (place.latitude != null && place.longitude != null) {
      setSelected(place);
      return;
    }
    if (!place.placeId || resolvingKey) return;
    setResolvingKey(place.key);
    try {
      const res = await fetch(
        `${PLACES_URL}/places/${encodeURIComponent(place.placeId)}?sessionToken=${sessionTokenRef.current}&languageCode=en`,
        {
          headers: {
            'X-Goog-Api-Key': GOOGLE_MAPS_API_KEY,
            'X-Goog-FieldMask': 'location,displayName,formattedAddress',
          },
        }
      );
      const data = await res.json();
      if (!res.ok || data?.location?.latitude == null || data?.location?.longitude == null) {
        throw new Error(googleErrorText(data, 'No coordinates for this place'));
      }
      const resolved: PlaceOption = {
        ...place,
        title: data.displayName?.text || place.title,
        subtitle: data.formattedAddress || place.subtitle,
        latitude: data.location.latitude,
        longitude: data.location.longitude,
      };
      setResults((prev) => prev.map((r) => (r.key === place.key ? resolved : r)));
      setSelected(resolved);
      // The session ends once details are fetched; start a new one for the next search
      sessionTokenRef.current = newSessionToken();
    } catch (error: any) {
      notification.error({
        message: 'Could not load this place',
        description: error?.message || 'Please try another result.',
      });
    } finally {
      setResolvingKey(null);
    }
  };

  // The user dragged the pin or clicked the map: select that point and look up its address
  const handleMapMove = async (latitude: number, longitude: number) => {
    const requestId = ++pinRequestRef.current;
    setSelected({
      key: 'pin',
      title: 'Dropped pin',
      subtitle: `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`,
      latitude,
      longitude,
      isPin: true,
    });
    try {
      const address = await reverseGeocode(latitude, longitude);
      if (address && requestId === pinRequestRef.current) {
        setSelected((prev) => (prev?.key === 'pin' ? { ...prev, subtitle: address } : prev));
      }
    } catch (error: any) {
      console.warn('Google reverse geocoding failed:', error?.code || '', error?.message || error);
    }
  };

  const handleSend = () => {
    if (!selected || sending || resolvingKey) return;
    if (selected.latitude == null || selected.longitude == null) {
      notification.error({ message: 'This location has no valid coordinates.' });
      return;
    }
    onSend({
      latitude: selected.latitude,
      longitude: selected.longitude,
      // The current location and a dropped pin have no place name, only an address
      name: selected.isCurrent || selected.isPin ? undefined : selected.title,
      address: selected.subtitle || undefined,
    });
  };

  const isSearching = query.trim().length >= MIN_QUERY_LENGTH;
  const canPreview = selected?.latitude != null && selected?.longitude != null && !!GOOGLE_MAPS_API_KEY;

  const renderOption = (place: PlaceOption) => {
    const isSelected = selected?.key === place.key;
    const isResolving = resolvingKey === place.key;
    return (
      <div
        key={place.key}
        role="button"
        tabIndex={0}
        onClick={() => handlePick(place)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            handlePick(place);
          }
        }}
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 12,
          padding: '10px 14px',
          cursor: resolvingKey ? 'wait' : 'pointer',
          background: isSelected ? '#f0f5ff' : undefined,
          borderBottom: '1px solid #f5f5f5',
        }}
      >
        <div
          style={{
            width: 36,
            height: 36,
            borderRadius: '50%',
            flexShrink: 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            background: place.isCurrent ? '#25d366' : '#e9edef',
            color: place.isCurrent ? '#fff' : '#54656f',
            fontSize: 17,
          }}
        >
          {place.isCurrent ? <AimOutlined /> : <EnvironmentOutlined />}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <Text strong style={{ display: 'block' }} ellipsis>
            {place.title}
          </Text>
          <Text type="secondary" style={{ display: 'block', fontSize: 12 }} ellipsis>
            {place.subtitle}
          </Text>
          {place.isCurrent && place.accuracy != null && place.accuracy > 100 && (
            <Text type="warning" style={{ display: 'block', fontSize: 12 }}>
              Your device reports this position only to about {Math.round(place.accuracy)} m, so it may be off.
              Search for the exact place if it looks wrong.
            </Text>
          )}
        </div>
        {isResolving && <LoadingOutlined style={{ color: '#1677ff' }} />}
        {isSelected && !isResolving && <CheckOutlined style={{ color: '#1677ff' }} />}
      </div>
    );
  };

  return (
    <Modal
      open={open}
      title="Send location"
      onCancel={onCancel}
      footer={null}
      destroyOnClose
      maskClosable={!sending}
      width={mapExpanded ? 900 : 480}
      bodyStyle={{ padding: 0 }}
    >
      <div style={{ padding: '12px 16px' }}>
        <Input
          prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
          placeholder="Search a place or address"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          allowClear
          disabled={sending || !GOOGLE_MAPS_API_KEY}
          autoFocus
        />
      </div>

      {canPreview && selected && (
        <LocationMap
          latitude={selected.latitude as number}
          longitude={selected.longitude as number}
          focusKey={selected.key}
          expanded={mapExpanded}
          onToggleExpand={() => setMapExpanded((prev) => !prev)}
          onMove={handleMapMove}
        />
      )}

      <div style={{ maxHeight: mapExpanded ? 180 : 280, overflowY: 'auto' }}>
        {!isSearching && (
          <>
            {selected?.isPin && renderOption(selected)}
            {locating && (
              <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <Spin indicator={<LoadingOutlined style={{ fontSize: 16 }} spin />} />
                <Text type="secondary">Finding your current location...</Text>
              </div>
            )}
            {currentPlace && renderOption(currentPlace)}
            {!locating && !currentPlace && locationError && (
              <div style={{ padding: '14px 16px' }}>
                <Text type="secondary">{locationError}</Text>
              </div>
            )}
          </>
        )}

        {isSearching && (
          <>
            {searching && (
              <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <Spin indicator={<LoadingOutlined style={{ fontSize: 16 }} spin />} />
                <Text type="secondary">Searching...</Text>
              </div>
            )}
            {!searching && searchError && (
              <div style={{ padding: '14px 16px' }}>
                <Text type="danger">{searchError}</Text>
              </div>
            )}
            {!searching && !searchError && results.length === 0 && debouncedQuery === query.trim() && (
              <div style={{ padding: '14px 16px' }}>
                <Text type="secondary">No places found</Text>
              </div>
            )}
            {results.map(renderOption)}
          </>
        )}
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, padding: '12px 16px', borderTop: '1px solid #f0f0f0' }}>
        <Button onClick={onCancel} disabled={sending}>
          Cancel
        </Button>
        <Button
          type="primary"
          onClick={handleSend}
          loading={sending}
          disabled={!selected || !!resolvingKey}
        >
          Send
        </Button>
      </div>
    </Modal>
  );
}
