import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Label } from '../ui/label';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Slider } from '../ui/slider';
import {
  Box,
  Layers,
  Eye,
  RotateCw,
  ZoomIn,
  ZoomOut,
  Grid3x3,
  TrendingUp,
  Activity,
  AlertCircle,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function LayerSamplingAnalysis() {
  const [selectedField, setSelectedField] = useState('field-1');
  const [selectedNutrient, setSelectedNutrient] = useState<'organic' | 'nitrogen' | 'phosphorus' | 'potassium'>('organic');
  const [viewMode, setViewMode] = useState<'3d' | 'slice' | 'contour'>('3d');
  const [depthSlice, setDepthSlice] = useState([20]); // 当前切片深度
  const [rotationAngle, setRotationAngle] = useState(45);
  const [zoomLevel, setZoomLevel] = useState(100);

  // 模拟三维数据
  const layers3DData = [
    { depth: '0-20cm', avgValue: 28.5, distribution: [25, 28, 32, 27, 30, 26, 29, 31, 28, 27] },
    { depth: '20-40cm', avgValue: 20.2, distribution: [18, 21, 23, 19, 22, 20, 21, 22, 19, 20] },
    { depth: '40-60cm', avgValue: 13.5, distribution: [12, 14, 15, 13, 14, 12, 13, 15, 14, 13] },
  ];

  const nutrientConfig = {
    organic: { label: '有机质', unit: 'g/kg', color: '#22c55e', min: 0, max: 40 },
    nitrogen: { label: '全氮', unit: 'g/kg', color: '#3b82f6', min: 0, max: 2 },
    phosphorus: { label: '有效磷', unit: 'mg/kg', color: '#f59e0b', min: 0, max: 40 },
    potassium: { label: '速效钾', unit: 'mg/kg', color: '#a855f7', min: 0, max: 250 },
  };

  const currentNutrient = nutrientConfig[selectedNutrient];

  const handleRotate = () => {
    setRotationAngle((prev) => (prev + 45) % 360);
    toast.success(`旋转至 ${(rotationAngle + 45) % 360}°`);
  };

  const getColorForValue = (value: number, nutrient: typeof selectedNutrient) => {
    const config = nutrientConfig[nutrient];
    const ratio = (value - config.min) / (config.max - config.min);
    
    if (ratio < 0.2) return '#ef4444'; // 红色 - 很低
    if (ratio < 0.4) return '#f97316'; // 橙色 - 低
    if (ratio < 0.6) return '#eab308'; // 黄色 - 中
    if (ratio < 0.8) return '#84cc16'; // 黄绿 - 较高
    return '#22c55e'; // 绿色 - 高
  };

  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={handleRotate}>
            <RotateCw className="w-4 h-4 mr-2" />
            旋转视角
          </Button>
        </div>
      </div>

      {/* 控制面板 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4">
          <Label className="mb-2">选择地块</Label>
          <Select value={selectedField} onValueChange={setSelectedField}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="field-1">东区1号地</SelectItem>
              <SelectItem value="field-2">西区2号地</SelectItem>
              <SelectItem value="field-3">南区3号地</SelectItem>
            </SelectContent>
          </Select>
        </Card>

        <Card className="p-4">
          <Label className="mb-2">选择养分指标</Label>
          <Select value={selectedNutrient} onValueChange={(v: any) => setSelectedNutrient(v)}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="organic">有机质</SelectItem>
              <SelectItem value="nitrogen">全氮</SelectItem>
              <SelectItem value="phosphorus">有效磷</SelectItem>
              <SelectItem value="potassium">速效钾</SelectItem>
            </SelectContent>
          </Select>
        </Card>

        <Card className="p-4">
          <Label className="mb-2">可视化模式</Label>
          <div className="flex gap-2">
            <Button
              variant={viewMode === '3d' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('3d')}
              className="flex-1"
            >
              <Box className="w-4 h-4 mr-1" />
              3D
            </Button>
            <Button
              variant={viewMode === 'slice' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('slice')}
              className="flex-1"
            >
              <Layers className="w-4 h-4 mr-1" />
              切片
            </Button>
            <Button
              variant={viewMode === 'contour' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('contour')}
              className="flex-1"
            >
              <Grid3x3 className="w-4 h-4 mr-1" />
              等值
            </Button>
          </div>
        </Card>

        <Card className="p-4">
          <Label className="mb-2">缩放比例</Label>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setZoomLevel(Math.max(50, zoomLevel - 10))}
            >
              <ZoomOut className="w-4 h-4" />
            </Button>
            <span className="text-sm flex-1 text-center">{zoomLevel}%</span>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setZoomLevel(Math.min(200, zoomLevel + 10))}
            >
              <ZoomIn className="w-4 h-4" />
            </Button>
          </div>
        </Card>
      </div>

      {/* 主可视化区域 */}
      <div className="grid grid-cols-3 gap-6">
        {/* 左侧：三维视图 */}
        <div className="col-span-2">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <Box className="w-5 h-5 text-green-600" />
                <h3>
                  {viewMode === '3d' && '三维分布模型'}
                  {viewMode === 'slice' && '立体切片图'}
                  {viewMode === 'contour' && '等值面图'}
                </h3>
              </div>
              <Badge>{currentNutrient.label}</Badge>
            </div>

            {/* 三维可视化容器 */}
            <div 
              className="relative bg-gradient-to-br from-gray-100 to-gray-50 rounded-lg border-2 border-gray-200 overflow-hidden"
              style={{ height: '500px' }}
            >
              {/* 3D模式 */}
              {viewMode === '3d' && (
                <div className="absolute inset-0 flex items-center justify-center p-8">
                  <div 
                    className="relative w-full h-full"
                    style={{ 
                      transform: `perspective(1000px) rotateX(60deg) rotateZ(${rotationAngle}deg) scale(${zoomLevel / 100})`,
                      transformStyle: 'preserve-3d',
                      transition: 'transform 0.5s ease',
                    }}
                  >
                    {/* 绘制三个土层 */}
                    {layers3DData.map((layer, layerIndex) => {
                      const offsetY = layerIndex * 60;
                      return (
                        <div
                          key={layerIndex}
                          className="absolute"
                          style={{
                            width: '300px',
                            height: '200px',
                            left: '50%',
                            top: '50%',
                            marginLeft: '-150px',
                            marginTop: '-100px',
                            transform: `translateZ(${-offsetY}px)`,
                            transformStyle: 'preserve-3d',
                          }}
                        >
                          {/* 网格化显示养分分布 */}
                          <div className="grid grid-cols-5 grid-rows-2 w-full h-full gap-1">
                            {layer.distribution.map((value, cellIndex) => (
                              <div
                                key={cellIndex}
                                className="rounded shadow-lg border border-white/30"
                                style={{
                                  backgroundColor: getColorForValue(value, selectedNutrient),
                                  opacity: 0.85,
                                }}
                                title={`${value} ${currentNutrient.unit}`}
                              />
                            ))}
                          </div>
                          
                          {/* 层标签 */}
                          <div className="absolute -left-20 top-1/2 transform -translate-y-1/2 bg-white px-3 py-1 rounded shadow text-sm font-medium whitespace-nowrap">
                            {layer.depth}
                          </div>
                        </div>
                      );
                    })}

                    {/* 坐标轴 */}
                    <div className="absolute bottom-0 left-1/2 transform -translate-x-1/2 text-xs text-muted-foreground">
                      水平方向 →
                    </div>
                    <div className="absolute left-0 top-1/2 transform -translate-y-1/2 -rotate-90 text-xs text-muted-foreground">
                      深度 ↓
                    </div>
                  </div>
                </div>
              )}

              {/* 切片模式 */}
              {viewMode === 'slice' && (
                <div className="p-8">
                  <div className="mb-4">
                    <Label className="mb-2">选择切片深度</Label>
                    <Slider
                      value={depthSlice}
                      onValueChange={setDepthSlice}
                      max={60}
                      step={10}
                      className="w-full"
                    />
                    <div className="flex justify-between text-xs text-muted-foreground mt-2">
                      <span>0cm</span>
                      <span className="font-medium">{depthSlice[0]}cm</span>
                      <span>60cm</span>
                    </div>
                  </div>

                  {/* 切片视图 */}
                  <div className="grid grid-cols-5 grid-rows-5 gap-2 w-full aspect-square">
                    {Array.from({ length: 25 }).map((_, index) => {
                      // 根据深度和位置插值计算养分值
                      const layerIndex = Math.floor(depthSlice[0] / 20);
                      const baseValue = layers3DData[layerIndex]?.avgValue || 15;
                      const variation = (Math.sin(index * 0.5) * 5);
                      const value = baseValue + variation;

                      return (
                        <div
                          key={index}
                          className="rounded-lg shadow-md border-2 border-white flex items-center justify-center text-xs"
                          style={{
                            backgroundColor: getColorForValue(value, selectedNutrient),
                          }}
                        >
                          <span className="text-white font-medium drop-shadow">
                            {value.toFixed(1)}
                          </span>
                        </div>
                      );
                    })}
                  </div>

                  <div className="mt-4 text-center text-sm text-muted-foreground">
                    {depthSlice[0]}cm 深度的水平切片
                  </div>
                </div>
              )}

              {/* 等值线模式 */}
              {viewMode === 'contour' && (
                <div className="p-8">
                  <div className="relative w-full h-full">
                    <svg className="w-full h-full">
                      {/* 绘制等值线 */}
                      {[30, 25, 20, 15, 10].map((value, index) => {
                        const radius = 50 + index * 40;
                        const color = getColorForValue(value, selectedNutrient);
                        return (
                          <g key={value}>
                            <ellipse
                              cx="50%"
                              cy="50%"
                              rx={`${radius}%`}
                              ry={`${radius * 0.7}%`}
                              fill={color}
                              fillOpacity="0.3"
                              stroke={color}
                              strokeWidth="2"
                            />
                            <text
                              x={`${50 + radius * 0.7}%`}
                              y="50%"
                              className="text-xs"
                              fill={color}
                            >
                              {value} {currentNutrient.unit}
                            </text>
                          </g>
                        );
                      })}
                    </svg>
                    <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 text-sm text-muted-foreground">
                      表层（0-20cm）等值线分布图
                    </div>
                  </div>
                </div>
              )}

              {/* 视图控制提示 */}
              <div className="absolute top-4 right-4 bg-white/90 backdrop-blur px-3 py-2 rounded-lg shadow text-xs">
                <div className="flex items-center gap-2">
                  <Eye className="w-4 h-4 text-green-600" />
                  <span>视角: {rotationAngle}°</span>
                </div>
              </div>
            </div>

            {/* 颜色图例 */}
            <div className="mt-4 p-4 bg-gray-50 rounded-lg">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium">养分含量图例</span>
                <span className="text-xs text-muted-foreground">单位: {currentNutrient.unit}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs">{currentNutrient.min}</span>
                <div className="flex-1 h-6 rounded-full" style={{
                  background: 'linear-gradient(to right, #ef4444, #f97316, #eab308, #84cc16, #22c55e)',
                }} />
                <span className="text-xs">{currentNutrient.max}</span>
              </div>
              <div className="flex justify-between mt-2 text-xs text-muted-foreground">
                <span>很低</span>
                <span>低</span>
                <span>中等</span>
                <span>较高</span>
                <span>高</span>
              </div>
            </div>
          </Card>
        </div>

        {/* 右侧：数据分析 */}
        <div className="space-y-4">
          {/* 垂直分布趋势 */}
          <Card className="p-4">
            <div className="flex items-center gap-2 mb-3">
              <Activity className="w-5 h-5 text-blue-600" />
              <h4>垂直分布趋势</h4>
            </div>
            <div className="space-y-3">
              {layers3DData.map((layer, index) => (
                <div key={index}>
                  <div className="flex items-center justify-between text-sm mb-1">
                    <span className="text-muted-foreground">{layer.depth}</span>
                    <span className="font-medium">
                      {layer.avgValue} {currentNutrient.unit}
                    </span>
                  </div>
                  <div className="w-full h-2 bg-gray-100 rounded-full overflow-hidden">
                    <div
                      className="h-full transition-all"
                      style={{
                        width: `${(layer.avgValue / currentNutrient.max) * 100}%`,
                        backgroundColor: getColorForValue(layer.avgValue, selectedNutrient),
                      }}
                    />
                  </div>
                </div>
              ))}
            </div>

            <div className="mt-4 pt-4 border-t">
              <div className="text-sm space-y-1">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">递减率:</span>
                  <span className="text-red-600">-29.1%/20cm</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">表层富集:</span>
                  <span className="text-green-600">明显</span>
                </div>
              </div>
            </div>
          </Card>

          {/* 水平变异性 */}
          <Card className="p-4">
            <div className="flex items-center gap-2 mb-3">
              <TrendingUp className="w-5 h-5 text-orange-600" />
              <h4>水平变异性</h4>
            </div>
            <div className="space-y-3 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">变异系数:</span>
                <span>14.8%</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">变异等级:</span>
                <Badge className="bg-yellow-500">中等变异</Badge>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">最高值:</span>
                <span className="text-green-600">32.1 {currentNutrient.unit}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">最低值:</span>
                <span className="text-orange-600">22.3 {currentNutrient.unit}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">极差:</span>
                <span>9.8 {currentNutrient.unit}</span>
              </div>
            </div>
          </Card>

          {/* 插值算法说明 */}
          <Card className="p-4 bg-blue-50 border-blue-200">
            <h4 className="mb-2 text-blue-900">插值算法</h4>
            <div className="text-xs text-blue-800 space-y-1">
              <p>• <strong>克里金插值</strong>（Kriging）</p>
              <p>• 考虑空间自相关性</p>
              <p>• 最佳无偏估计</p>
              <p>• 适用于土壤养分空间预测</p>
            </div>
          </Card>

          {/* 分析结论 */}
          <Card className="p-4 bg-green-50 border-green-200">
            <h4 className="mb-2 text-green-900">分析结论</h4>
            <ul className="text-xs text-green-800 space-y-1">
              <li>• 养分在垂直方向呈递减分布</li>
              <li>• 表层（0-20cm）含量最高</li>
              <li>• 水平分布呈中等变异</li>
              <li>• 建议分层精准施肥</li>
            </ul>
          </Card>
        </div>
      </div>

      {/* 分层数据对比表 */}
      <Card className="p-6">
        <h3 className="mb-4">分层数据详细对比</h3>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-sm">土层深度</th>
                <th className="px-4 py-3 text-center text-sm">有机质 (g/kg)</th>
                <th className="px-4 py-3 text-center text-sm">全氮 (g/kg)</th>
                <th className="px-4 py-3 text-center text-sm">有效磷 (mg/kg)</th>
                <th className="px-4 py-3 text-center text-sm">速效钾 (mg/kg)</th>
                <th className="px-4 py-3 text-center text-sm">平均pH值</th>
                <th className="px-4 py-3 text-center text-sm">含水量 (%)</th>
              </tr>
            </thead>
            <tbody>
              <tr className="border-t">
                <td className="px-4 py-3 font-medium">0-20cm</td>
                <td className="px-4 py-3 text-center">28.5</td>
                <td className="px-4 py-3 text-center">1.2</td>
                <td className="px-4 py-3 text-center">25.3</td>
                <td className="px-4 py-3 text-center">180</td>
                <td className="px-4 py-3 text-center">6.8</td>
                <td className="px-4 py-3 text-center">22.5</td>
              </tr>
              <tr className="border-t bg-gray-50">
                <td className="px-4 py-3 font-medium">20-40cm</td>
                <td className="px-4 py-3 text-center">20.2</td>
                <td className="px-4 py-3 text-center">0.8</td>
                <td className="px-4 py-3 text-center">18.5</td>
                <td className="px-4 py-3 text-center">145</td>
                <td className="px-4 py-3 text-center">6.5</td>
                <td className="px-4 py-3 text-center">25.8</td>
              </tr>
              <tr className="border-t">
                <td className="px-4 py-3 font-medium">40-60cm</td>
                <td className="px-4 py-3 text-center">13.5</td>
                <td className="px-4 py-3 text-center">0.5</td>
                <td className="px-4 py-3 text-center">12.3</td>
                <td className="px-4 py-3 text-center">98</td>
                <td className="px-4 py-3 text-center">6.3</td>
                <td className="px-4 py-3 text-center">28.2</td>
              </tr>
              <tr className="border-t bg-yellow-50">
                <td className="px-4 py-3 font-medium">层间变化率</td>
                <td className="px-4 py-3 text-center text-red-600">-29.1%</td>
                <td className="px-4 py-3 text-center text-red-600">-33.3%</td>
                <td className="px-4 py-3 text-center text-red-600">-26.8%</td>
                <td className="px-4 py-3 text-center text-red-600">-19.4%</td>
                <td className="px-4 py-3 text-center text-orange-600">-7.4%</td>
                <td className="px-4 py-3 text-center text-blue-600">+25.3%</td>
              </tr>
            </tbody>
          </table>
        </div>
      </Card>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <div className="flex gap-2">
          <AlertCircle className="w-5 h-5 text-blue-600 flex-shrink-0" />
          <div className="text-sm text-blue-800">
            <p className="mb-2">三维可视化分析说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>三维模型</strong>: 立体展示土壤养分的空间分布，支持旋转和缩放</li>
              <li>• <strong>立体切片</strong>: 选择任意深度查看该层的水平分布热力图</li>
              <li>• <strong>等值面图</strong>: 以等值线形式展示养分浓度分布</li>
              <li>• <strong>克里金插值</strong>: 基于采样点数据，使用地统计学方法生成连续分布模型</li>
              <li>• <strong>垂直分析</strong>: 分析养分在土壤剖面的递减规律</li>
              <li>• <strong>水平变异</strong>: 评估同一深度养分分布的均匀性</li>
              <li>• <strong>精准施肥</strong>: 根据三维分布特征制定分层分区施肥方案</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );
}
