'use client';

import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Box, Layers, Grid3x3, Eye, RotateCw, ZoomIn, ZoomOut } from 'lucide-react';

interface Visualization3DProps {
  viewMode: '3d' | 'slice' | 'contour';
  selectedNutrient: 'organic' | 'nitrogen' | 'phosphorus' | 'potassium';
  depthSlice: number[];
  rotationAngle: number;
  zoomLevel: number;
  onRotate: () => void;
  onZoomIn: () => void;
  onZoomOut: () => void;
}

export function Visualization3D({
  viewMode,
  selectedNutrient,
  depthSlice,
  rotationAngle,
  zoomLevel,
  onRotate,
  onZoomIn,
  onZoomOut,
}: Visualization3DProps) {
  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 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 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 (
    <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 dark:from-gray-800 dark:to-gray-900 rounded-lg border-2 border-gray-200 dark:border-gray-700 overflow-hidden"
        style={{ height: '500px' }}
      >
        {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-card px-3 py-1 rounded shadow text-sm font-medium whitespace-nowrap border">
                      {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">
              <div className="text-sm font-medium mb-2">选择切片深度</div>
              <div className="text-center text-lg font-semibold text-muted-foreground mb-4">
                {depthSlice[0]}cm
              </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 dark:border-gray-800 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>
          </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-card/90 backdrop-blur px-3 py-2 rounded-lg shadow text-xs border">
          <div className="flex items-center gap-2">
            <Eye className="w-4 h-4 text-green-600" />
            <span>视角: {rotationAngle}°</span>
          </div>
        </div>

        <div className="absolute bottom-4 right-4 flex gap-2">
          <button
            onClick={onRotate}
            className="bg-card hover:bg-muted p-2 rounded-lg shadow border transition-colors"
            title="旋转视角"
          >
            <RotateCw className="w-4 h-4" />
          </button>
          <button
            onClick={onZoomOut}
            className="bg-card hover:bg-muted p-2 rounded-lg shadow border transition-colors"
            title="缩小"
          >
            <ZoomOut className="w-4 h-4" />
          </button>
          <button
            onClick={onZoomIn}
            className="bg-card hover:bg-muted p-2 rounded-lg shadow border transition-colors"
            title="放大"
          >
            <ZoomIn className="w-4 h-4" />
          </button>
        </div>
      </div>

      <div className="mt-4 p-4 bg-muted 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>
  );
}