import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Progress } from '../../ui/progress';
import { MachineryRecord } from '../../../types/machinery';
import { HealthAssessment as HealthAssessmentType } from '../../../types/equipment';
import { machineryStorage } from '../../../lib/machineryStorage';
import { TrendingUp, TrendingDown, Minus, Award, AlertCircle } from 'lucide-react';

export function HealthAssessment() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [assessments, setAssessments] = useState<HealthAssessmentType[]>([]);

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

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

    // 生成模拟健康评估数据
    const mockAssessments: HealthAssessmentType[] = machineryData.slice(0, 6).map((m, index) => {
      const score = 60 + Math.random() * 35;
      const level = score >= 90 ? '优秀' : score >= 75 ? '良好' : score >= 60 ? '注意' : '警告';
      const trend = index % 3 === 0 ? 'improving' : index % 3 === 1 ? 'stable' : 'declining';
      
      return {
        machineryId: m.id,
        machineryName: m.name,
        score: Math.round(score),
        level,
        metrics: {
          runningHours: 1000 + Math.random() * 5000,
          faultCount: Math.floor(Math.random() * 10),
          maintenanceScore: 70 + Math.random() * 30,
          workloadScore: 60 + Math.random() * 40,
        },
        trend,
        recommendations: generateRecommendations(score, level),
        assessedAt: new Date().toISOString(),
        assessedBy: '系统自动评估',
      };
    });
    
    setAssessments(mockAssessments);
  };

  const generateRecommendations = (score: number, level: string): string[] => {
    const recommendations: string[] = [];
    
    if (score < 70) {
      recommendations.push('建议尽快进行全面检查和维护');
      recommendations.push('关注发动机和传动系统状态');
    }
    
    if (score < 85) {
      recommendations.push('定期更换机油和滤清器');
      recommendations.push('检查轮胎磨损情况');
    }
    
    recommendations.push('保持正常的保养周期');
    recommendations.push('避免长时间超负荷运转');
    
    return recommendations;
  };

  const getLevelColor = (level: string) => {
    switch (level) {
      case '优秀': return 'bg-green-100 text-green-700 border-green-300';
      case '良好': return 'bg-blue-100 text-blue-700 border-blue-300';
      case '注意': return 'bg-yellow-100 text-yellow-700 border-yellow-300';
      case '警告': return 'bg-red-100 text-red-700 border-red-300';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const getScoreColor = (score: number) => {
    if (score >= 90) return 'text-green-600';
    if (score >= 75) return 'text-blue-600';
    if (score >= 60) return 'text-yellow-600';
    return 'text-red-600';
  };

  const getTrendIcon = (trend: string) => {
    switch (trend) {
      case 'improving': return <TrendingUp className="w-4 h-4 text-green-600" />;
      case 'declining': return <TrendingDown className="w-4 h-4 text-red-600" />;
      default: return <Minus className="w-4 h-4 text-gray-600" />;
    }
  };

  const getTrendText = (trend: string) => {
    switch (trend) {
      case 'improving': return '改善中';
      case 'declining': return '下降中';
      default: return '稳定';
    }
  };

  const stats = {
    excellent: assessments.filter(a => a.level === '优秀').length,
    good: assessments.filter(a => a.level === '良好').length,
    attention: assessments.filter(a => a.level === '注意').length,
    warning: assessments.filter(a => a.level === '警告').length,
    avgScore: Math.round(assessments.reduce((sum, a) => sum + a.score, 0) / (assessments.length || 1)),
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">健康评估</h2>
          <p className="text-muted-foreground">综合评估农机健康状况和维护建议</p>
        </div>
      </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 ${getScoreColor(stats.avgScore)}`}>{stats.avgScore}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">优秀</div>
          <div className="mt-1 text-green-600">{stats.excellent}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">良好</div>
          <div className="mt-1 text-blue-600">{stats.good}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">注意</div>
          <div className="mt-1 text-yellow-600">{stats.attention}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">警告</div>
          <div className="mt-1 text-red-600">{stats.warning}</div>
        </Card>
      </div>

      {/* 健康评估列表 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {assessments.map(assessment => (
          <Card key={assessment.machineryId} className="p-6">
            <div className="flex items-start justify-between mb-4">
              <div>
                <h3 className="text-base">{assessment.machineryName}</h3>
                <div className="flex items-center gap-2 mt-1">
                  <Badge variant="outline" className={getLevelColor(assessment.level)}>
                    {assessment.level}
                  </Badge>
                  <div className="flex items-center gap-1 text-sm text-muted-foreground">
                    {getTrendIcon(assessment.trend)}
                    <span>{getTrendText(assessment.trend)}</span>
                  </div>
                </div>
              </div>
              <div className="text-center">
                <div className={`${getScoreColor(assessment.score)}`}>
                  {assessment.score}
                </div>
                <div className="text-xs text-muted-foreground mt-1">健康分</div>
              </div>
            </div>

            {/* 健康分进度条 */}
            <div className="mb-4">
              <Progress value={assessment.score} className="h-2" />
            </div>

            {/* 评估指标 */}
            <div className="space-y-3 mb-4">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <div className="text-xs text-muted-foreground">运行小时</div>
                  <div className="text-sm mt-1">{assessment.metrics.runningHours.toFixed(0)} h</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">故障次数</div>
                  <div className="text-sm mt-1">{assessment.metrics.faultCount} 次</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">维保得分</div>
                  <div className="text-sm mt-1">{assessment.metrics.maintenanceScore.toFixed(0)}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">负荷得分</div>
                  <div className="text-sm mt-1">{assessment.metrics.workloadScore.toFixed(0)}</div>
                </div>
              </div>
            </div>

            {/* 建议 */}
            <div className="pt-3 border-t">
              <h4 className="text-xs mb-2 flex items-center gap-2">
                {assessment.level === '警告' || assessment.level === '注意' ? (
                  <AlertCircle className="w-4 h-4 text-orange-600" />
                ) : (
                  <Award className="w-4 h-4 text-green-600" />
                )}
                维护建议
              </h4>
              <ul className="space-y-1">
                {assessment.recommendations.slice(0, 2).map((rec, index) => (
                  <li key={index} className="text-xs text-muted-foreground">• {rec}</li>
                ))}
              </ul>
            </div>

            <div className="mt-3 pt-3 border-t text-xs text-muted-foreground">
              评估时间: {new Date(assessment.assessedAt).toLocaleString('zh-CN')}
            </div>
          </Card>
        ))}
      </div>

      {/* 评估报告 */}
      <Card className="p-6">
        <h3 className="mb-4">健康评估详细报告</h3>
        <div className="space-y-4">
          <div>
            <h4 className="mb-2">评估方法</h4>
            <p className="text-sm text-muted-foreground">
              健康评估综合考虑以下因素：运行小时数（权重25%）、故障历史（权重30%）、
              维修保养记录（权重25%）、作业负荷（权重20%）。
            </p>
          </div>

          <div>
            <h4 className="mb-2">评分标准</h4>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              <div className="p-3 border rounded-lg">
                <div className="flex items-center gap-2 mb-1">
                  <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                  <span className="text-sm">优秀 (90-100)</span>
                </div>
                <p className="text-xs text-muted-foreground">设备状态极佳，保持当前维护</p>
              </div>
              <div className="p-3 border rounded-lg">
                <div className="flex items-center gap-2 mb-1">
                  <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                  <span className="text-sm">良好 (75-89)</span>
                </div>
                <p className="text-xs text-muted-foreground">设备状态良好，定期保养即可</p>
              </div>
              <div className="p-3 border rounded-lg">
                <div className="flex items-center gap-2 mb-1">
                  <div className="w-2 h-2 bg-yellow-500 rounded-full"></div>
                  <span className="text-sm">注意 (60-74)</span>
                </div>
                <p className="text-xs text-muted-foreground">需要加强维护保养</p>
              </div>
              <div className="p-3 border rounded-lg">
                <div className="flex items-center gap-2 mb-1">
                  <div className="w-2 h-2 bg-red-500 rounded-full"></div>
                  <span className="text-sm">警告 (&lt;60)</span>
                </div>
                <p className="text-xs text-muted-foreground">需要立即检修</p>
              </div>
            </div>
          </div>
        </div>
      </Card>

      {/* 功能说明 */}
      <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>• 自动生成健康评估报告，包含趋势分析和维护建议</li>
          <li>• 支持导出PDF格式的详细评估报告</li>
          <li>• 可设置定期自动评估（每周/每月）</li>
          <li>• 健康分数变化趋势图，便于追踪设备状态</li>
          <li>• 低分设备自动预警提醒</li>
        </ul>
      </Card>
    </div>
  );
}
