/**
 * 地块影像组件
 * 集成时序遥感影像服务，支持天地图、Sentinel、Landsat等数据源
 */

'use client';

import { useState, useEffect } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Slider } from '@/components/ui/slider';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Satellite,
  Calendar,
  Image as ImageIcon,
  TrendingUp,
  TrendingDown,
  Layers,
  Download,
  Eye,
  BarChart3,
  Cloud,
  Leaf,
  Sun,
  Droplets,
  AlertCircle,
  RefreshCw,
  Filter,
  Maximize2,
  ChevronLeft,
  ChevronRight,
  Activity
} from 'lucide-react';
import { toast } from 'sonner';
import {
  SatelliteImageService,
  DATA_SOURCES,
  getCloudCoverColorClass,
  formatImageDate
} from './satelliteImageService';
import {
  SatelliteImage,
  ImageComparisonResult,
  TimeSeriesAnalysis
} from './satelliteTypes';

export function FieldSatellite() {
  const [selectedField, setSelectedField] = useState('field-1');
  const [imageSource, setImageSource] = useState<string>('Sentinel-2');
  const [selectedImage, setSelectedImage] = useState<SatelliteImage | null>(null);
  const [comparisonImage, setComparisonImage] = useState<SatelliteImage | null>(null);
  const [showComparison, setShowComparison] = useState(false);
  const [timeSliderValue, setTimeSliderValue] = useState([0]);
  const [maxCloudCover, setMaxCloudCover] = useState(30);
  const [images, setImages] = useState<SatelliteImage[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [comparisonResult, setComparisonResult] = useState<ImageComparisonResult | null>(null);
  const [timeSeriesAnalysis, setTimeSeriesAnalysis] = useState<TimeSeriesAnalysis | null>(null);
  const [activeView, setActiveView] = useState<'single' | 'comparison' | 'timeseries'>('single');

  // 模拟地块数据
  const mockFields = [
    { id: 'field-1', name: '东区1号地', code: 'DB001' },
    { id: 'field-2', name: '西区2号地', code: 'DB002' },
    { id: 'field-3', name: '南区3号地', code: 'DB003' },
  ];

  // 加载影像数据
  useEffect(() => {
    loadImages();
  }, [selectedField, imageSource, maxCloudCover]);

  // 自动选择第一张影像
  useEffect(() => {
    if (images.length > 0 && !selectedImage) {
      setSelectedImage(images[0]);
      setTimeSliderValue([0]);
    }
  }, [images]);

  // 更新时序分析
  useEffect(() => {
    if (images.length >= 2) {
      const analysis = SatelliteImageService.analyzeTimeSeries(images);
      setTimeSeriesAnalysis(analysis);
    }
  }, [images]);

  const loadImages = async () => {
    setIsLoading(true);
    try {
      // 获取最近6个月的影像
      const endDate = new Date();
      const startDate = new Date();
      startDate.setMonth(startDate.getMonth() - 6);

      const loadedImages = await SatelliteImageService.getFieldImages(
        selectedField,
        startDate.toISOString().split('T')[0],
        endDate.toISOString().split('T')[0],
        imageSource,
        maxCloudCover
      );

      setImages(loadedImages);
      toast.success(`加载了 ${loadedImages.length} 张影像`);
    } catch (error) {
      toast.error('加载影像失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleImageSelect = (image: SatelliteImage, index: number) => {
    setSelectedImage(image);
    setTimeSliderValue([index]);
    toast.success(`已加载 ${formatImageDate(image.date)} 影像`);
  };

  const handleTimeSliderChange = (value: number[]) => {
    setTimeSliderValue(value);
    if (images[value[0]]) {
      setSelectedImage(images[value[0]]);
    }
  };

  const handleComparisonToggle = () => {
    if (!showComparison) {
      // 开启对比模式，选择当前影像的前一张作为对比
      const currentIndex = timeSliderValue[0];
      if (currentIndex < images.length - 1) {
        setComparisonImage(images[currentIndex + 1]);
      } else if (images.length >= 2) {
        setComparisonImage(images[0]);
      }
    }
    setShowComparison(!showComparison);
    setActiveView(showComparison ? 'single' : 'comparison');
  };

  const handleCompare = () => {
    if (!selectedImage || !comparisonImage) {
      toast.error('请选择两张影像进行对比');
      return;
    }

    const result = SatelliteImageService.compareImages(comparisonImage, selectedImage);
    setComparisonResult(result);
    toast.success('影像对比完成');
  };

  const handleDownload = async () => {
    if (!selectedImage) {
      toast.error('请先选择影像');
      return;
    }

    try {
      await SatelliteImageService.downloadImage(selectedImage, 'jpg');
      toast.success(`正在下载 ${formatImageDate(selectedImage.date)} 影像...`);
    } catch (error) {
      toast.error('下载失败');
    }
  };

  const navigateImage = (direction: 'prev' | 'next') => {
    const currentIndex = timeSliderValue[0];
    let newIndex = currentIndex;

    if (direction === 'prev' && currentIndex > 0) {
      newIndex = currentIndex - 1;
    } else if (direction === 'next' && currentIndex < images.length - 1) {
      newIndex = currentIndex + 1;
    }

    if (newIndex !== currentIndex) {
      handleImageSelect(images[newIndex], newIndex);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">地块影像</h2>
          <p className="text-muted-foreground">
            时序遥感影像分析与作物长势监测
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={loadImages}
            disabled={isLoading}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
            {isLoading ? '加载中...' : '刷新影像'}
          </Button>
          <Button
            variant="outline"
            onClick={handleComparisonToggle}
          >
            <BarChart3 className="w-4 h-4 mr-2" />
            {showComparison ? '单影像' : '影像对比'}
          </Button>
          <Button variant="outline" onClick={handleDownload}>
            <Download className="w-4 h-4 mr-2" />
            下载影像
          </Button>
        </div>
      </div>

      {/* 数据源和地块信息 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4 bg-gradient-to-br from-green-50 to-blue-50 dark:from-green-950 dark:to-blue-950">
          <div className="flex items-center gap-3">
            <Satellite className="w-8 h-8 text-green-600 dark:text-green-400" />
            <div>
              <div className="text-sm text-muted-foreground">数据源</div>
              <div className="font-medium">{DATA_SOURCES[imageSource as keyof typeof DATA_SOURCES]?.name || imageSource}</div>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-card">
          <div className="flex items-center gap-3">
            <Layers className="w-8 h-8 text-blue-600 dark:text-blue-400" />
            <div>
              <div className="text-sm text-muted-foreground">影像数量</div>
              <div className="font-medium">{images.length} 张</div>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-card">
          <div className="flex items-center gap-3">
            <Eye className="w-8 h-8 text-purple-600 dark:text-purple-400" />
            <div>
              <div className="text-sm text-muted-foreground">分辨率</div>
              <div className="font-medium">{DATA_SOURCES[imageSource as keyof typeof DATA_SOURCES]?.resolution || '--'}米</div>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-card">
          <div className="flex items-center gap-3">
            <Activity className="w-8 h-8 text-orange-600 dark:text-orange-400" />
            <div>
              <div className="text-sm text-muted-foreground">健康分数</div>
              <div className="font-medium">{timeSeriesAnalysis?.healthScore || '--'}</div>
            </div>
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-4 gap-6">
        {/* 左侧控制面板 */}
        <div className="space-y-4">
          {/* 地块选择 */}
          <Card className="p-4 bg-card">
            <label className="text-sm font-medium mb-2 block">选择地块</label>
            <Select value={selectedField} onValueChange={setSelectedField}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {mockFields.map(field => (
                  <SelectItem key={field.id} value={field.id}>
                    {field.name} ({field.code})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </Card>

          {/* 数据源选择 */}
          <Card className="p-4 bg-card">
            <label className="text-sm font-medium mb-2 block">数据源</label>
            <div className="space-y-2">
              {Object.entries(DATA_SOURCES).map(([key, source]) => (
                <Button
                  key={key}
                  variant={imageSource === key ? 'default' : 'outline'}
                  className="w-full justify-start"
                  onClick={() => setImageSource(key)}
                >
                  <Satellite className="w-4 h-4 mr-2" />
                  <div className="text-left flex-1">
                    <div>{source.name}</div>
                    <div className="text-xs opacity-70">{source.resolution}m</div>
                  </div>
                </Button>
              ))}
            </div>
          </Card>

          {/* 云量过滤 */}
          <Card className="p-4 bg-card">
            <label className="text-sm font-medium mb-2 block">
              最大云量: {maxCloudCover}%
            </label>
            <Slider
              value={[maxCloudCover]}
              onValueChange={(value) => setMaxCloudCover(value[0])}
              max={100}
              step={5}
              className="w-full"
            />
            <div className="flex items-center gap-2 mt-2 text-xs text-muted-foreground">
              <Cloud className="w-3 h-3" />
              <span>仅显示云量 ≤ {maxCloudCover}% 的影像</span>
            </div>
          </Card>

          {/* 视图切换 */}
          <Card className="p-4 bg-card">
            <label className="text-sm font-medium mb-2 block">显示模式</label>
            <div className="space-y-2">
              <Button
                variant={activeView === 'single' ? 'default' : 'outline'}
                className="w-full justify-start"
                onClick={() => {
                  setActiveView('single');
                  setShowComparison(false);
                }}
              >
                <Eye className="w-4 h-4 mr-2" />
                单影像
              </Button>
              <Button
                variant={activeView === 'comparison' ? 'default' : 'outline'}
                className="w-full justify-start"
                onClick={() => {
                  setActiveView('comparison');
                  setShowComparison(true);
                }}
              >
                <BarChart3 className="w-4 h-4 mr-2" />
                对比分析
              </Button>
              <Button
                variant={activeView === 'timeseries' ? 'default' : 'outline'}
                className="w-full justify-start"
                onClick={() => setActiveView('timeseries')}
              >
                <TrendingUp className="w-4 h-4 mr-2" />
                时序分析
              </Button>
            </div>
          </Card>

          {/* 指标说明 */}
          <Card className="p-4 bg-card">
            <h4 className="mb-3">植被指数说明</h4>
            <div className="space-y-3 text-xs">
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <Leaf className="w-3 h-3 text-green-600 dark:text-green-400" />
                  <span className="font-medium">NDVI</span>
                </div>
                <p className="text-muted-foreground">
                  归一化植被指数，反映植被覆盖度和长势
                </p>
              </div>
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <TrendingUp className="w-3 h-3 text-blue-600 dark:text-blue-400" />
                  <span className="font-medium">EVI</span>
                </div>
                <p className="text-muted-foreground">
                  增强型植被指数，对高生物量更敏感
                </p>
              </div>
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <Activity className="w-3 h-3 text-purple-600 dark:text-purple-400" />
                  <span className="font-medium">SAVI</span>
                </div>
                <p className="text-muted-foreground">
                  土壤调节植被指数，减少土壤背景影响
                </p>
              </div>
            </div>
          </Card>
        </div>

        {/* 主显示区域 */}
        <div className="col-span-3 space-y-4">
          <Tabs value={activeView} onValueChange={(v) => setActiveView(v as any)}>
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="single">单影像</TabsTrigger>
              <TabsTrigger value="comparison">影像对比</TabsTrigger>
              <TabsTrigger value="timeseries">时序分析</TabsTrigger>
            </TabsList>

            {/* 单影像视图 */}
            <TabsContent value="single" className="space-y-4">
              {/* 影像显示 */}
              <Card className="overflow-hidden bg-card">
                <div className="relative h-[400px] bg-gradient-to-br from-green-900 via-green-700 to-green-500">
                  {/* 模拟卫星影像 */}
                  <div className="absolute inset-0 opacity-60">
                    <div
                      className="w-full h-full"
                      style={{
                        backgroundImage: `
                          radial-gradient(circle at 30% 40%, rgba(34, 197, 94, ${selectedImage?.ndvi || 0.8}) 0%, transparent 50%),
                          radial-gradient(circle at 70% 60%, rgba(22, 163, 74, ${(selectedImage?.ndvi || 0.8) * 0.8}) 0%, transparent 50%),
                          radial-gradient(circle at 50% 80%, rgba(21, 128, 61, ${(selectedImage?.ndvi || 0.8) * 0.9}) 0%, transparent 40%)
                        `,
                      }}
                    />
                  </div>

                  {/* 导航按钮 */}
                  <div className="absolute inset-y-0 left-0 right-0 flex items-center justify-between px-4">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => navigateImage('prev')}
                      disabled={timeSliderValue[0] === 0}
                      className="bg-white/90 backdrop-blur dark:bg-black/90"
                    >
                      <ChevronLeft className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => navigateImage('next')}
                      disabled={timeSliderValue[0] === images.length - 1}
                      className="bg-white/90 backdrop-blur dark:bg-black/90"
                    >
                      <ChevronRight className="w-4 h-4" />
                    </Button>
                  </div>

                  {/* 影像信息叠加 */}
                  {selectedImage && (
                    <>
                      <div className="absolute top-4 left-4 right-4">
                        <div className="flex items-center justify-between">
                          <Card className="px-4 py-2 bg-white/90 backdrop-blur dark:bg-black/90">
                            <div className="flex items-center gap-3">
                              <Calendar className="w-4 h-4 text-green-600 dark:text-green-400" />
                              <span className="font-medium">{formatImageDate(selectedImage.date)}</span>
                              <Badge variant="outline" className="font-light">{selectedImage.season}</Badge>
                            </div>
                          </Card>
                          <Card className="px-4 py-2 bg-white/90 backdrop-blur dark:bg-black/90">
                            <div className="flex items-center gap-2">
                              <Cloud className="w-4 h-4" />
                              <span className="text-sm">云量: {selectedImage.cloudCover.toFixed(0)}%</span>
                            </div>
                          </Card>
                        </div>
                      </div>

                      {/* NDVI图例 */}
                      <div className="absolute bottom-4 left-4">
                        <Card className="p-3 bg-white/90 backdrop-blur dark:bg-black/90">
                          <div className="text-xs mb-2">NDVI 值</div>
                          <div className="flex items-center gap-2">
                            <div className="w-32 h-4 rounded" style={{
                              background: 'linear-gradient(to right, #ef4444, #f97316, #eab308, #84cc16, #22c55e)',
                            }}></div>
                            <div className="flex justify-between w-32 text-xs">
                              <span>0.0</span>
                              <span>1.0</span>
                            </div>
                          </div>
                        </Card>
                      </div>

                      {/* 当前NDVI值 */}
                      <div className="absolute bottom-4 right-4">
                        <Card className="p-4 bg-white/90 backdrop-blur dark:bg-black/90">
                          <div className="text-center">
                            <div className="text-xs text-muted-foreground mb-1">当前NDVI</div>
                            <div
                              className="text-2xl font-bold"
                              style={{ color: SatelliteImageService.getNDVIColor(selectedImage.ndvi) }}
                            >
                              {selectedImage.ndvi.toFixed(2)}
                            </div>
                            <div className="text-xs mt-1">
                              {SatelliteImageService.getNDVILabel(selectedImage.ndvi)}
                            </div>
                          </div>
                        </Card>
                      </div>
                    </>
                  )}
                </div>
              </Card>

              {/* 作物长势分析 */}
              {selectedImage && (
                <Card className="p-6 bg-card">
                  <h3 className="mb-4">作物长势分析</h3>
                  <div className="grid grid-cols-4 gap-4">
                    <Card className="p-4 bg-green-50 dark:bg-green-950">
                      <div className="flex items-center gap-2 mb-2">
                        <Leaf className="w-5 h-5 text-green-600 dark:text-green-400" />
                        <span className="text-sm">植被覆盖度</span>
                      </div>
                      <div className="text-2xl text-green-600 dark:text-green-400">
                        {(selectedImage.ndvi * 100).toFixed(0)}%
                      </div>
                    </Card>
                    <Card className="p-4 bg-blue-50 dark:bg-blue-950">
                      <div className="flex items-center gap-2 mb-2">
                        <TrendingUp className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                        <span className="text-sm">长势评价</span>
                      </div>
                      <div className="text-sm text-blue-600 dark:text-blue-400">
                        {SatelliteImageService.getNDVILabel(selectedImage.ndvi)}
                      </div>
                    </Card>
                    <Card className="p-4 bg-yellow-50 dark:bg-yellow-950">
                      <div className="flex items-center gap-2 mb-2">
                        <Sun className="w-5 h-5 text-yellow-600 dark:text-yellow-400" />
                        <span className="text-sm">叶面积指数</span>
                      </div>
                      <div className="text-2xl text-yellow-600 dark:text-yellow-400">{selectedImage.lai.toFixed(1)}</div>
                    </Card>
                    <Card className="p-4 bg-cyan-50 dark:bg-cyan-950">
                      <div className="flex items-center gap-2 mb-2">
                        <Droplets className="w-5 h-5 text-cyan-600 dark:text-cyan-400" />
                        <span className="text-sm">增强植被指数</span>
                      </div>
                      <div className="text-sm text-cyan-600 dark:text-cyan-400">{selectedImage.evi.toFixed(2)}</div>
                    </Card>
                  </div>
                </Card>
              )}
            </TabsContent>

            {/* 影像对比视图 */}
            <TabsContent value="comparison" className="space-y-4">
              <Card className="p-6 bg-card">
                <div className="flex items-center justify-between mb-4">
                  <h3>影像对比分析</h3>
                  <Button onClick={handleCompare}>
                    <BarChart3 className="w-4 h-4 mr-2" />
                    执行对比
                  </Button>
                </div>

                {/* 选择对比影像 */}
                <div className="grid grid-cols-2 gap-4 mb-6">
                  <div>
                    <label className="text-sm font-medium mb-2 block">对比影像1（早期）</label>
                    <Select
                      value={comparisonImage?.id || ''}
                      onValueChange={(id) => {
                        const img = images.find(i => i.id === id);
                        if (img) setComparisonImage(img);
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择影像" />
                      </SelectTrigger>
                      <SelectContent>
                        {images.map((img) => (
                          <SelectItem key={img.id} value={img.id}>
                            {formatImageDate(img.date)} - NDVI: {img.ndvi.toFixed(2)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <label className="text-sm font-medium mb-2 block">对比影像2（近期）</label>
                    <Select
                      value={selectedImage?.id || ''}
                      onValueChange={(id) => {
                        const img = images.find(i => i.id === id);
                        if (img) {
                          setSelectedImage(img);
                          const index = images.indexOf(img);
                          setTimeSliderValue([index]);
                        }
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择影像" />
                      </SelectTrigger>
                      <SelectContent>
                        {images.map((img) => (
                          <SelectItem key={img.id} value={img.id}>
                            {formatImageDate(img.date)} - NDVI: {img.ndvi.toFixed(2)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* 对比结果 */}
                {comparisonResult && (
                  <div className="space-y-4">
                    <Card className={`p-4 ${
                      comparisonResult.changeType === 'improvement' ? 'bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800' :
                      comparisonResult.changeType === 'decline' ? 'bg-red-50 dark:bg-red-950 border-red-200 dark:border-red-800' :
                      'bg-gray-50 dark:bg-gray-950'
                    }`}>
                      <div className="flex items-center gap-3">
                        {comparisonResult.changeType === 'improvement' && <TrendingUp className="w-6 h-6 text-green-600 dark:text-green-400" />}
                        {comparisonResult.changeType === 'decline' && <TrendingDown className="w-6 h-6 text-red-600 dark:text-red-400" />}
                        {comparisonResult.changeType === 'stable' && <Activity className="w-6 h-6 text-gray-600 dark:text-gray-400" />}
                        <div className="flex-1">
                          <h4 className={
                            comparisonResult.changeType === 'improvement' ? 'text-green-900 dark:text-green-100' :
                            comparisonResult.changeType === 'decline' ? 'text-red-900 dark:text-red-100' :
                            'text-gray-900 dark:text-gray-100'
                          }>
                            {comparisonResult.changeDescription}
                          </h4>
                        </div>
                      </div>
                    </Card>

                    <div className="grid grid-cols-2 gap-4">
                      <Card className="p-4 bg-card">
                        <h4 className="mb-3">NDVI变化</h4>
                        <div className="flex items-baseline gap-2">
                          <span className="text-3xl font-bold" style={{
                            color: comparisonResult.ndviChange > 0 ? '#22c55e' :
                                   comparisonResult.ndviChange < 0 ? '#ef4444' : '#6b7280'
                          }}>
                            {comparisonResult.ndviChange > 0 ? '+' : ''}{comparisonResult.ndviChange.toFixed(3)}
                          </span>
                          <span className="text-sm text-muted-foreground">
                            ({comparisonResult.image1.ndvi.toFixed(2)} → {comparisonResult.image2.ndvi.toFixed(2)})
                          </span>
                        </div>
                      </Card>
                      <Card className="p-4 bg-card">
                        <h4 className="mb-3">EVI变化</h4>
                        <div className="flex items-baseline gap-2">
                          <span className="text-3xl font-bold" style={{
                            color: comparisonResult.eviChange > 0 ? '#22c55e' :
                                   comparisonResult.eviChange < 0 ? '#ef4444' : '#6b7280'
                          }}>
                            {comparisonResult.eviChange > 0 ? '+' : ''}{comparisonResult.eviChange.toFixed(3)}
                          </span>
                          <span className="text-sm text-muted-foreground">
                            ({comparisonResult.image1.evi.toFixed(2)} → {comparisonResult.image2.evi.toFixed(2)})
                          </span>
                        </div>
                      </Card>
                    </div>

                    <Card className="p-4 bg-card">
                      <h4 className="mb-3">管理建议</h4>
                      <ul className="space-y-2">
                        {comparisonResult.recommendations.map((rec, index) => (
                          <li key={index} className="flex items-start gap-2 text-sm">
                            <span className="text-green-600 dark:text-green-400 mt-0.5">•</span>
                            <span>{rec}</span>
                          </li>
                        ))}
                      </ul>
                    </Card>
                  </div>
                )}
              </Card>
            </TabsContent>

            {/* 时序分析视图 */}
            <TabsContent value="timeseries" className="space-y-4">
              {timeSeriesAnalysis && (
                <>
                  <Card className="p-6 bg-card">
                    <h3 className="mb-4">生长趋势分析</h3>
                    <div className="grid grid-cols-4 gap-4 mb-6">
                      <Card className="p-4 bg-blue-50 dark:bg-blue-950">
                        <div className="text-sm text-muted-foreground mb-1">变化趋势</div>
                        <div className="flex items-center gap-2">
                          {timeSeriesAnalysis.trend === 'increasing' && <TrendingUp className="w-5 h-5 text-green-600 dark:text-green-400" />}
                          {timeSeriesAnalysis.trend === 'decreasing' && <TrendingDown className="w-5 h-5 text-red-600 dark:text-red-400" />}
                          {timeSeriesAnalysis.trend === 'stable' && <Activity className="w-5 h-5 text-blue-600 dark:text-blue-400" />}
                          {timeSeriesAnalysis.trend === 'fluctuating' && <Activity className="w-5 h-5 text-yellow-600 dark:text-yellow-400" />}
                          <span className="font-medium">
                            {timeSeriesAnalysis.trend === 'increasing' && '上升'}
                            {timeSeriesAnalysis.trend === 'decreasing' && '下降'}
                            {timeSeriesAnalysis.trend === 'stable' && '稳定'}
                            {timeSeriesAnalysis.trend === 'fluctuating' && '波动'}
                          </span>
                        </div>
                      </Card>
                      <Card className="p-4 bg-green-50 dark:bg-green-950">
                        <div className="text-sm text-muted-foreground mb-1">生长阶段</div>
                        <div className="text-lg text-green-600 dark:text-green-400">{timeSeriesAnalysis.growthStage}</div>
                      </Card>
                      <Card className="p-4 bg-purple-50 dark:bg-purple-950">
                        <div className="text-sm text-muted-foreground mb-1">健康分数</div>
                        <div className="text-2xl text-purple-600 dark:text-purple-400">{timeSeriesAnalysis.healthScore}</div>
                      </Card>
                      <Card className="p-4 bg-orange-50 dark:bg-orange-950">
                        <div className="text-sm text-muted-foreground mb-1">影像数量</div>
                        <div className="text-2xl text-orange-600 dark:text-orange-400">{timeSeriesAnalysis.dates.length}</div>
                      </Card>
                    </div>

                    {/* NDVI趋势图 */}
                    <div className="relative h-64 border rounded-lg p-4 bg-gray-50 dark:bg-gray-900">
                      <h4 className="text-sm mb-4">NDVI变化曲线</h4>
                      <svg className="w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none">
                        {/* 网格线 */}
                        {[0, 25, 50, 75, 100].map(y => (
                          <line
                            key={`grid-${y}`}
                            x1="0"
                            y1={y}
                            x2="100"
                            y2={y}
                            stroke="#e5e7eb"
                            strokeWidth="0.2"
                          />
                        ))}

                        {/* NDVI曲线 */}
                        <polyline
                          points={timeSeriesAnalysis.ndviValues.map((ndvi, i) =>
                            `${(i / (timeSeriesAnalysis.ndviValues.length - 1)) * 100},${100 - ndvi * 100}`
                          ).join(' ')}
                          fill="none"
                          stroke="#22c55e"
                          strokeWidth="1"
                        />

                        {/* 数据点 */}
                        {timeSeriesAnalysis.ndviValues.map((ndvi, i) => (
                          <circle
                            key={`point-${i}`}
                            cx={(i / (timeSeriesAnalysis.ndviValues.length - 1)) * 100}
                            cy={100 - ndvi * 100}
                            r="1.5"
                            fill="#22c55e"
                          />
                        ))}
                      </svg>

                      {/* 刻度标签 */}
                      <div className="flex justify-between text-xs text-muted-foreground mt-2">
                        <span>{timeSeriesAnalysis.dates[0]}</span>
                        <span>{timeSeriesAnalysis.dates[timeSeriesAnalysis.dates.length - 1]}</span>
                      </div>
                    </div>
                  </Card>

                  {/* 警报信息 */}
                  {timeSeriesAnalysis.alerts.length > 0 && (
                    <Card className="p-4 bg-amber-50 dark:bg-amber-950 border-amber-200 dark:border-amber-800">
                      <h4 className="mb-3 flex items-center gap-2">
                        <AlertCircle className="w-5 h-5 text-amber-600 dark:text-amber-400" />
                        注意事项
                      </h4>
                      <ul className="space-y-2">
                        {timeSeriesAnalysis.alerts.map((alert, index) => (
                          <li key={index} className="text-sm text-amber-800 dark:text-amber-200">
                            {alert}
                          </li>
                        ))}
                      </ul>
                    </Card>
                  )}
                </>
              )}
            </TabsContent>
          </Tabs>

          {/* 时间滑块（所有视图通用） */}
          {images.length > 0 && (
            <Card className="p-4 bg-card">
              <div className="flex items-center gap-4">
                <Calendar className="w-5 h-5 text-green-600 dark:text-green-400" />
                <div className="flex-1">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm">时间轴</span>
                    <span className="text-sm text-muted-foreground">
                      {images[timeSliderValue[0]] && formatImageDate(images[timeSliderValue[0]].date)}
                    </span>
                  </div>
                  <Slider
                    value={timeSliderValue}
                    onValueChange={handleTimeSliderChange}
                    max={images.length - 1}
                    step={1}
                    className="w-full"
                  />
                  <div className="flex justify-between text-xs text-muted-foreground mt-2">
                    <span>{images[0] && formatImageDate(images[0].date)}</span>
                    <span>{images[images.length - 1] && formatImageDate(images[images.length - 1].date)}</span>
                  </div>
                </div>
              </div>
            </Card>
          )}

          {/* 影像列表 */}
          <Card className="p-4 bg-card">
            <h3 className="mb-4">历史影像列表</h3>
            <div className="grid grid-cols-3 gap-3">
              {images.map((image, index) => (
                <div
                  key={image.id}
                  className={`p-3 border rounded-lg cursor-pointer transition-all ${
                    selectedImage?.id === image.id
                      ? 'border-green-500 bg-green-50 dark:bg-green-950'
                      : 'border-gray-200 dark:border-gray-700 hover:border-green-300 dark:hover:border-green-700'
                  }`}
                  onClick={() => handleImageSelect(image, index)}
                >
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <ImageIcon className="w-4 h-4 text-green-600 dark:text-green-400" />
                      <span className="text-sm font-medium">{formatImageDate(image.date)}</span>
                    </div>
                    <Badge className={`font-light ${getCloudCoverColorClass(image.cloudCover)}`}>
                      <Cloud className="w-3 h-3 mr-1" />
                      {image.cloudCover.toFixed(0)}%
                    </Badge>
                  </div>
                  <div className="space-y-1 text-xs">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">数据源:</span>
                      <span>{image.source}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">分辨率:</span>
                      <span>{image.resolution}m</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">NDVI:</span>
                      <span style={{ color: SatelliteImageService.getNDVIColor(image.ndvi) }}>
                        {image.ndvi.toFixed(2)}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">EVI:</span>
                      <span>{image.evi.toFixed(2)}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
        <div className="flex gap-2">
          <AlertCircle className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
          <div className="text-sm text-blue-800 dark:text-blue-200">
            <p className="mb-2">遥感影像功能说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>时序影像</strong>：通过时间滑块查看同一地块不同时期的卫星影像，直观对比地块变化</li>
              <li>• <strong>影像对比</strong>：选择两个时期的影像进行对比，自动计算NDVI、EVI变化并生成管理建议</li>
              <li>• <strong>时序分析</strong>：分析NDVI变化趋势，判断作物生长阶段，计算健康分数</li>
              <li>• <strong>多数据源</strong>：支持Sentinel-2（10米）、Landsat-8（30米）、天地图等多种数据源</li>
              <li>• <strong>云量过滤</strong>：可设置最大云量阈值，自动过滤云量过高的影像，确保分析准确性</li>
              <li>• <strong>植被指数</strong>：NDVI（植被覆盖度）、EVI（高生物量敏感）、SAVI（土壤调节）、LAI（叶面积指数）</li>
              <li>• <strong>智能建议</strong>：根据影像变化自动生成灌溉、施肥、病虫害防治等管理建议</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );
}