import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import {
  Search,
  Plus,
  Edit,
  Eye,
  Trash2,
  Settings,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface WFParameter {
  id: string;
  parameterNo: string;
  parameterName: string;
  minValue: number;
  maxValue: number;
  unit: string;
  accuracy?: string;
  samplingInterval?: number;
}

export function WaterFertilizerParameter() {
  const [parameters, setParameters] = useState<WFParameter[]>([
    {
      id: 'param-1',
      parameterNo: 'PARAM-2024-001',
      parameterName: '系统压力',
      unit: 'bar',
      minValue: 0,
      maxValue: 10,
      accuracy: '±0.1',
      samplingInterval: 5,
    },
    {
      id: 'param-2',
      parameterNo: 'PARAM-2024-002',
      parameterName: '灌溉流量',
      unit: 'L/min',
      minValue: 0,
      maxValue: 50,
      accuracy: '±1%',
      samplingInterval: 5,
    },
    {
      id: 'param-3',
      parameterNo: 'PARAM-2024-003',
      parameterName: '溶液EC值',
      unit: 'mS/cm',
      minValue: 0,
      maxValue: 5,
      accuracy: '±0.01',
      samplingInterval: 10,
    },
    {
      id: 'param-4',
      parameterNo: 'PARAM-2024-004',
      parameterName: '溶液PH值',
      unit: 'pH',
      minValue: 0,
      maxValue: 14,
      accuracy: '±0.02',
      samplingInterval: 10,
    },
    {
      id: 'param-5',
      parameterNo: 'PARAM-2024-005',
      parameterName: '水温',
      unit: '℃',
      minValue: 0,
      maxValue: 50,
      accuracy: '±0.5',
      samplingInterval: 30,
    },
    {
      id: 'param-6',
      parameterNo: 'PARAM-2024-006',
      parameterName: '泵体转速',
      unit: 'RPM',
      minValue: 0,
      maxValue: 3000,
      accuracy: '±10',
      samplingInterval: 5,
    },
    {
      id: 'param-7',
      parameterNo: 'PARAM-2024-007',
      parameterName: '电机功率',
      unit: 'kW',
      minValue: 0,
      maxValue: 10,
      accuracy: '±0.1',
      samplingInterval: 5,
    },
    {
      id: 'param-8',
      parameterNo: 'PARAM-2024-008',
      parameterName: '肥料罐液位',
      unit: '%',
      minValue: 0,
      maxValue: 100,
      accuracy: '±1',
      samplingInterval: 60,
    },
    {
      id: 'param-9',
      parameterNo: 'PARAM-2024-009',
      parameterName: '施肥浓度',
      unit: 'g/L',
      minValue: 0,
      maxValue: 100,
      accuracy: '±0.5',
      samplingInterval: 10,
    },
    {
      id: 'param-10',
      parameterNo: 'PARAM-2024-010',
      parameterName: '环境湿度',
      unit: '%RH',
      minValue: 0,
      maxValue: 100,
      accuracy: '±2',
      samplingInterval: 60,
    },
  ]);

  const [showDialog, setShowDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editingParameter, setEditingParameter] = useState<WFParameter | null>(null);
  const [viewingParameter, setViewingParameter] = useState<WFParameter | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<WFParameter | null>(null);
  const [searchText, setSearchText] = useState('');
  const [formData, setFormData] = useState<Partial<WFParameter>>({});

  const filteredParameters = parameters.filter(param => {
    const matchSearch = searchText === '' || 
      param.parameterName.toLowerCase().includes(searchText.toLowerCase()) ||
      param.parameterNo.toLowerCase().includes(searchText.toLowerCase()) ||
      param.unit.toLowerCase().includes(searchText.toLowerCase());
    
    return matchSearch;
  });

  const stats = {
    total: parameters.length,
  };

  const handleAdd = () => {
    setEditingParameter(null);
    setFormData({
      parameterNo: `PARAM-${new Date().getFullYear()}-${String(parameters.length + 1).padStart(3, '0')}`,
      minValue: 0,
      maxValue: 100,
      samplingInterval: 10,
    });
    setShowDialog(true);
  };

  const handleEdit = (parameter: WFParameter) => {
    setEditingParameter(parameter);
    setFormData(parameter);
    setShowDialog(true);
  };

  const handleView = (parameter: WFParameter) => {
    setViewingParameter(parameter);
    setShowDetailDialog(true);
  };

  const handleDelete = (parameter: WFParameter) => {
    setDeleteTarget(parameter);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (deleteTarget) {
      setParameters(parameters.filter(p => p.id !== deleteTarget.id));
      toast.success(`参数 ${deleteTarget.parameterName} 已删除`);
      setShowDeleteDialog(false);
      setDeleteTarget(null);
    }
  };

  const handleSave = () => {
    if (!formData.parameterName || !formData.parameterNo) {
      toast.error('请填写参数编码和参数名称');
      return;
    }

    if (formData.minValue !== undefined && formData.maxValue !== undefined && formData.minValue >= formData.maxValue) {
      toast.error('最小值必须小于最大值');
      return;
    }

    if (editingParameter) {
      setParameters(parameters.map(p => 
        p.id === editingParameter.id ? { 
          ...p, 
          ...formData,
        } as WFParameter : p
      ));
      toast.success('参数配置已更新');
    } else {
      const newParameter: WFParameter = {
        ...formData,
        id: `param-${Date.now()}`,
      } as WFParameter;
      setParameters([...parameters, newParameter]);
      toast.success('参数配置添加成功');
    }
    setShowDialog(false);
    setFormData({});
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">水肥机参数配置</h2>
          <p className="text-sm text-muted-foreground mt-1">
            对水肥机各项运行参数进行系统配置，实现设备参数标准化管理
          </p>
        </div>
      </div>

      <Card className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border-green-200">
        <div className="flex items-start gap-2">
          <Settings className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-green-900">
            <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>
            </ul>
          </div>
        </div>
      </Card>

      <div className="grid grid-cols-1 md:grid-cols-1 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">参数总数</p>
              <p className="mt-2 text-3xl text-blue-600">{stats.total}</p>
            </div>
            <Settings className="w-12 h-12 text-blue-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Card className="p-4">
        <div className="flex items-center justify-between gap-4">
          <div className="flex gap-4 flex-1">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索参数名称、编号、单位..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Button className="bg-green-600 hover:bg-green-700" onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-2" />
            新增参数
          </Button>
        </div>
      </Card>

      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>参数编码</TableHead>
              <TableHead>参数名称</TableHead>
              <TableHead>量程范围</TableHead>
              <TableHead>单位</TableHead>
              <TableHead>精度</TableHead>
              <TableHead>采样间隔</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredParameters.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  <Settings className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  <p>暂无参数配置数据</p>
                </TableCell>
              </TableRow>
            ) : (
              filteredParameters.map((parameter) => (
                <TableRow key={parameter.id}>
                  <TableCell>
                    <div className="font-mono text-sm">{parameter.parameterNo}</div>
                  </TableCell>
                  <TableCell>
                    <div className="font-medium">{parameter.parameterName}</div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      {parameter.minValue} - {parameter.maxValue}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">{parameter.unit || '-'}</div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">{parameter.accuracy || '-'}</div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      {parameter.samplingInterval ? `${parameter.samplingInterval}秒` : '-'}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2 justify-end">
                      <Button size="sm" variant="outline" onClick={() => handleView(parameter)}>
                        <Eye className="w-3 h-3" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleEdit(parameter)}>
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline" 
                        onClick={() => handleDelete(parameter)}
                        className="text-red-600 hover:text-red-700 hover:border-red-300"
                      >
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingParameter ? '编辑参数配置' : '新增参数配置'}
            </DialogTitle>
            <DialogDescription>
              {editingParameter ? '修改参数配置信息' : '添加新的运行参数配置'}
            </DialogDescription>
          </DialogHeader>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>参数编码 *</Label>
              <Input
                value={formData.parameterNo || ''}
                onChange={(e) => setFormData({ ...formData, parameterNo: e.target.value })}
                placeholder="PARAM-2024-001"
                disabled={!!editingParameter}
              />
            </div>

            <div>
              <Label>参数名称 *</Label>
              <Input
                value={formData.parameterName || ''}
                onChange={(e) => setFormData({ ...formData, parameterName: e.target.value })}
                placeholder="系统压力"
              />
            </div>

            <div>
              <Label>单位</Label>
              <Input
                value={formData.unit || ''}
                onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                placeholder="bar / L/min / mS/cm / pH / ℃"
              />
            </div>

            <div>
              <Label>最小值</Label>
              <Input
                type="number"
                step="0.01"
                value={formData.minValue ?? ''}
                onChange={(e) => setFormData({ ...formData, minValue: Number(e.target.value) })}
                placeholder="0"
              />
            </div>

            <div>
              <Label>最大值</Label>
              <Input
                type="number"
                step="0.01"
                value={formData.maxValue ?? ''}
                onChange={(e) => setFormData({ ...formData, maxValue: Number(e.target.value) })}
                placeholder="10"
              />
            </div>

            <div>
              <Label>精度</Label>
              <Input
                value={formData.accuracy || ''}
                onChange={(e) => setFormData({ ...formData, accuracy: e.target.value })}
                placeholder="±0.1"
              />
            </div>

            <div>
              <Label>采样间隔（秒）</Label>
              <Input
                type="number"
                value={formData.samplingInterval ?? ''}
                onChange={(e) => setFormData({ ...formData, samplingInterval: Number(e.target.value) })}
                placeholder="10"
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>参数配置详情</DialogTitle>
            <DialogDescription>
              查看参数的详细配置信息
            </DialogDescription>
          </DialogHeader>

          {viewingParameter && (
            <div className="space-y-6">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>参数编码</Label>
                  <div className="field-value font-mono">{viewingParameter.parameterNo}</div>
                </div>
                <div>
                  <Label>参数名称</Label>
                  <div className="field-value">{viewingParameter.parameterName}</div>
                </div>
                <div>
                  <Label>单位</Label>
                  <div className="field-value">{viewingParameter.unit || '-'}</div>
                </div>
                <div>
                  <Label>量程范围</Label>
                  <div className="field-value">
                    {viewingParameter.minValue} - {viewingParameter.maxValue}
                  </div>
                </div>
                <div>
                  <Label>精度</Label>
                  <div className="field-value">{viewingParameter.accuracy || '-'}</div>
                </div>
                <div>
                  <Label>采样间隔</Label>
                  <div className="field-value">
                    {viewingParameter.samplingInterval ? `${viewingParameter.samplingInterval}秒` : '-'}
                  </div>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除参数配置 "{deleteTarget?.parameterName}" 吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction 
              onClick={confirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
