'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { SpatialField } from './spatialQueryReducer';
import {
  MapPin,
  AreaChart,
  Ruler,
  User,
  Calendar,
  RefreshCw,
  Eye,
  FileText,
  Database
} from 'lucide-react';

interface ResultsPanelProps {
  results: SpatialField[] | null;
  isLoading: boolean;
  onViewOnMap: (fields: SpatialField[]) => void;
  onExportData: () => void;
  onClearResults: () => void;
}

export function ResultsPanel({ results, isLoading, onViewOnMap, onExportData, onClearResults }: ResultsPanelProps) {
  if (isLoading) {
    return (
      <Card className="p-6 bg-card">
        <div className="flex items-center justify-center py-12">
          <div className="text-center space-y-3">
            <RefreshCw className="w-8 h-8 text-blue-600 dark:text-blue-400 animate-spin mx-auto" />
            <p className="text-muted-foreground">正在执行空间查询...</p>
          </div>
        </div>
      </Card>
    );
  }

  if (!results || results.length === 0) {
    return (
      <Card className="p-6 bg-card">
        <div className="flex items-center justify-center py-12">
          <div className="text-center space-y-3">
            <Database className="w-12 h-12 text-muted-foreground mx-auto" />
            <h3 className="text-lg font-medium">暂无查询结果</h3>
            <p className="text-sm text-muted-foreground max-w-md">
              请设置查询参数并执行查询，这里将显示查询到的地块信息
            </p>
          </div>
        </div>
      </Card>
    );
  }

  // 计算统计信息
  const totalArea = results.reduce((sum, field) => sum + field.area, 0);
  const totalPerimeter = results.reduce((sum, field) => sum + field.perimeter, 0);
  const soilTypes = [...new Set(results.map(field => field.soilType))];
  const plantingModes = [...new Set(results.map(field => field.plantingMode))];

  return (
    <div className="space-y-6">
      {/* 查询结果统计 */}
      <Card className="p-6 bg-card">
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold">查询结果统计</h3>
            <Badge variant="secondary" className="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200">
              {results.length} 个地块
            </Badge>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="p-3 bg-green-50 dark:bg-green-950 rounded-lg border border-green-200 dark:border-green-800">
              <div className="flex items-center gap-2 mb-1">
                <AreaChart className="w-4 h-4 text-green-600 dark:text-green-400" />
                <span className="text-sm text-green-800 dark:text-green-200">总面积</span>
              </div>
              <div className="text-xl font-bold text-green-700 dark:text-green-300">
                {totalArea.toFixed(1)}
              </div>
              <div className="text-xs text-green-600 dark:text-green-400">亩</div>
            </div>

            <div className="p-3 bg-blue-50 dark:bg-blue-950 rounded-lg border border-blue-200 dark:border-blue-800">
              <div className="flex items-center gap-2 mb-1">
                <Ruler className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                <span className="text-sm text-blue-800 dark:text-blue-200">总周长</span>
              </div>
              <div className="text-xl font-bold text-blue-700 dark:text-blue-300">
                {totalPerimeter.toFixed(0)}
              </div>
              <div className="text-xs text-blue-600 dark:text-blue-400">米</div>
            </div>

            <div className="p-3 bg-purple-50 dark:bg-purple-950 rounded-lg border border-purple-200 dark:border-purple-800">
              <div className="flex items-center gap-2 mb-1">
                <MapPin className="w-4 h-4 text-purple-600 dark:text-purple-400" />
                <span className="text-sm text-purple-800 dark:text-purple-200">土壤类型</span>
              </div>
              <div className="text-xl font-bold text-purple-700 dark:text-purple-300">
                {soilTypes.length}
              </div>
              <div className="text-xs text-purple-600 dark:text-purple-400">种类型</div>
            </div>

            <div className="p-3 bg-orange-50 dark:bg-orange-950 rounded-lg border border-orange-200 dark:border-orange-800">
              <div className="flex items-center gap-2 mb-1">
                <FileText className="w-4 h-4 text-orange-600 dark:text-orange-400" />
                <span className="text-sm text-orange-800 dark:text-orange-200">种植模式</span>
              </div>
              <div className="text-xl font-bold text-orange-700 dark:text-orange-300">
                {plantingModes.length}
              </div>
              <div className="text-xs text-orange-600 dark:text-orange-400">种模式</div>
            </div>
          </div>

          <div className="flex gap-2">
            <Button
              variant="outline"
              className="flex-1"
              onClick={() => onViewOnMap(results)}
            >
              <Eye className="w-4 h-4 mr-2" />
              在地图上查看
            </Button>
            <Button
              variant="outline"
              className="flex-1"
              onClick={onExportData}
            >
              <Database className="w-4 h-4 mr-2" />
              导出数据
            </Button>
            <Button
              variant="ghost"
              onClick={onClearResults}
            >
              <RefreshCw className="w-4 h-4" />
            </Button>
          </div>
        </div>
      </Card>

      {/* 地块详细列表 */}
      <Card className="p-6 bg-card">
        <div className="space-y-4">
          <h3 className="text-lg font-semibold">地块详细信息</h3>

          <div className="space-y-3 max-h-96 overflow-y-auto">
            {results.map((field, index) => (
              <div key={field.id} className="p-4 border rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <h4 className="font-medium text-base">{field.name}</h4>
                    <p className="text-sm text-muted-foreground">{field.code}</p>
                  </div>
                  <Badge variant="outline" className="font-light">
                    #{index + 1}
                  </Badge>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">面积</span>
                    <div className="font-medium text-green-600 dark:text-green-400">
                      {field.area.toFixed(1)} 亩
                    </div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">周长</span>
                    <div className="font-medium text-blue-600 dark:text-blue-400">
                      {field.perimeter.toFixed(0)} 米
                    </div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">中心坐标</span>
                    <div className="font-medium text-xs">
                      {field.centroid.lat.toFixed(4)}, {field.centroid.lng.toFixed(4)}
                    </div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">状态</span>
                    <div>
                      <Badge
                        variant={field.status === 'active' ? 'default' : 'secondary'}
                        className="text-xs font-light"
                      >
                        {field.status === 'active' ? '活跃' : '未激活'}
                      </Badge>
                    </div>
                  </div>
                </div>

                <Separator className="my-3" />

                <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">土壤类型:</span>
                    <Badge variant="outline" className="font-light">
                      {getSoilTypeName(field.soilType)}
                    </Badge>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">种植模式:</span>
                    <Badge variant="outline" className="font-light">
                      {getPlantingModeName(field.plantingMode)}
                    </Badge>
                  </div>
                  <div className="flex items-center gap-2">
                    <User className="w-3 h-3 text-muted-foreground" />
                    <span className="text-muted-foreground">负责人:</span>
                    <span className="font-medium">{field.owner}</span>
                  </div>
                </div>

                <div className="flex items-center gap-2 mt-2 text-xs text-muted-foreground">
                  <Calendar className="w-3 h-3" />
                  <span>创建时间: {field.createdAt}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </Card>

      {/* 分类统计 */}
      <Card className="p-6 bg-card">
        <div className="space-y-4">
          <h3 className="text-lg font-semibold">分类统计</h3>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 土壤类型分布 */}
            <div>
              <h4 className="font-medium mb-3">土壤类型分布</h4>
              <div className="space-y-2">
                {soilTypes.map(soilType => {
                  const fields = results.filter(field => field.soilType === soilType);
                  const area = fields.reduce((sum, field) => sum + field.area, 0);
                  const percentage = (area / totalArea * 100).toFixed(1);

                  return (
                    <div key={soilType} className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full" style={{ backgroundColor: getSoilTypeColor(soilType) }} />
                        <span className="text-sm">{getSoilTypeName(soilType)}</span>
                      </div>
                      <div className="text-right">
                        <div className="text-sm font-medium">{area.toFixed(1)} 亩</div>
                        <div className="text-xs text-muted-foreground">{percentage}%</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* 种植模式分布 */}
            <div>
              <h4 className="font-medium mb-3">种植模式分布</h4>
              <div className="space-y-2">
                {plantingModes.map(mode => {
                  const fields = results.filter(field => field.plantingMode === mode);
                  const area = fields.reduce((sum, field) => sum + field.area, 0);
                  const percentage = (area / totalArea * 100).toFixed(1);

                  return (
                    <div key={mode} className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full" style={{ backgroundColor: getPlantingModeColor(mode) }} />
                        <span className="text-sm">{getPlantingModeName(mode)}</span>
                      </div>
                      <div className="text-right">
                        <div className="text-sm font-medium">{area.toFixed(1)} 亩</div>
                        <div className="text-xs text-muted-foreground">{percentage}%</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}

// 获取土壤类型名称
function getSoilTypeName(type: string): string {
  const soilTypes: Record<string, string> = {
    'sandy': '沙质土',
    'clay': '黏质土',
    'loamy': '壤质土',
    'peat': '泥炭土',
    'saline': '盐碱土',
    'silt': '粉质土',
    'rocky': '岩石土'
  };
  return soilTypes[type] || type;
}

// 获取土壤类型颜色
function getSoilTypeColor(type: string): string {
  const colors: Record<string, string> = '#fbbf24'; // 黄色
  const colorMap: Record<string, string> = {
    'sandy': '#fbbf24', // 黄色
    'clay': '#a78bfa', // 紫色
    'loamy': '#60a5fa', // 蓝色
    'peat': '#8b5cf6', // 深紫色
    'saline': '#f87171', // 红色
    'silt': '#34d399', // 绿色
    'rocky': '#6b7280' // 灰色
  };
  return colorMap[type] || '#6b7280';
}

// 获取种植模式名称
function getPlantingModeName(mode: string): string {
  const modes: Record<string, string> = {
    'conventional': '传统种植',
    'organic': '有机种植',
    'greenhouse': '温室种植',
    'hydroponic': '水培种植',
    'aeroponic': '气培种植'
  };
  return modes[mode] || mode;
}

// 获取种植模式颜色
function getPlantingModeColor(mode: string): string {
  const colorMap: Record<string, string> = {
    'conventional': '#60a5fa', // 蓝色
    'organic': '#34d399', // 绿色
    'greenhouse': '#fbbf24', // 黄色
    'hydroponic': '#a78bfa', // 紫色
    'aeroponic': '#f87171' // 红色
  };
  return colorMap[mode] || '#6b7280';
}