/**
 * 简单地图选点组件
 * 用于选择单个GPS坐标点
 */

import { useEffect, useRef, useState } from 'react';
import { Card } from '../ui/card';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Button } from '../ui/button';
import { MapPin, Check } from 'lucide-react';

interface SimpleMapPointPickerProps {
  onPointSelect: (lat: number, lng: number) => void;
  selectedPoint?: [number, number]; // [latitude, longitude]
  height?: string;
}

export function SimpleMapPointPicker({ 
  onPointSelect, 
  selectedPoint,
  height = '300px'
}: SimpleMapPointPickerProps) {
  const mapRef = useRef<HTMLDivElement>(null);
  const [map, setMap] = useState<any>(null);
  const [marker, setMarker] = useState<any>(null);
  const [manualLat, setManualLat] = useState('');
  const [manualLng, setManualLng] = useState('');
  const [isAmapAvailable, setIsAmapAvailable] = useState(false);

  // 检查高德地图SDK是否可用
  useEffect(() => {
    setIsAmapAvailable(typeof window.AMap !== 'undefined');
  }, []);

  // 初始化地图
  useEffect(() => {
    if (!mapRef.current || map || !isAmapAvailable) return;

    // 默认中心点
    const center = selectedPoint 
      ? [selectedPoint[1], selectedPoint[0]] // AMap使用 [lng, lat]
      : [116.4074, 39.9042];

    // 创建地图实例
    const mapInstance = new window.AMap.Map(mapRef.current, {
      zoom: 13,
      center: center,
      mapStyle: 'amap://styles/normal',
      viewMode: '2D',
    });

    setMap(mapInstance);

    // 添加点击事件
    mapInstance.on('click', (e: any) => {
      const lng = e.lnglat.getLng();
      const lat = e.lnglat.getLat();
      
      // 移除旧标记
      if (marker) {
        mapInstance.remove(marker);
      }

      // 添加新标记
      const newMarker = new window.AMap.Marker({
        position: [lng, lat],
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(32, 32),
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
          imageSize: new window.AMap.Size(32, 32),
        }),
      });

      mapInstance.add(newMarker);
      setMarker(newMarker);

      // 回调
      onPointSelect(lat, lng);
    });

    // 清理函数
    return () => {
      if (mapInstance) {
        mapInstance.destroy();
      }
    };
  }, []);

  // 当selectedPoint变化时更新标记
  useEffect(() => {
    if (!map || !selectedPoint) return;

    const [lat, lng] = selectedPoint;

    // 移除旧标记
    if (marker) {
      map.remove(marker);
    }

    // 添加新标记
    const newMarker = new window.AMap.Marker({
      position: [lng, lat],
      icon: new window.AMap.Icon({
        size: new window.AMap.Size(32, 32),
        image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        imageSize: new window.AMap.Size(32, 32),
      }),
    });

    map.add(newMarker);
    setMarker(newMarker);

    // 移动地图中心
    map.setCenter([lng, lat]);
  }, [selectedPoint, map]);

  // 手动输入坐标并确认
  const handleManualInput = () => {
    const lat = parseFloat(manualLat);
    const lng = parseFloat(manualLng);
    
    if (isNaN(lat) || isNaN(lng)) {
      return;
    }

    if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
      return;
    }

    onPointSelect(lat, lng);
  };

  // 使用演示地图模式，提供手动输入界面
  if (!isAmapAvailable) {
    return (
      <Card className="overflow-hidden">
        <div className="relative" style={{ height }}>
          {/* 占位地图背景 */}
          <div className="absolute inset-0 bg-gradient-to-br from-green-50 to-blue-50">
            <div 
              className="absolute inset-0" 
              style={{
                backgroundImage: 'linear-gradient(rgba(0,0,0,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(0,0,0,0.03) 1px, transparent 1px)',
                backgroundSize: '50px 50px'
              }}
            />
          </div>
          
          {/* 手动输入坐标界面 */}
          <div className="absolute inset-0 flex items-center justify-center p-6">
            <Card className="p-6 max-w-md w-full bg-white/95 backdrop-blur shadow-lg">
              <div className="flex items-center gap-2 mb-4">
                <MapPin className="w-5 h-5 text-green-600" />
                <h4 className="text-green-800">选择坐标位置</h4>
              </div>
              
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>纬度 (Latitude)</Label>
                    <Input 
                      type="number"
                      step="0.000001"
                      placeholder="39.9042"
                      value={manualLat}
                      onChange={(e) => setManualLat(e.target.value)}
                      className="mt-1"
                    />
                    <p className="text-xs text-muted-foreground mt-1">-90 ~ 90</p>
                  </div>
                  <div>
                    <Label>经度 (Longitude)</Label>
                    <Input 
                      type="number"
                      step="0.000001"
                      placeholder="116.4074"
                      value={manualLng}
                      onChange={(e) => setManualLng(e.target.value)}
                      className="mt-1"
                    />
                    <p className="text-xs text-muted-foreground mt-1">-180 ~ 180</p>
                  </div>
                </div>
                
                <Button 
                  onClick={handleManualInput}
                  className="w-full bg-green-600 hover:bg-green-700"
                  disabled={!manualLat || !manualLng}
                >
                  <Check className="w-4 h-4 mr-2" />
                  确认坐标
                </Button>
                
                {selectedPoint && (
                  <div className="mt-4 p-3 bg-green-50 rounded-lg border border-green-200">
                    <p className="text-sm text-green-800">
                      <strong>当前坐标：</strong><br/>
                      纬度: {selectedPoint[0].toFixed(6)}<br/>
                      经度: {selectedPoint[1].toFixed(6)}
                    </p>
                  </div>
                )}
                
                <p className="text-xs text-muted-foreground text-center">
                  💡 提示：可使用百度地图、高德地图等工具查询坐标
                </p>
              </div>
            </Card>
          </div>
        </div>
      </Card>
    );
  }

  // 高德地图可用时显示交互式地图
  return (
    <Card className="overflow-hidden">
      <div className="relative">
        <div 
          ref={mapRef} 
          style={{ height }}
          className="w-full"
        />
        {/* 提示信息 */}
        <div className="absolute top-3 left-3 bg-white px-3 py-2 rounded-lg shadow-md border flex items-center gap-2 text-sm">
          <MapPin className="w-4 h-4 text-green-600" />
          <span className="text-gray-700">点击地图选择位置</span>
        </div>
      </div>
    </Card>
  );
}
