import { useEffect, useRef, useState } from 'react';
import Taro from '@tarojs/taro';
import { fetchMapData, getAutoScaleBySites } from '../../../../utils/Robotaxi-public-method';
import { readHomeCachedUserLocation } from './use-user-location-cache';

const AUTO_SCALE_MAX = 17; // 自动缩放最大等级
const AUTO_SCALE_MIN = 11; // 自动缩放最小等级
const HOME_MAP_POINT_ON_OFF = 1; // 首页地图固定拉取上车点

// 站点 marker 原始（紫色）图标，来自 formatSiteToMarker
const OLD_SITE_MARKER_ICON = 'https://s.xiaopeng.com/xp-fe/robot-taxi/imgs/site-poi.png';
// 首页地图站点金色图标
const SITE_MARKER_ICON = 'https://s.xiaopeng.com/xp-fe/robot-taxi/imgs/v2/golden-site-20260708.png';

/**
 * 将站点 marker 的图标替换为首页金色图标（仅影响首页地图）。
 */
const applySiteMarkerIcon = (markerList: any[]) => {
  if (!Array.isArray(markerList)) {
    return markerList;
  }
  return markerList.map((marker) => (
    marker?.iconPath === OLD_SITE_MARKER_ICON
      ? { ...marker, iconPath: SITE_MARKER_ICON, width: 18, height: 18 }
      : marker
  ));
};

/**
 * 比较两批站点 marker 的关键展示字段是否一致。
 */
const isSameMarkerList = (currentMarkers: any[], nextMarkers: any[]) => {
  if (currentMarkers.length !== nextMarkers.length) {
    return false;
  }
  return currentMarkers.every((marker, index) => {
    const nextMarker = nextMarkers[index];
    return marker?.id === nextMarker?.id
      && marker?.latitude === nextMarker?.latitude
      && marker?.longitude === nextMarker?.longitude
      && marker?.iconPath === nextMarker?.iconPath
      && marker?.width === nextMarker?.width
      && marker?.height === nextMarker?.height
      && marker?.zIndex === nextMarker?.zIndex
      && marker?.markerType === nextMarker?.markerType;
  });
};

/**
 * 地图状态管理：拥有地图坐标、围栏、标记点及地图业务数据刷新能力。
 */
