'use client';

import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { MapPin, Layers, Navigation } from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

interface SpatialDistributionProps {
  state: SpatialAnalysisState;
  dispatch: React.Dispatch<SpatialAnalysisAction>;
}

export default function SpatialDistribution({ state, dispatch }: SpatialDistributionProps) {
  const getScoreColor = (score: number) => {
    if (score >= 80) return 'bg-green-500';
    if (score >= 60) return 'bg-yellow-500';
    if (score >= 40) return 'bg-orange-500';
    return 'bg-red-500';
  };

  const getScoreTextColor = (score: number) => {
    if (score >= 80) return 'text-green-600';
    if (score >= 60) return 'text-yellow-600';
    if (score >= 40) return 'text-orange-600';
    return 'text-red-600';
  };

  const selectedBlocksWithScores = state.selectedBlocks.map(blockId => {
    const block = state.landBlocks.find(b => b.id === blockId);
    const result = state.analysisResults.find(r => r.blockId === blockId);
    return { block, result };
  }).filter(item => item.block);

  return (
    <Card className="p-6">
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-medium flex items-center gap-2">
          <MapPin className="w-5 h-5" />
          空间分布可视化
        </h3>
        <Badge variant="outline">
          {selectedBlocksWithScores.length} 个地块
        </Badge>
      </div>

      {/* 简化的地图展示 */}
      <div className="relative bg-gray-50 dark:bg-gray-900 rounded-lg p-8 min-h-[400px] flex items-center justify-center">
        {selectedBlocksWithScores.length === 0 ? (
          <div className="text-center text-muted-foreground">
            <MapPin className="w-16 h-16 mx-auto mb-4 opacity-50" />
            <p>请先选择地块以查看空间分布</p>
          </div>
        ) : (
          <div className="relative w-full h-full min-h-[350px]">
            {/* 模拟地图背景 */}
            <div className="absolute inset-0 bg-gradient-to-br from-green-50 to-blue-50 dark:from-green-950 dark:to-blue-950 rounded-lg opacity-30"></div>

            {/* 地块分布 */}
            <div className="relative h-full flex items-center justify-center">
              <div className="grid grid-cols-2 md:grid-cols-3 gap-6 w-full max-w-2xl">
                {selectedBlocksWithScores.map((item, index) => {
                  const positions = [
                    { top: '20%', left: '15%' },
                    { top: '25%', left: '60%' },
                    { top: '60%', left: '25%' },
                    { top: '65%', left: '70%' },
                    { top: '40%', left: '40%' },
                    { top: '30%', left: '80%' }
                  ];

                  const position = positions[index % positions.length];

                  return (
                    <div
                      key={item.block!.id}
                      className="absolute transform -translate-x-1/2 -translate-y-1/2"
                      style={position}
                    >
                      {/* 地块标记 */}
                      <div className="relative">
                        <div
                          className={`w-12 h-12 ${getScoreColor(item.result?.overallScore || 0)} rounded-full opacity-80 animate-pulse`}></div>
                        <div className="absolute inset-0 flex items-center justify-center">
                          <MapPin className="w-6 h-6 text-white" />
                        </div>

                        {/* 地块信息卡片 */}
                        <div className="absolute top-14 left-1/2 transform -translate-x-1/2 bg-white dark:bg-gray-800 border rounded-lg shadow-lg p-3 w-48 z-10">
                          <div className="flex items-center justify-between mb-2">
                            <h4 className="font-medium text-sm truncate">{item.block!.name}</h4>
                            <Badge
                              variant="outline"
                              className={`text-xs ${getScoreTextColor(item.result?.overallScore || 0)}`}
                            >
                              {item.result?.overallScore || '--'}分
                            </Badge>
                          </div>

                          <div className="space-y-1 text-xs text-muted-foreground">
                            <div className="flex justify-between">
                              <span>面积:</span>
                              <span>{item.block!.area} 亩</span>
                            </div>
                            <div className="flex justify-between">
                              <span>土壤:</span>
                              <span>{item.block!.soilType}</span>
                            </div>
                            {item.result && (
                              <>
                                <div className="flex justify-between">
                                  <span>土壤得分:</span>
                                  <span>{Math.round(item.result.soilScore)}</span>
                                </div>
                                <div className="flex justify-between">
                                  <span>气候得分:</span>
                                  <span>{Math.round(item.result.climateScore)}</span>
                                </div>
                              </>
                            )}
                            {item.result?.recommendedCrops[0] && (
                              <div className="pt-1 border-t">
                                <span className="text-blue-600">推荐: {item.result.recommendedCrops[0].crop.name}</span>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* 图例 */}
            <div className="absolute bottom-4 left-4 bg-white dark:bg-gray-800 border rounded-lg p-3 shadow-lg">
              <h4 className="font-medium text-sm mb-2 flex items-center gap-2">
                <Layers className="w-4 h-4" />
                适宜性等级
              </h4>
              <div className="space-y-1 text-xs">
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                  <span>优秀 (≥80分)</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
                  <span>良好 (60-79分)</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-orange-500 rounded-full"></div>
                  <span>一般 (40-59分)</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                  <span>较差 (&lt;40分)</span>
                </div>
              </div>
            </div>

            {/* 指北针 */}
            <div className="absolute top-4 right-4">
              <div className="w-12 h-12 bg-white dark:bg-gray-800 border rounded-full shadow-lg flex items-center justify-center">
                <Navigation className="w-6 h-6 text-gray-600 dark:text-gray-400" />
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 统计信息 */}
      {selectedBlocksWithScores.length > 0 && (
        <div className="mt-6 grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">
              {selectedBlocksWithScores.filter(item => (item.result?.overallScore || 0) >= 80).length}
            </div>
            <div className="text-sm text-muted-foreground">优秀地块</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">
              {Math.round(
                selectedBlocksWithScores.reduce((sum, item) => sum + (item.block?.area || 0), 0)
              )}
            </div>
            <div className="text-sm text-muted-foreground">总面积(亩)</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-purple-600">
              {selectedBlocksWithScores.length > 0
                ? Math.round(
                    selectedBlocksWithScores.reduce((sum, item) => sum + (item.result?.overallScore || 0), 0) /
                    selectedBlocksWithScores.length
                  )
                : 0}
            </div>
            <div className="text-sm text-muted-foreground">平均得分</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-orange-600">
              {[...new Set(
                selectedBlocksWithScores
                  .filter(item => item.result?.recommendedCrops[0])
                  .map(item => item.result!.recommendedCrops[0].crop.name)
              )].length}
            </div>
            <div className="text-sm text-muted-foreground">推荐作物</div>
          </div>
        </div>
      )}
    </Card>
  );
}