import { ref } from 'vue'
import * as Cesium from 'cesium'
import { applyRandomOffset } from '../utils/geoUtils'
import soldierIcon from '../assets/images/SketchPngfbec927027ff9e49207749ebaafd229429315341fda199251b6dfb1723ff17fb.png'
import deviceIcon from '../assets/images/SketchPng860d54f2a31f5f441fc6a88081224f1e98534bf6d5ca1246e420983bdf690380.png'

/**
 * Composable for managing simulated emergency markers
 *
 * Manages 6 markers total:
 * - 2 at disaster center (static)
 * - 4 at the 2 nearest reserve centers (will be animated on dispatch)
 */
export function useSimulatedMarkers() {
  const simulatedMarkers = ref([])

  /**
   * Create all 6 simulated markers
   * @param {Cesium.Viewer} viewer
   * @param {Object} disasterCenter - { lon, lat }
   * @param {Array} emergencyPoints - Top 2 nearest emergency points [{ gl1Lng, gl1Lat, gl1Yjllmc, gl1Id, ... }, ...]
   */
  const createSimulatedMarkers = (viewer, disasterCenter, emergencyPoints) => {
    if (!viewer || !disasterCenter || !emergencyPoints || emergencyPoints.length < 2) {
      console.error('[useSimulatedMarkers] Invalid parameters')
      return
    }

    // Clear existing simulated markers
    clearSimulatedMarkers(viewer)

    const newMarkers = []

    // 1. Create 2 center markers (static, no animation)
    // const centerPersonnelCoords = applyRandomOffset(disasterCenter, 10, 30)
    // const centerPersonnel = viewer.entities.add({
    //   position: Cesium.Cartesian3.fromDegrees(centerPersonnelCoords.lon, centerPersonnelCoords.lat, 0),
    //   billboard: {
    //     image: soldierIcon,
    //     width: 36,
    //     height: 40,
    //     verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    //     heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    //     disableDepthTestDistance: Number.POSITIVE_INFINITY
    //   },
    //   properties: new Cesium.PropertyBag({
    //     type: 'centerPersonnel',
    //     name: '应急人员',
    //     isSimulated: true,
    //     isStatic: true
    //   })
    // })
    // newMarkers.push(centerPersonnel)

    // const centerEquipmentCoords = applyRandomOffset(disasterCenter, 10, 30)
    // const centerEquipment = viewer.entities.add({
    //   position: Cesium.Cartesian3.fromDegrees(centerEquipmentCoords.lon, centerEquipmentCoords.lat, 0),
    //   billboard: {
    //     image: deviceIcon,
    //     width: 36,
    //     height: 40,
    //     verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    //     heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    //     disableDepthTestDistance: Number.POSITIVE_INFINITY
    //   },
    //   properties: new Cesium.PropertyBag({
    //     type: 'centerEquipment',
    //     name: '应急装备',
    //     isSimulated: true,
    //     isStatic: true
    //   })
    // })
    // newMarkers.push(centerEquipment)

    // 2. Create 4 emergency point markers (will be animated later)
    emergencyPoints.slice(0, 2).forEach((point, index) => {
      const pointCoords = { lon: point.gl1Lng, lat: point.gl1Lat }
      const pointName = point.gl1Yjllmc || `应急点${index + 1}`

      // Personnel marker
      const personnelCoords = applyRandomOffset(pointCoords, 10, 30)
      const personnelMarker = viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(personnelCoords.lon, personnelCoords.lat, 0),
        billboard: {
          image: soldierIcon,
          width: 36,
          height: 40,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        properties: new Cesium.PropertyBag({
          type: 'emergencyPersonnel',
          name: `${pointName} - 应急人员`,
          isSimulated: true,
          isStatic: false,
          emergencyPointId: point.gl1Id,
          emergencyPointCoords: pointCoords,
          markerCoords: personnelCoords
        })
      })
      newMarkers.push(personnelMarker)

      // Equipment marker
      const equipmentCoords = applyRandomOffset(pointCoords, 10, 30)
      const equipmentMarker = viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(equipmentCoords.lon, equipmentCoords.lat, 0),
        billboard: {
          image: deviceIcon,
          width: 36,
          height: 40,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        properties: new Cesium.PropertyBag({
          type: 'emergencyEquipment',
          name: `${pointName} - 应急装备`,
          isSimulated: true,
          isStatic: false,
          emergencyPointId: point.gl1Id,
          emergencyPointCoords: pointCoords,
          markerCoords: equipmentCoords
        })
      })
      newMarkers.push(equipmentMarker)
    })

    simulatedMarkers.value = newMarkers
    console.log(`[useSimulatedMarkers] Created ${newMarkers.length} simulated markers`)

    return newMarkers
  }

  /**
   * Clear all simulated markers
   */
  const clearSimulatedMarkers = (viewer) => {
    if (!viewer) return

    simulatedMarkers.value.forEach(entity => {
      viewer.entities.remove(entity)
    })
    simulatedMarkers.value = []

    console.log('[useSimulatedMarkers] Cleared all simulated markers')
  }

  /**
   * Hide emergency point markers (before starting animation)
   */
  const hideEmergencyMarkers = (viewer) => {
    if (!viewer) return

    viewer.entities.values.forEach(entity => {
      if (entity.properties) {
        const type = entity.properties.type?.getValue()
        const isStatic = entity.properties.isStatic?.getValue()
        if ((type === 'emergencyPersonnel' || type === 'emergencyEquipment') && !isStatic) {
          entity.show = false
        }
      }
    })

    console.log('[useSimulatedMarkers] Hidden emergency markers')
  }

  /**
   * Get emergency marker data for animation
   * @returns {Array} [{ type, name, markerCoords: { lon, lat }, emergencyPointCoords: { lon, lat } }, ...]
   */
  const getEmergencyMarkerData = () => {
    return simulatedMarkers.value
      .filter(entity => {
        const isStatic = entity.properties?.isStatic?.getValue()
        return !isStatic
      })
      .map(entity => {
        const props = entity.properties
        return {
          type: props.type.getValue(),
          name: props.name.getValue(),
          markerCoords: props.markerCoords.getValue(),
          emergencyPointCoords: props.emergencyPointCoords.getValue()
        }
      })
  }

  return {
    simulatedMarkers,
    createSimulatedMarkers,
    clearSimulatedMarkers,
    hideEmergencyMarkers,
    getEmergencyMarkerData
  }
}