export default function useMapState() {
  const [longitude, setLongitude] = useState<number | null>(() => {
    const startSite = Taro.getStorageSync('startSite');
    if (startSite && Number.isFinite(Number(startSite.longitude))) {
      return Number(startSite.longitude);
    }
    const cachedUserLoc = readHomeCachedUserLocation();
    if (cachedUserLoc && Number.isFinite(cachedUserLoc.lng)) {
      return cachedUserLoc.lng;
    }
    return null;
  });
  const [latitude, setLatitude] = useState<number | null>(() => {
    const startSite = Taro.getStorageSync('startSite');
    if (startSite && Number.isFinite(Number(startSite.latitude))) {
      return Number(startSite.latitude);
    }
    const cachedUserLoc = readHomeCachedUserLocation();
    if (cachedUserLoc && Number.isFinite(cachedUserLoc.lat)) {
      return cachedUserLoc.lat;
    }
    return null;
  });
  const [markers, setMarkers] = useState<any[]>([]);
  const [polygons, setPolygons] = useState<any[]>([]);
  const [mapScale, setMapScale] = useState(14);
  const [isOperatingArea, setIsOperatingArea] = useState(true);
  const [electronicAreaId, setElectronicAreaId] = useState('');
  const [nearbySites, setNearbySites] = useState<any[]>([]);
  const [isLocationAuthDenied, setIsLocationAuthDenied] = useState(false);
  const [nearbyLoading, setNearbyLoading] = useState(false);

  const shouldIgnoreRegionChange = useRef(false);
  const isReturningToOrigin = useRef(false);
  const resetTimer = useRef<any>(null);
  const pendingNearbyRequestCountRef = useRef(0);
  const autoScaleAppliedCityCodeRef = useRef(''); // 已执行自动缩放的城市 code
  const markersRef = useRef<any[]>([]); // 当前站点 marker 快照
  const markerCommitTimerRef = useRef<any>(null); // 延迟提交站点 marker 的定时器

  /**
   * 清理延迟提交站点 marker 的定时器。
   */
  const clearMarkerCommitTimer = () => {
    if (markerCommitTimerRef.current) {
      clearTimeout(markerCommitTimerRef.current);
      markerCommitTimerRef.current = null;
    }
  };

  /**
   * 立即提交站点 marker 到地图。
   */
  const commitMarkers = (nextMarkers: any[]) => {
    if (!isSameMarkerList(markersRef.current, nextMarkers)) {
      markersRef.current = nextMarkers;
      setMarkers(nextMarkers);
    }
  };

  /**
   * 按指定延迟提交站点 marker，拖图查询可先拿结果、后避让车辆动画提交。
   */
  const scheduleMarkerCommit = (nextMarkers: any[], delayMs = 0) => {
    clearMarkerCommitTimer();
    if (delayMs <= 0) {
      commitMarkers(nextMarkers);
      return;
    }
    markerCommitTimerRef.current = setTimeout(() => {
      markerCommitTimerRef.current = null;
      commitMarkers(nextMarkers);
    }, delayMs);
  };

  /**
   * 根据经纬度和城市编码刷新地图业务数据（围栏内判断、电子围栏 ID、站点标记）。
   */
  const updateMapData = async (
    lat: number,
    lng: number,
    cityCode?: string,
    options?: {
      commitMarkers?: boolean;
      markerCommitDelayMs?: number;
    }
  ) => {
    const code = cityCode || Taro.getStorageSync('selectedCity')?.code;
    if (!code) {
      return { isInside: false, electronicAreaId: '', newMarkers: [], sites: [] };
    }
    pendingNearbyRequestCountRef.current += 1;
    setNearbyLoading(true);
    try {
      const result = await fetchMapData(lat, lng, code, HOME_MAP_POINT_ON_OFF);
      result.newMarkers = applySiteMarkerIcon(result.newMarkers);
      setIsOperatingArea(result.isInside);
      setElectronicAreaId(result.electronicAreaId);
      setNearbySites(Array.isArray(result?.sites) ? result.sites : []);
      if (options?.commitMarkers !== false) {
        scheduleMarkerCommit(result.newMarkers, options?.markerCommitDelayMs || 0);
      }
      
      // 检查当前选中的站点是否为场站子站点
      // 因为 autoScale 会强制覆盖 mapScale，如果当前处于场站聚焦态（应当是 18），需要跳过 autoScale 逻辑
      const currentSite = Taro.getStorageSync('startSite');
      const isStationFocused = currentSite && currentSite.stationId;

      if (!isStationFocused && autoScaleAppliedCityCodeRef.current !== code) {
        const autoScale = getAutoScaleBySites(result?.sites || result?.newMarkers || [], lat, lng);
        if (typeof autoScale === 'number') {
          setMapScale((prev) => {
            const nextScale = Math.max(AUTO_SCALE_MIN, Math.min(AUTO_SCALE_MAX, autoScale));
            if (Math.abs(prev - nextScale) < 0.01) return prev;
            return nextScale;
          });
        }
        autoScaleAppliedCityCodeRef.current = code;
      }
      return result;
    } finally {
      pendingNearbyRequestCountRef.current = Math.max(0, pendingNearbyRequestCountRef.current - 1);
      if (pendingNearbyRequestCountRef.current === 0) {
        setNearbyLoading(false);
      }
    }
  };

  useEffect(() => {
    return () => {
      clearMarkerCommitTimer();
    };
  }, []);

  return {
    longitude,
    latitude,
    markers,
    polygons,
    mapScale,
    isOperatingArea,
    electronicAreaId,
    nearbySites,
    isLocationAuthDenied,
    nearbyLoading,
    setLongitude,
    setLatitude,
    setMarkers,
    setPolygons,
    setMapScale,
    setIsOperatingArea,
    setElectronicAreaId,
    setNearbySites,
    setIsLocationAuthDenied,
    shouldIgnoreRegionChange,
    isReturningToOrigin,
    resetTimer,
    commitMarkers,
    scheduleMarkerCommit,
    updateMapData,
  };
}
