'use client';

import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { SoilDataState, SoilDataAction, getPHLevel, getOrganicMatterLevel } from './soilDataReducer';

interface LayerDataDialogProps {
  state: SoilDataState;
  dispatch: React.Dispatch<SoilDataAction>;
}

export default function LayerDataDialog({ state, dispatch }: LayerDataDialogProps) {
  if (!state.selectedPoint) return null;

  return (
    <Dialog open={state.showLayerDialog} onOpenChange={(open) => {
      if (!open) {
        dispatch({ type: 'SET_SHOW_LAYER_DIALOG', payload: false });
        dispatch({ type: 'SET_SELECTED_POINT', payload: null });
      }
    }}>
      <DialogContent className="max-w-4xl">
        <DialogHeader>
          <DialogTitle>土壤剖面分层数据 - {state.selectedPoint.code}</DialogTitle>
          <DialogDescription className="sr-only">
            查看土壤剖面的分层详细数据
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 基本信息 */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 bg-muted rounded-lg">
            <div>
              <span className="text-xs text-muted-foreground">采样点:</span>
              <p className="text-sm font-medium">{state.selectedPoint.code}</p>
            </div>
            <div>
              <span className="text-xs text-muted-foreground">地块:</span>
              <p className="text-sm font-medium">{state.selectedPoint.fieldName}</p>
            </div>
            <div>
              <span className="text-xs text-muted-foreground">采样日期:</span>
              <p className="text-sm font-medium">{state.selectedPoint.sampleDate}</p>
            </div>
            <div>
              <span className="text-xs text-muted-foreground">采样人:</span>
              <p className="text-sm font-medium">{state.selectedPoint.sampler}</p>
            </div>
          </div>

          {/* 坐标信息 */}
          <div className="grid grid-cols-2 gap-4 p-4 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg">
            <div>
              <span className="text-xs text-blue-800 dark:text-blue-200">纬度:</span>
              <p className="text-sm font-medium text-blue-900 dark:text-blue-100">
                {state.selectedPoint.latitude.toFixed(6)}
              </p>
            </div>
            <div>
              <span className="text-xs text-blue-800 dark:text-blue-200">经度:</span>
              <p className="text-sm font-medium text-blue-900 dark:text-blue-100">
                {state.selectedPoint.longitude.toFixed(6)}
              </p>
            </div>
          </div>

          {/* 分层数据表格 */}
          <div className="border rounded-lg overflow-hidden">
            <table className="w-full">
              <thead className="bg-muted">
                <tr>
                  <th className="px-4 py-3 text-left text-sm font-medium">深度</th>
                  <th className="px-4 py-3 text-center text-sm font-medium">pH值</th>
                  <th className="px-4 py-3 text-center text-sm font-medium">有机质</th>
                  <th className="px-4 py-3 text-center text-sm font-medium">全氮</th>
                  <th className="px-4 py-3 text-center text-sm font-medium">有效磷</th>
                  <th className="px-4 py-3 text-center text-sm font-medium">速效钾</th>
                  <th className="px-4 py-3 text-center text-sm font-medium">含水量</th>
                </tr>
              </thead>
              <tbody>
                {state.selectedPoint.layers.map((layer, index) => (
                  <tr key={index} className="border-t">
                    <td className="px-4 py-3 font-medium">{layer.depth}</td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex items-center justify-center gap-2">
                        <span>{layer.pH}</span>
                        <div className={`w-2 h-2 rounded-full ${getPHLevel(layer.pH || 0).color}`} />
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <span className={getOrganicMatterLevel(layer.organicMatter || 0).color}>
                        {layer.organicMatter} g/kg
                      </span>
                    </td>
                    <td className="px-4 py-3 text-center">{layer.nitrogen} g/kg</td>
                    <td className="px-4 py-3 text-center">{layer.phosphorus} mg/kg</td>
                    <td className="px-4 py-3 text-center">{layer.potassium} mg/kg</td>
                    <td className="px-4 py-3 text-center">{layer.moisture}%</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 设备绑定信息 */}
          {state.selectedPoint.deviceId && (
            <div className="p-4 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-lg">
              <h4 className="text-sm font-medium text-green-900 dark:text-green-100 mb-2">绑定的IoT设备</h4>
              {(() => {
                const device = state.iotDevices.find(d => d.id === state.selectedPoint?.deviceId);
                return device ? (
                  <div className="text-sm text-green-800 dark:text-green-200">
                    <p><strong>设备编号:</strong> {device.code}</p>
                    <p><strong>设备名称:</strong> {device.name}</p>
                    <p><strong>设备类型:</strong> {device.type}</p>
                    <p><strong>设备状态:</strong>
                      <Badge variant={device.status === 'online' ? 'default' : 'secondary'} className="ml-2">
                        {device.status === 'online' ? '在线' : '离线'}
                      </Badge>
                    </p>
                    <p className="mt-2"><strong>最后更新:</strong> {device.data.lastUpdate}</p>
                  </div>
                ) : null;
              })()}
            </div>
          )}

          {/* 土壤质量评估 */}
          <div className="p-4 bg-amber-50 dark:bg-amber-950 border border-amber-200 dark:border-amber-800 rounded-lg">
            <h4 className="text-sm font-medium text-amber-900 dark:text-amber-100 mb-2">土壤质量评估</h4>
            <div className="text-sm text-amber-800 dark:text-amber-200 space-y-1">
              <p>• <strong>pH状况:</strong>
                {state.selectedPoint.layers[0]?.pH
                  ? ` 表层pH值为${state.selectedPoint.layers[0].pH}，呈${getPHLevel(state.selectedPoint.layers[0].pH).label}反应`
                  : ' 数据不足，无法评估'
                }
              </p>
              <p>• <strong>有机质含量:</strong>
                {state.selectedPoint.layers[0]?.organicMatter
                  ? ` 表层有机质含量为${state.selectedPoint.layers[0].organicMatter} g/kg，${getOrganicMatterLevel(state.selectedPoint.layers[0].organicMatter).label}水平`
                  : ' 数据不足，无法评估'
                }
              </p>
              <p>• <strong>养分状况:</strong>
                {state.selectedPoint.layers[0]?.nitrogen && state.selectedPoint.layers[0]?.phosphorus && state.selectedPoint.layers[0]?.potassium
                  ? ` 氮磷钾含量分别为${state.selectedPoint.layers[0].nitrogen}、${state.selectedPoint.layers[0].phosphorus}、${state.selectedPoint.layers[0].potassium} mg/kg`
                  : ' 数据不足，无法评估'
                }
              </p>
              <p>• <strong>综合评价:</strong>
                {state.selectedPoint.layers[0]?.pH && state.selectedPoint.layers[0]?.organicMatter
                  ? (state.selectedPoint.layers[0].pH >= 6.5 && state.selectedPoint.layers[0].pH <= 7.5 && state.selectedPoint.layers[0].organicMatter >= 20
                    ? ' 土壤理化性状良好，适宜大多数作物生长'
                    : ' 土壤需要改良，建议增施有机肥和调节pH值')
                  : ' 数据不足，无法进行综合评价'
                }
              </p>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}