'use client';

import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, X, Save, Droplets, Leaf, Zap, TrendingUp } from 'lucide-react';
import { SoilDataState, SoilDataAction } from './soilDataReducer';

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

export default function AddSamplePointDialog({ state, dispatch }: AddSamplePointDialogProps) {
  const handleAddSamplePoint = () => {
    const newPoint = state.newPoint;

    if (!newPoint.code || !newPoint.fieldName || !newPoint.sampleDate || !newPoint.sampler) {
      return;
    }

    if (!newPoint.latitude || !newPoint.longitude || newPoint.latitude === 0 || newPoint.longitude === 0) {
      return;
    }

    // 从设备读取数据并填充到分层信息
    const layersWithData = (newPoint.layers || []).map(layer => {
      if (layer.deviceId) {
        const device = state.iotDevices.find(d => d.id === layer.deviceId);
        if (device) {
          return {
            ...layer,
            pH: device.data.pH,
            organicMatter: device.data.organicMatter,
            nitrogen: device.data.nitrogen,
            phosphorus: device.data.phosphorus,
            potassium: device.data.potassium,
            moisture: device.data.moisture,
          };
        }
      }
      return layer;
    });

    const samplePoint = {
      id: `sp-${Date.now()}`,
      ...newPoint,
      layers: layersWithData,
    } as any;

    dispatch({ type: 'ADD_SAMPLE_POINT', payload: samplePoint });
    dispatch({ type: 'SET_SHOW_ADD_DIALOG', payload: false });
    dispatch({ type: 'RESET_NEW_POINT' });
  };

  const handleMapPointSelect = (lat: number, lng: number) => {
    dispatch({ type: 'UPDATE_NEW_POINT', payload: { latitude: lat, longitude: lng } });
  };

  const handleAddLayer = () => {
    const currentLayers = state.newPoint.layers || [];
    const newLayer = {
      depth: `${currentLayers.length * 20}-${(currentLayers.length + 1) * 20}cm`,
      deviceId: '',
    };
    dispatch({
      type: 'UPDATE_NEW_POINT',
      payload: {
        layers: [...currentLayers, newLayer]
      }
    });
  };

  const handleUpdateLayerDevice = (layerIndex: number, deviceId: string) => {
    const updatedLayers = [...(state.newPoint.layers || [])];
    updatedLayers[layerIndex] = { ...updatedLayers[layerIndex], deviceId };
    dispatch({
      type: 'UPDATE_NEW_POINT',
      payload: { layers: updatedLayers }
    });
  };

  const handleRemoveLayer = (index: number) => {
    const currentLayers = state.newPoint.layers || [];
    if (currentLayers.length > 1) {
      const updatedLayers = currentLayers.filter((_, i) => i !== index);
      dispatch({
        type: 'UPDATE_NEW_POINT',
        payload: { layers: updatedLayers }
      });
    }
  };

  return (
    <Dialog open={state.showAddDialog} onOpenChange={(open) => {
      if (!open) {
        dispatch({ type: 'SET_SHOW_ADD_DIALOG', payload: false });
        dispatch({ type: 'RESET_NEW_POINT' });
      }
    }}>
      <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>新增采样点</DialogTitle>
          <DialogDescription className="sr-only">
            添加新的土壤采样点，包含GPS坐标定位和分层数据录入
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label>采样点编号 *</Label>
              <Input
                value={state.newPoint.code || ''}
                onChange={(e) => dispatch({ type: 'UPDATE_NEW_POINT', payload: { code: e.target.value } })}
                placeholder="如: SP004"
              />
            </div>
            <div>
              <Label>所属地块 *</Label>
              <Input
                value={state.newPoint.fieldName || ''}
                onChange={(e) => dispatch({ type: 'UPDATE_NEW_POINT', payload: { fieldName: e.target.value } })}
                placeholder="如: 东区1号地"
              />
            </div>
            <div>
              <Label>采样日期 *</Label>
              <Input
                type="date"
                value={state.newPoint.sampleDate || ''}
                onChange={(e) => dispatch({ type: 'UPDATE_NEW_POINT', payload: { sampleDate: e.target.value } })}
              />
            </div>
            <div>
              <Label>采样人 *</Label>
              <Input
                value={state.newPoint.sampler || ''}
                onChange={(e) => dispatch({ type: 'UPDATE_NEW_POINT', payload: { sampler: e.target.value } })}
                placeholder="如: 张三"
              />
            </div>
            <div className="md:col-span-2">
              <Label>IoT设备（可选）</Label>
              <Select
                value={state.newPoint.deviceId || 'none'}
                onValueChange={(value) => dispatch({ type: 'UPDATE_NEW_POINT', payload: { deviceId: value === 'none' ? '' : value } })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择物联网设备" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">不绑定设备</SelectItem>
                  {state.iotDevices.map((device) => (
                    <SelectItem key={device.id} value={device.id}>
                      <div className="flex items-center gap-2">
                        <span>{device.code} - {device.name}</span>
                        <Badge variant={device.status === 'online' ? 'default' : 'secondary'} className="ml-2">
                          {device.status === 'online' ? '在线' : '离线'}
                        </Badge>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {state.newPoint.deviceId && (() => {
                const device = state.iotDevices.find(d => d.id === state.newPoint.deviceId);
                return device ? (
                  <div className="mt-2 p-3 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-lg">
                    <div className="text-xs text-green-800 dark:text-green-200 mb-1">设备实时数据（最后更新：{device.data.lastUpdate}）</div>
                    <div className="grid grid-cols-2 md:grid-cols-6 gap-2 text-xs text-green-700 dark:text-green-300">
                      <div>pH: {device.data.pH}</div>
                      <div>有机质: {device.data.organicMatter}</div>
                      <div>全氮: {device.data.nitrogen}</div>
                      <div>有效磷: {device.data.phosphorus}</div>
                      <div>速效钾: {device.data.potassium}</div>
                      <div>含水量: {device.data.moisture}%</div>
                    </div>
                  </div>
                ) : null;
              })()}
            </div>
          </div>

          {/* GPS坐标定位 */}
          <div>
            <Label>GPS坐标定位 *</Label>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-2">
              <div>
                <Input
                  type="number"
                  value={state.newPoint.latitude || ''}
                  onChange={(e) => dispatch({ type: 'UPDATE_NEW_POINT', payload: { latitude: parseFloat(e.target.value) || 0 } })}
                  placeholder="纬度"
                  step="0.000001"
                />
              </div>
              <div>
                <Input
                  type="number"
                  value={state.newPoint.longitude || ''}
                  onChange={(e) => dispatch({ type: 'UPDATE_NEW_POINT', payload: { longitude: parseFloat(e.target.value) || 0 } })}
                  placeholder="经度"
                  step="0.000001"
                />
              </div>
            </div>
            <Card className="p-4 bg-muted">
              <div className="text-center text-muted-foreground">
                <p className="text-sm">地图选择器</p>
                <p className="text-xs mt-1">请在上方输入坐标或使用地图选择器</p>
              </div>
            </Card>
          </div>

          {/* 分层数据 */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <Label>土壤分层数据</Label>
              <Button type="button" size="sm" variant="outline" onClick={handleAddLayer}>
                <Plus className="w-4 h-4 mr-1" />
                添加土层
              </Button>
            </div>
            <div className="space-y-4">
              {(state.newPoint.layers || []).map((layer, layerIndex) => (
                <Card key={layerIndex} className="p-4">
                  <div className="flex items-center justify-between mb-3">
                    <h4>第 {layerIndex + 1} 层 ({layer.depth})</h4>
                    {(state.newPoint.layers || []).length > 1 && (
                      <Button
                        type="button"
                        size="sm"
                        variant="ghost"
                        onClick={() => handleRemoveLayer(layerIndex)}
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    )}
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                      <Label className="text-xs">深度 *</Label>
                      <Input
                        value={layer.depth}
                        onChange={(e) => {
                          const updatedLayers = [...(state.newPoint.layers || [])];
                          updatedLayers[layerIndex] = { ...updatedLayers[layerIndex], depth: e.target.value };
                          dispatch({ type: 'UPDATE_NEW_POINT', payload: { layers: updatedLayers } });
                        }}
                        placeholder="如: 0-20cm"
                      />
                    </div>
                    <div>
                      <Label className="text-xs">IoT设备（可选）</Label>
                      <Select
                        value={layer.deviceId || 'none'}
                        onValueChange={(value) => handleUpdateLayerDevice(layerIndex, value === 'none' ? '' : value)}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="选择设备读取数据" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">不绑定设备</SelectItem>
                          {state.iotDevices.map((device) => (
                            <SelectItem key={device.id} value={device.id}>
                              <span>{device.code} - {device.name}</span>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  {layer.deviceId && (() => {
                    const device = state.iotDevices.find(d => d.id === layer.deviceId);
                    return device ? (
                      <div className="mt-3 p-3 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg">
                        <div className="text-xs text-blue-800 dark:text-blue-200 mb-2">从设备读取的数据（最后更新：{device.data.lastUpdate}）</div>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 text-sm">
                          <div className="flex items-center gap-2">
                            <Droplets className="w-4 h-4 text-blue-600" />
                            <span>pH: <strong>{device.data.pH}</strong></span>
                          </div>
                          <div className="flex items-center gap-2">
                            <Leaf className="w-4 h-4 text-green-600" />
                            <span>有机质: <strong>{device.data.organicMatter}</strong> g/kg</span>
                          </div>
                          <div className="flex items-center gap-2">
                            <Zap className="w-4 h-4 text-blue-600" />
                            <span>全氮: <strong>{device.data.nitrogen}</strong> g/kg</span>
                          </div>
                          <div className="flex items-center gap-2">
                            <TrendingUp className="w-4 h-4 text-orange-600" />
                            <span>有效磷: <strong>{device.data.phosphorus}</strong> mg/kg</span>
                          </div>
                          <div className="flex items-center gap-2">
                            <TrendingUp className="w-4 h-4 text-purple-600" />
                            <span>速效钾: <strong>{device.data.potassium}</strong> mg/kg</span>
                          </div>
                          <div className="flex items-center gap-2">
                            <Droplets className="w-4 h-4 text-cyan-600" />
                            <span>含水量: <strong>{device.data.moisture}</strong>%</span>
                          </div>
                        </div>
                      </div>
                    ) : null;
                  })()}
                </Card>
              ))}
            </div>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button variant="outline" onClick={() => {
              dispatch({ type: 'SET_SHOW_ADD_DIALOG', payload: false });
              dispatch({ type: 'RESET_NEW_POINT' });
            }}>
              取消
            </Button>
            <Button
              className="bg-green-600 hover:bg-green-700"
              onClick={handleAddSamplePoint}
              disabled={!state.newPoint.code || !state.newPoint.fieldName || !state.newPoint.sampleDate || !state.newPoint.sampler || !state.newPoint.latitude || !state.newPoint.longitude}
            >
              <Save className="w-4 h-4 mr-2" />
              保存采样点
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}