import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Switch } from '../../ui/switch';
import { Badge } from '../../ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Plus, Edit, Trash2, AlertTriangle, Info, CheckCircle2 } from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { FaultCategory } from '../../../lib/faultCodeLibrary';

// 预警规则类型
export interface AlertRule {
  id: string;
  name: string;
  category: FaultCategory;
  level: 'info' | 'warning' | 'error' | 'critical';
  description: string;
  
  // 触发条件
  sensorKey: string;
  threshold: {
    type: 'greater' | 'less' | 'equal' | 'range';
    value: number;
    maxValue?: number; // 用于范围类型
    duration?: number; // 持续时间（秒）
  };
  
  // 预警动作
  pushChannels: ('internal' | 'sms' | 'email' | 'push')[];
  autoCreateTask?: boolean; // 是否自动创建维修任务
  
  // 状态
  enabled: boolean;
  
  // 元数据
  createdAt: string;
  updatedAt: string;
  createdBy: string;
}

const CATEGORY_OPTIONS: FaultCategory[] = [
  '发动机系统',
  '传动系统',
  '液压系统',
  '电气系统',
  '冷却系统',
  '燃油系统',
  '排放系统',
  '作业装置',
  '其他'
];

const SENSOR_OPTIONS = [
  { value: 'engine_rpm', label: '发动机转速 (RPM)' },
  { value: 'coolant_temp', label: '冷却液温度 (℃)' },
  { value: 'oil_pressure', label: '机油压力 (kPa)' },
  { value: 'fuel_level', label: '燃油液位 (%)' },
  { value: 'hydraulic_pressure', label: '液压压力 (MPa)' },
  { value: 'battery_voltage', label: '电池电压 (V)' },
  { value: 'vibration_level', label: '振动等级' },
  { value: 'belt_tension', label: '皮带张紧度' },
];

