import React, { useEffect, useState, useRef } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image, StatusBar, Linking, Platform, PermissionsAndroid } from 'react-native';
import { MapView, Marker, MapType } from 'react-native-amap3d';
import Geolocation from '@react-native-community/geolocation';
import { rpx } from '../../utils/rpx';
import { useNavigation, useRoute } from '@react-navigation/native';
import { transformFromWGSToGCJ } from '../../utils/coordtransform';
import { apiService } from '../../utils/api';

interface DeviceLocation {
  latitude: number;
  longitude: number;
  address?: string;
  updateTime?: string;
}

interface DeviceInfo {
  latitude: string;
  longitude: string;
  lastLocationTime: string;
  location?: string;
}

const DeviceMap = () => {
  const navigation = useNavigation();
  const route = useRoute();
  const { sn } = route.params as { sn: string };
  const mapRef = useRef<MapView | null>(null);
  
  const [userLocation, setUserLocation] = useState<{latitude: number; longitude: number} | null>(null);
  const [deviceLocation, setDeviceLocation] = useState<DeviceLocation | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 获取设备位置信息
  const getDeviceLocation = async () => {
    try {
      if (!sn) {
        console.warn('设备SN不存在');
        return;
      }

      const response = await apiService.getDeviceInfo(sn);
      if (response.code === 200 && response.data) {
        const { latitude, longitude, lastLocationTime, location } = response.data;
        setDeviceLocation({
          latitude: Number(latitude),
          longitude: Number(longitude),
          address: location || '',
          updateTime: lastLocationTime || ''
        });
        setIsLoading(false);
      } else {
        console.warn('获取设备信息失败:', response);
      }
    } catch (error) {
      console.error('获取设备位置信息失败:', error);
    }
  };

  const getCurrentLocation = () => {
    // 移除原有的检查，因为 userLocation 可能还未获取到
    try {
      if (mapRef.current && userLocation) {
        mapRef.current.moveCamera({
          target: userLocation,
          zoom: 15,
        }, 1000);
      } else {
        // 如果还没有获取到位置，等待位置信息
        console.log('等待获取用户位置...');
      }
    } catch (error) {
      console.error('移动地图失败:', error);
    }
  };


  useEffect(() => {
    // 先获取位置，再调用 getCurrentLocation
    const watchId = Geolocation.watchPosition(
      (position) => {
        const gcjLocation = transformFromWGSToGCJ(
          position.coords.latitude,
          position.coords.longitude
        );
        setUserLocation(gcjLocation);
        
        // 位置获取成功后自动移动地图
        if (mapRef.current) {
          mapRef.current.moveCamera({
            target: gcjLocation,
            zoom: 15,
          }, 1000);
        }
      },
      (error) => {
        console.error('位置监听错误:', error);
      },
      {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 1000,
        distanceFilter: 10
      }
    );
  
    getDeviceLocation();
  
    return () => {
      Geolocation.clearWatch(watchId);
    };
  }, [sn]);

  // 跳转到高德地图
  const openAMap = async () => {
    if (!deviceLocation) return;

    const url = Platform.select({
      android: `androidamap://navi?sourceApplication=appname&lat=${deviceLocation.latitude}&lon=${deviceLocation.longitude}&dev=0&style=2`,
      ios: `iosamap://navi?sourceApplication=appname&lat=${deviceLocation.latitude}&lon=${deviceLocation.longitude}&dev=0&style=2`,
    });
    const fallbackUrl = `https://uri.amap.com/navigation?to=${deviceLocation.longitude},${deviceLocation.latitude},目的地&mode=car&coordinate=gaode`;

    try {
      const supported = await Linking.canOpenURL(url);
      if (supported) {
        await Linking.openURL(url);
      } else {
        await Linking.openURL(fallbackUrl);
      }
    } catch (error) {
      console.error('无法打开高德地图:', error);
      await Linking.openURL(fallbackUrl);
    }
  };

  // 格式化时间
  const formatTime = (timeString: string) => {
    if (!timeString) return '12:00';
    const date = new Date(timeString);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };

  if (isLoading || !deviceLocation) {
    return (
      <View style={styles.container}>
        <Text>加载中...</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <MapView
        ref={mapRef}
        style={styles.map}
        mapType={MapType.Standard}
        zoomControlsEnabled={false}
        scrollEnabled={true}
        zoomEnabled={true}
        initialCameraPosition={{
          target: {
            latitude: deviceLocation.latitude,
            longitude: deviceLocation.longitude,
          },
          zoom: 15,
        }}
      >
        {userLocation && (
          <Marker
            position={{
              latitude: userLocation.latitude,
              longitude: userLocation.longitude,
            }}
            // icon={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uY9tYXXZztuE1VTLDl5y' }}
          />
        )}
        
        <Marker
          position={{
            latitude: deviceLocation.latitude,
            longitude: deviceLocation.longitude,
          }}
          icon={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uRx1B8B8acbquF2TO7Ry' }}
        />
      </MapView>
      
      <TouchableOpacity 
        style={styles.locationIcon} 
        onPress={getCurrentLocation}
      >
        <Image 
          source={{ uri: 'https://api.ccttiot.com/smartmeter/img/static/uOCaLkinKXhZLxCkTFAQ' }} 
          style={{ width: rpx(90), height: rpx(90) }} 
        />
      </TouchableOpacity>

      <View style={styles.bottomCard}>
        <View style={styles.addressInfo}>
          <Text style={styles.addressText}>
            {deviceLocation.address || '获取地址中...'}
          </Text>
          <TouchableOpacity onPress={()=>{
           const response =  apiService.ring(sn);
           console.log(response,'response');
          }}>
          <Image 
            source={{ uri: 'https://api.ccttiot.com/smartmeter/img/static/ucBlLZW1SpAaKxSQYkr6' }}
            style={styles.voiceIcon}
          />
          </TouchableOpacity>
          
        </View>
        <View style={styles.timeBlock}>
          <Image 
            source={{ uri: 'https://api.ccttiot.com/smartmeter/img/static/uMnpK2e8az06pzJrKms5' }} 
            style={styles.timeClock} 
          />
          <Text style={styles.timeText1}>
           {deviceLocation.updateTime}
          </Text>
        </View>
        <TouchableOpacity 
          style={styles.navigationButton}
          onPress={openAMap}
        >
          <Text style={styles.buttonText}>导航到车辆</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
  locationIcon: {
    position: 'absolute',
    right: rpx(32),
    bottom: rpx(400),
    width: rpx(90),
    height: rpx(90),
  },
  map: {
    flex: 1,
    width: '100%',
  },
  timeBlock: {
    display: 'flex',
    flexDirection: 'row',
    alignSelf: 'flex-start',
    justifyContent:'center',
    alignItems:'center',
    padding: rpx(8),
    paddingHorizontal:rpx(18),
    backgroundColor: '#EFEFEF',
    borderRadius: rpx(29),
    flexWrap: 'nowrap',
    marginBottom:rpx(40),
  },
  timeClock:{
    marginRight:rpx(14),
    width:rpx(26),
    height:rpx(26),
  },
  timeText1:{
    fontSize:rpx(24),
    color:'#808080',
  },
  bottomCard: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: '#FFFFFF',
    borderTopLeftRadius: rpx(24),
    borderTopRightRadius: rpx(24),
    padding: rpx(36),
  },
  addressInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: rpx(32),
  },
  addressText: {
    flex: 1,
    fontSize: rpx(36),
    color: '#333333',
    marginRight: rpx(16),
  },
  voiceIcon: {
    width: rpx(90),
    height: rpx(90),
  },
  navigationButton: {
    height: rpx(96),
    backgroundColor: '#2089FF',
    borderRadius: rpx(20),
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    fontSize: rpx(32),
    color: '#FFFFFF',
    fontWeight: '500',
  },
});

export default DeviceMap;