import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { AlertTriangle, CheckCircle, XCircle, Info } from 'lucide-react';
import { FaultDiagnosis } from '../../../types/equipment';
import { MachineryRecord } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { Textarea } from '../../ui/textarea';
import { toast } from 'sonner@2.0.3';
import { getKnowledgeBaseArticles, predictPotentialFaults } from '../../../lib/faultCodeLibrary';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';

export function FaultWarning() {
  const [faults, setFaults] = useState<FaultDiagnosis[]>([]);
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [selectedFault, setSelectedFault] = useState<FaultDiagnosis | null>(null);
  const [showHandleDialog, setShowHandleDialog] = useState(false);
  const [handleNotes, setHandleNotes] = useState('');

  useEffect(() => {
    loadData();
    
    // 模拟实时故障检测
    const interval = setInterval(() => {
      detectPotentialFaults();
    }, 30000); // 每30秒检测一次
    
    return () => clearInterval(interval);
  }, []);

  const loadData = () => {
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);

    const faultsData = localStorage.getItem('smart_agriculture_faults');
    if (faultsData) {
      setFaults(JSON.parse(faultsData));
    } else {
      // 初始化示例故障数据
      const mockFaults: FaultDiagnosis[] = [
        {
          id: 'fault-1',
          machineryId: machineryData[0]?.id || 'machinery-1',
          machineryName: machineryData[0]?.name,
          faultCode: 'P0301',
          faultName: '第1缸失火',
          faultLevel: 'error',
          description: '发动机第1缸检测到失火现象',
          diagnosis: '可能是火花塞老化或点火线圈故障',
          predictedCause: '火花塞使用寿命已达90%，建议更换',
          solution: '1. 检查火花塞状态\n2. 检查点火线圈\n3. 检查燃油喷射系统',
          knowledgeBaseIds: ['KB001', 'KB015'],
          detectedAt: '2024-10-12T09:15:00',
          status: '待处理',
        },
        {
          id: 'fault-2',
          machineryId: machineryData[1]?.id || 'machinery-2',
          machineryName: machineryData[1]?.name,
          faultCode: 'P0171',
          faultName: '系统过稀',
          faultLevel: 'warning',
          description: '燃油系统混合气过稀',
          diagnosis: '可能是空气滤清器堵塞或燃油压力不足',
          predictedCause: '空气滤清器使用超过500小时',
          solution: '1. 更换空气滤清器\n2. 检查燃油泵压力\n3. 检查真空泄漏',
          knowledgeBaseIds: ['KB002', 'KB018'],
          detectedAt: '2024-10-12T10:30:00',
          status: '已处理',
          handler: '技术员张三',
          resolvedAt: '2024-10-12T14:20:00',
        },
        {
          id: 'fault-3',
          machineryId: machineryData[0]?.id || 'machinery-1',
          machineryName: machineryData[0]?.name,
          faultCode: 'C0040',
          faultName: '发动机温度过高',
          faultLevel: 'critical',
          description: '发动机冷却液温度超过安全阈值',
          diagnosis: '冷却系统故障，需立即停机检修',
          predictedCause: '冷却液不足或水泵故障',
          solution: '1. 立即停机\n2. 检查冷却液液位\n3. 检查水泵工作状态\n4. 检查散热器',
          knowledgeBaseIds: ['KB003', 'KB025'],
          detectedAt: '2024-10-12T11:45:00',
          status: '待处理',
        },
        // 预测性故障
        {
          id: 'fault-4',
          machineryId: machineryData[2]?.id || 'machinery-3',
          machineryName: machineryData[2]?.name,
          faultCode: 'W1001',
          faultName: '发动机积碳预警',
          faultLevel: 'warning',
          description: '根据运行模式和燃油消耗分析，预测发动机可能存在积碳',
          diagnosis: '长期低转速运行容易产生积碳',
          predictedCause: '低转速运行时间占比超过60%',
          solution: '1. 使用发动机积碳清洗剂\n2. 适当提高转速运行\n3. 检查火花塞积碳情况',
          knowledgeBaseIds: ['KB030', 'KB031'],
          detectedAt: new Date().toISOString(),
          status: '待处理',
        },
        {
          id: 'fault-5',
          machineryId: machineryData[1]?.id || 'machinery-2',
          machineryName: machineryData[1]?.name,
          faultCode: 'W1002',
          faultName: '皮带磨损预警',
          faultLevel: 'warning',
          description: '根据使用时间和振动数据，预测传动皮带可能需要更换',
          diagnosis: '皮带接近使用寿命',
          predictedCause: '皮带使用时间已达1850小时，接近更换周期',
          solution: '1. 检查皮带张紧度\n2. 检查皮带表面磨损\n3. 更换传动皮带',
          knowledgeBaseIds: ['KB040', 'KB041'],
          detectedAt: new Date().toISOString(),
          status: '待处理',
        },
      ];
      localStorage.setItem('smart_agriculture_faults', JSON.stringify(mockFaults));
      setFaults(mockFaults);
    }
  };

  // 检测潜在故障
  const detectPotentialFaults = () => {
    // 模拟传感器数据
    const mockSensorData = {
      belt_usage_hours: 1850,
      belt_tension_drop: 22,
      low_rpm_hours_ratio: 0.65,
      fuel_efficiency_drop: 18,
      hydraulic_oil_hours: 520,
      over_temp_hours: 55,
    };

    const predictions = predictPotentialFaults(mockSensorData);
    
    if (predictions.length > 0) {
      console.log('检测到潜在故障:', predictions);
    }
  };

  const handleProcess = (faultId: string, notes?: string) => {
    const updatedFaults = faults.map(f => {
      if (f.id === faultId) {
        return {
          ...f,
          status: '已处理' as const,
          resolvedAt: new Date().toISOString(),
          handler: '系统管理员',
          handleNotes: notes,
        };
      }
      return f;
    });

    setFaults(updatedFaults);
    localStorage.setItem('smart_agriculture_faults', JSON.stringify(updatedFaults));
    toast.success('故障已标记为已处理');
    setShowHandleDialog(false);
    setSelectedFault(null);
    setHandleNotes('');
  };

  const getLevelColor = (level: FaultDiagnosis['faultLevel']) => {
    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';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getLevelIcon = (level: FaultDiagnosis['faultLevel']) => {
    switch (level) {
      case 'critical': return XCircle;
      case 'error': return AlertTriangle;
      case 'warning': return AlertTriangle;
      case 'info': return Info;
      default: return Info;
    }
  };

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

  const getStatusColor = (status: FaultDiagnosis['status']) => {
    switch (status) {
      case '待处理': return 'bg-warning-muted text-warning';
      case '已处理': return 'bg-success-muted text-success';
      case '已忽略': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const stats = {
    total: faults.length,
    pending: faults.filter(f => f.status === '待处理').length,
    resolved: faults.filter(f => f.status === '已处理').length,
    critical: faults.filter(f => f.faultLevel === 'critical' && f.status !== '已处理').length,
    predicted: faults.filter(f => f.faultCode.startsWith('W')).length,
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-green-800">预警记录</h2>
        <p className="text-muted-foreground">查看和处理农机设备的故障预警记录</p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-5 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-orange-600">{stats.pending}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已处理</div>
          <div className="mt-1 text-green-600">{stats.resolved}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">严重预警</div>
          <div className="mt-1 text-red-600">{stats.critical}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">预测预警</div>
          <div className="mt-1 text-blue-600">{stats.predicted}</div>
        </Card>
      </div>

      {/* 预警列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>级别</TableHead>
              <TableHead>农机</TableHead>
              <TableHead>故障码</TableHead>
              <TableHead>预警名称</TableHead>
              <TableHead>诊断结果</TableHead>
              <TableHead>检测时间</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {faults.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                  <CheckCircle className="w-12 h-12 mx-auto mb-3 text-green-600" />
                  <p>暂无预警记录</p>
                </TableCell>
              </TableRow>
            ) : (
              faults.map(fault => {
                const LevelIcon = getLevelIcon(fault.faultLevel);
                
                return (
                  <TableRow key={fault.id}>
                    <TableCell>
                      <Badge variant="outline" className={getLevelColor(fault.faultLevel)}>
                        <LevelIcon className="w-3 h-3 mr-1" />
                        {getLevelText(fault.faultLevel)}
                      </Badge>
                    </TableCell>
                    <TableCell>{fault.machineryName}</TableCell>
                    <TableCell>
                      <code className="text-xs bg-muted px-2 py-1 rounded">
                        {fault.faultCode}
                      </code>
                    </TableCell>
                    <TableCell>{fault.faultName}</TableCell>
                    <TableCell className="max-w-xs truncate">
                      {fault.diagnosis}
                    </TableCell>
                    <TableCell className="text-xs">
                      {new Date(fault.detectedAt).toLocaleString('zh-CN')}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary" className={getStatusColor(fault.status)}>
                        {fault.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSelectedFault(fault);
                            setShowHandleDialog(true);
                          }}
                        >
                          详情
                        </Button>
                        {fault.status === '待处理' && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setSelectedFault(fault);
                              setHandleNotes('');
                              setShowHandleDialog(true);
                            }}
                          >
                            处理
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 处理对话框 */}
      <Dialog open={showHandleDialog} onOpenChange={setShowHandleDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>预警详情与处理</DialogTitle>
            <DialogDescription className="sr-only">
              查看预警详细信息并处理
            </DialogDescription>
          </DialogHeader>
          {selectedFault && (
            <Tabs defaultValue="detail" className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="detail">预警详情</TabsTrigger>
                <TabsTrigger value="knowledge">知识库</TabsTrigger>
              </TabsList>

              <TabsContent value="detail" className="space-y-4">
                <Card className="p-4 bg-orange-50 border-orange-200">
                  <div className="flex items-start gap-3">
                    <AlertTriangle className="w-5 h-5 text-orange-600 mt-0.5" />
                    <div className="flex-1">
                      <h4 className="text-orange-900">{selectedFault.faultName}</h4>
                      <p className="text-sm text-orange-800 mt-1">{selectedFault.description}</p>
                      <div className="mt-2 text-xs text-orange-700">
                        故障码: <code className="bg-white px-2 py-0.5 rounded">{selectedFault.faultCode}</code>
                      </div>
                    </div>
                  </div>
                </Card>

                <div>
                  <h4 className="mb-2">诊断结果</h4>
                  <p className="text-sm text-muted-foreground">{selectedFault.diagnosis}</p>
                </div>

                <div>
                  <h4 className="mb-2">预测原因</h4>
                  <p className="text-sm text-muted-foreground">{selectedFault.predictedCause}</p>
                </div>

                {selectedFault.status === '已处理' && (
                  <div>
                    <h4 className="mb-2">处理信息</h4>
                    <div className="text-sm space-y-1">
                      <p>处理人员：{selectedFault.handler}</p>
                      <p>处理时间：{selectedFault.resolvedAt ? new Date(selectedFault.resolvedAt).toLocaleString('zh-CN') : '-'}</p>
                      {selectedFault.handleNotes && (
                        <p className="mt-2">
                          <span className="text-muted-foreground">处理备注：</span>
                          <br />
                          {selectedFault.handleNotes}
                        </p>
                      )}
                    </div>
                  </div>
                )}

                {selectedFault.status === '待处理' && (
                  <div>
                    <h4 className="mb-2">处理备注</h4>
                    <Textarea
                      value={handleNotes}
                      onChange={(e) => setHandleNotes(e.target.value)}
                      rows={4}
                      placeholder="请输入处理过程和结果..."
                    />
                  </div>
                )}
              </TabsContent>

              <TabsContent value="knowledge" className="space-y-4">
                {(() => {
                  const articles = getKnowledgeBaseArticles(selectedFault.faultCode);
                  return articles.length > 0 ? (
                    articles.map(article => (
                      <Card key={article.id} className="p-4">
                        <div className="flex items-start justify-between mb-3">
                          <div>
                            <h4 className="text-base">{article.title}</h4>
                            <div className="flex gap-2 mt-2">
                              {article.tags.map(tag => (
                                <Badge key={tag} variant="secondary" className="text-xs">
                                  {tag}
                                </Badge>
                              ))}
                            </div>
                          </div>
                          <Badge variant="outline">
                            难度: {article.difficulty === 'easy' ? '简单' : article.difficulty === 'medium' ? '中等' : '困难'}
                          </Badge>
                        </div>
                        <div className="prose prose-sm max-w-none">
                          <pre className="whitespace-pre-wrap text-sm text-muted-foreground bg-muted p-3 rounded">
                            {article.content}
                          </pre>
                        </div>
                        <div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
                          <span>预计耗时: {article.estimatedTime}</span>
                          <span>查看: {article.viewCount}次</span>
                          <span>有帮助: {article.helpfulCount}次</span>
                        </div>
                      </Card>
                    ))
                  ) : (
                    <div className="text-center py-8 text-muted-foreground">
                      暂无相关知识库文章
                    </div>
                  );
                })()}
              </TabsContent>
            </Tabs>
          )}
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setShowHandleDialog(false);
                setSelectedFault(null);
                setHandleNotes('');
              }}
            >
              关闭
            </Button>
            {selectedFault?.status === '待处理' && (
              <Button
                onClick={() => {
                  if (selectedFault) {
                    handleProcess(selectedFault.id, handleNotes);
                  }
                }}
              >
                <CheckCircle className="w-4 h-4 mr-2" />
                标记已处理
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 功能说明 */}
      <Card className="p-6 bg-blue-50 border-blue-200">
        <h4 className="mb-3 text-blue-900">预警处理流程</h4>
        <ul className="space-y-2 text-sm text-blue-800">
          <li>• <strong>查看详情</strong>: 点击"详情"按钮查看完整的预警信息和诊断结果</li>
          <li>• <strong>处理预警</strong>: 点击"处理"按钮填写处理备注并标记为"已处理"状态</li>
          <li>• <strong>知识库</strong>: 在详情对话框中查看相关维修指导文章</li>
          <li>• <strong>预警记录</strong>: 所有预警记录永久保存，便于追溯和统计分析</li>
        </ul>
      </Card>
    </div>
  );
}