export function AlertRuleManagement() {
  const [rules, setRules] = useState<AlertRule[]>([]);
  const [showDialog, setShowDialog] = useState(false);
  const [editingRule, setEditingRule] = useState<AlertRule | null>(null);
  
  // 表单状态
  const [formData, setFormData] = useState({
    name: '',
    category: '发动机系统' as FaultCategory,
    level: 'warning' as AlertRule['level'],
    description: '',
    sensorKey: 'engine_rpm',
    thresholdType: 'greater' as AlertRule['threshold']['type'],
    thresholdValue: 0,
    thresholdMaxValue: 0,
    duration: 0,
    pushInternal: true,
    pushSMS: false,
    pushEmail: false,
    pushPush: true,
    autoCreateTask: false,
    enabled: true,
  });

  useEffect(() => {
    loadRules();
  }, []);

  const loadRules = () => {
    const data = localStorage.getItem('smart_agriculture_alert_rules');
    if (data) {
      setRules(JSON.parse(data));
    } else {
      // 初始化默认规则
      const defaultRules: AlertRule[] = [
        {
          id: 'rule-1',
          name: '发动机温度过高预警',
          category: '冷却系统',
          level: 'critical',
          description: '当冷却液温度超过105℃时触发严重预警',
          sensorKey: 'coolant_temp',
          threshold: {
            type: 'greater',
            value: 105,
            duration: 30,
          },
          pushChannels: ['internal', 'sms', 'push'],
          autoCreateTask: true,
          enabled: true,
          createdAt: '2024-10-01T08:00:00',
          updatedAt: '2024-10-01T08:00:00',
          createdBy: '系统管理员',
        },
        {
          id: 'rule-2',
          name: '机油压力过低预警',
          category: '发动机系统',
          level: 'error',
          description: '当机油压力低于150kPa时触发预警',
          sensorKey: 'oil_pressure',
          threshold: {
            type: 'less',
            value: 150,
            duration: 10,
          },
          pushChannels: ['internal', 'sms'],
          autoCreateTask: false,
          enabled: true,
          createdAt: '2024-10-01T08:00:00',
          updatedAt: '2024-10-01T08:00:00',
          createdBy: '系统管理员',
        },
        {
          id: 'rule-3',
          name: '燃油液位过低提醒',
          category: '燃油系统',
          level: 'warning',
          description: '当燃油液位低于20%时提醒补充燃油',
          sensorKey: 'fuel_level',
          threshold: {
            type: 'less',
            value: 20,
            duration: 0,
          },
          pushChannels: ['internal', 'push'],
          autoCreateTask: false,
          enabled: true,
          createdAt: '2024-10-01T08:00:00',
          updatedAt: '2024-10-01T08:00:00',
          createdBy: '系统管理员',
        },
      ];
      localStorage.setItem('smart_agriculture_alert_rules', JSON.stringify(defaultRules));
      setRules(defaultRules);
    }
  };

  const handleOpenDialog = (rule?: AlertRule) => {
    if (rule) {
      setEditingRule(rule);
      setFormData({
        name: rule.name,
        category: rule.category,
        level: rule.level,
        description: rule.description,
        sensorKey: rule.sensorKey,
        thresholdType: rule.threshold.type,
        thresholdValue: rule.threshold.value,
        thresholdMaxValue: rule.threshold.maxValue || 0,
        duration: rule.threshold.duration || 0,
        pushInternal: rule.pushChannels.includes('internal'),
        pushSMS: rule.pushChannels.includes('sms'),
        pushEmail: rule.pushChannels.includes('email'),
        pushPush: rule.pushChannels.includes('push'),
        autoCreateTask: rule.autoCreateTask || false,
        enabled: rule.enabled,
      });
    } else {
      setEditingRule(null);
      setFormData({
        name: '',
        category: '发动机系统',
        level: 'warning',
        description: '',
        sensorKey: 'engine_rpm',
        thresholdType: 'greater',
        thresholdValue: 0,
        thresholdMaxValue: 0,
        duration: 0,
        pushInternal: true,
        pushSMS: false,
        pushEmail: false,
        pushPush: true,
        autoCreateTask: false,
        enabled: true,
      });
    }
    setShowDialog(true);
  };

  const handleSave = () => {
    if (!formData.name.trim()) {
      toast.error('请输入规则名称');
      return;
    }

    const pushChannels: AlertRule['pushChannels'] = [];
    if (formData.pushInternal) pushChannels.push('internal');
    if (formData.pushSMS) pushChannels.push('sms');
    if (formData.pushEmail) pushChannels.push('email');
    if (formData.pushPush) pushChannels.push('push');

    const newRule: AlertRule = {
      id: editingRule?.id || `rule-${Date.now()}`,
      name: formData.name,
      category: formData.category,
      level: formData.level,
      description: formData.description,
      sensorKey: formData.sensorKey,
      threshold: {
        type: formData.thresholdType,
        value: formData.thresholdValue,
        maxValue: formData.thresholdType === 'range' ? formData.thresholdMaxValue : undefined,
        duration: formData.duration,
      },
      pushChannels,
      autoCreateTask: formData.autoCreateTask,
      enabled: formData.enabled,
      createdAt: editingRule?.createdAt || new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      createdBy: editingRule?.createdBy || '系统管理员',
    };

    let updatedRules;
    if (editingRule) {
      updatedRules = rules.map(r => r.id === editingRule.id ? newRule : r);
      toast.success('规则更新成功');
    } else {
      updatedRules = [...rules, newRule];
      toast.success('规则创建成功');
    }

    setRules(updatedRules);
    localStorage.setItem('smart_agriculture_alert_rules', JSON.stringify(updatedRules));
    setShowDialog(false);
  };

  const handleDelete = (id: string) => {
    if (confirm('确定要删除这条规则吗？')) {
      const updatedRules = rules.filter(r => r.id !== id);
      setRules(updatedRules);
      localStorage.setItem('smart_agriculture_alert_rules', JSON.stringify(updatedRules));
      toast.success('规则删除成功');
    }
  };

  const handleToggleEnabled = (id: string) => {
    const updatedRules = rules.map(r => {
      if (r.id === id) {
        return { ...r, enabled: !r.enabled, updatedAt: new Date().toISOString() };
      }
      return r;
    });
    setRules(updatedRules);
    localStorage.setItem('smart_agriculture_alert_rules', JSON.stringify(updatedRules));
    toast.success('规则状态已更新');
  };

  const getLevelColor = (level: AlertRule['level']) => {
    switch (level) {
      case 'critical': return 'bg-error-muted text-error border-error';
      case 'error': return 'bg-warning-muted text-warning border-warning';
      case 'warning': return 'bg-warning-muted text-warning border-warning';
      case 'info': return 'bg-info-muted text-info border-info';
    }
  };

  const getLevelText = (level: AlertRule['level']) => {
    switch (level) {
      case 'critical': return '严重';
      case 'error': return '错误';
      case 'warning': return '警告';
      case 'info': return '提示';
    }
  };

  const getThresholdText = (rule: AlertRule) => {
    const sensor = SENSOR_OPTIONS.find(s => s.value === rule.sensorKey);
    const sensorName = sensor?.label || rule.sensorKey;
    const { type, value, maxValue, duration } = rule.threshold;

    let condition = '';
    switch (type) {
      case 'greater':
        condition = `> ${value}`;
        break;
      case 'less':
        condition = `< ${value}`;
        break;
      case 'equal':
        condition = `= ${value}`;
        break;
      case 'range':
        condition = `${value} ~ ${maxValue}`;
        break;
    }

    let text = `${sensorName} ${condition}`;
    if (duration && duration > 0) {
      text += ` (持续${duration}秒)`;
    }
    return text;
  };

  const stats = {
    total: rules.length,
    enabled: rules.filter(r => r.enabled).length,
    disabled: rules.filter(r => !r.enabled).length,
    critical: rules.filter(r => r.level === 'critical' && r.enabled).length,
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">预警规则管理</h2>
          <p className="text-muted-foreground">配置和管理农机设备的预警规则</p>
        </div>
        <Button onClick={() => handleOpenDialog()}>
          <Plus className="w-4 h-4 mr-2" />
          新增规则
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">规则总数</div>
          <div className="mt-1">{stats.total}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已启用</div>
          <div className="mt-1 text-success">{stats.enabled}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已禁用</div>
          <div className="mt-1 text-muted-foreground">{stats.disabled}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">严重级别</div>
          <div className="mt-1 text-error">{stats.critical}</div>
        </Card>
      </div>

      {/* 规则列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>状态</TableHead>
              <TableHead>规则名称</TableHead>
              <TableHead>级别</TableHead>
              <TableHead>分类</TableHead>
              <TableHead>触发条件</TableHead>
              <TableHead>推送渠道</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rules.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                  暂无预警规则
                </TableCell>
              </TableRow>
            ) : (
              rules.map(rule => (
                <TableRow key={rule.id}>
                  <TableCell>
                    <Switch
                      checked={rule.enabled}
                      onCheckedChange={() => handleToggleEnabled(rule.id)}
                    />
                  </TableCell>
                  <TableCell>
                    <div>
                      <div>{rule.name}</div>
                      {rule.description && (
                        <div className="text-xs text-muted-foreground mt-1">{rule.description}</div>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline" className={getLevelColor(rule.level)}>
                      {getLevelText(rule.level)}
                    </Badge>
                  </TableCell>
                  <TableCell>{rule.category}</TableCell>
                  <TableCell className="text-sm">{getThresholdText(rule)}</TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-1">
                      {rule.pushChannels.map(channel => (
                        <Badge key={channel} variant="secondary" className="text-xs">
                          {channel === 'internal' ? '站内信' : 
                           channel === 'sms' ? '短信' : 
                           channel === 'email' ? '邮件' : '推送'}
                        </Badge>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleOpenDialog(rule)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDelete(rule.id)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </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>{editingRule ? '编辑规则' : '新增规则'}</DialogTitle>
            <DialogDescription>
              配置预警规则的触发条件和推送方式
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            {/* 基本信息 */}
            <div className="space-y-4">
              <h4>基本信息</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="name">规则名称 *</Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    placeholder="如：发动机温度过高预警"
                  />
                </div>
                <div>
                  <Label htmlFor="category">所属分类</Label>
                  <Select value={formData.category} onValueChange={(value) => setFormData({ ...formData, category: value as FaultCategory })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {CATEGORY_OPTIONS.map(cat => (
                        <SelectItem key={cat} value={cat}>{cat}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="level">预警级别</Label>
                  <Select value={formData.level} onValueChange={(value) => setFormData({ ...formData, level: value as AlertRule['level'] })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="info">提示</SelectItem>
                      <SelectItem value="warning">警告</SelectItem>
                      <SelectItem value="error">错误</SelectItem>
                      <SelectItem value="critical">严重</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div>
                <Label htmlFor="description">规则描述</Label>
                <Input
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="简要描述规则的用途"
                />
              </div>
            </div>

            {/* 触发条件 */}
            <div className="space-y-4">
              <h4>触发条件</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="sensorKey">监测参数</Label>
                  <Select value={formData.sensorKey} onValueChange={(value) => setFormData({ ...formData, sensorKey: value })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {SENSOR_OPTIONS.map(option => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="thresholdType">条件类型</Label>
                  <Select value={formData.thresholdType} onValueChange={(value) => setFormData({ ...formData, thresholdType: value as AlertRule['threshold']['type'] })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="greater">大于 (&gt;)</SelectItem>
                      <SelectItem value="less">小于 (&lt;)</SelectItem>
                      <SelectItem value="equal">等于 (=)</SelectItem>
                      <SelectItem value="range">范围内</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="thresholdValue">阈值</Label>
                  <Input
                    id="thresholdValue"
                    type="number"
                    value={formData.thresholdValue}
                    onChange={(e) => setFormData({ ...formData, thresholdValue: Number(e.target.value) })}
                  />
                </div>
                {formData.thresholdType === 'range' && (
                  <div>
                    <Label htmlFor="thresholdMaxValue">最大值</Label>
                    <Input
                      id="thresholdMaxValue"
                      type="number"
                      value={formData.thresholdMaxValue}
                      onChange={(e) => setFormData({ ...formData, thresholdMaxValue: Number(e.target.value) })}
                    />
                  </div>
                )}
                <div>
                  <Label htmlFor="duration">持续时间（秒）</Label>
                  <Input
                    id="duration"
                    type="number"
                    value={formData.duration}
                    onChange={(e) => setFormData({ ...formData, duration: Number(e.target.value) })}
                    placeholder="0表示立即触发"
                  />
                </div>
              </div>
            </div>

            {/* 预警动作 */}
            <div className="space-y-4">
              <h4>预警动作</h4>
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <Label htmlFor="pushInternal">站内信通知</Label>
                  <Switch
                    id="pushInternal"
                    checked={formData.pushInternal}
                    onCheckedChange={(checked) => setFormData({ ...formData, pushInternal: checked })}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <Label htmlFor="pushSMS">短信通知</Label>
                  <Switch
                    id="pushSMS"
                    checked={formData.pushSMS}
                    onCheckedChange={(checked) => setFormData({ ...formData, pushSMS: checked })}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <Label htmlFor="pushEmail">邮件通知</Label>
                  <Switch
                    id="pushEmail"
                    checked={formData.pushEmail}
                    onCheckedChange={(checked) => setFormData({ ...formData, pushEmail: checked })}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <Label htmlFor="pushPush">推送通知</Label>
                  <Switch
                    id="pushPush"
                    checked={formData.pushPush}
                    onCheckedChange={(checked) => setFormData({ ...formData, pushPush: checked })}
                  />
                </div>
                <div className="flex items-center justify-between">
                  <Label htmlFor="autoCreateTask">自动创建维修任务</Label>
                  <Switch
                    id="autoCreateTask"
                    checked={formData.autoCreateTask}
                    onCheckedChange={(checked) => setFormData({ ...formData, autoCreateTask: checked })}
                  />
                </div>
              </div>
            </div>

            {/* 规则状态 */}
            <div className="flex items-center justify-between">
              <Label htmlFor="enabled">启用规则</Label>
              <Switch
                id="enabled"
                checked={formData.enabled}
                onCheckedChange={(checked) => setFormData({ ...formData, enabled: checked })}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 功能说明 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="mb-3 text-muted-foreground">规则配置说明</h4>
        <ul className="space-y-2 text-sm text-muted-foreground">
          <li>• <strong>触发条件</strong>: 选择监测参数和阈值，支持大于、小于、等于和范围判断</li>
          <li>• <strong>持续时间</strong>: 设置为0表示立即触发，大于0表示需要持续超过阈值指定秒数才触发</li>
          <li>• <strong>推送渠道</strong>: 可同时选择多种推送方式，确保预警及时送达</li>
          <li>• <strong>自动任务</strong>: 启用后，触发预警时自动创建维修任务，便于快速响应</li>
          <li>• <strong>规则启停</strong>: 可随时启用或禁用规则，禁用后不会触发预警</li>
        </ul>
      </Card>
    </div>
  );
}
