import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Shield, 
  CheckCircle, 
  AlertTriangle, 
  XCircle, 
  RefreshCw, 
  Activity,
  Database,
  FileText,
  TrendingUp,
  Clock
} from 'lucide-react';
import { 
  runFullDataIntegrityCheck, 
  getErrorRateStats,
  getFailedValidations,
  type DataIntegrityReport 
} from '../utils/dataValidation';

/**
 * 数据完整性监控面板
 * 实时显示系统数据质量状态
 */
export function DataIntegrityDashboard() {
  const [report, setReport] = useState<DataIntegrityReport | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [lastCheck, setLastCheck] = useState<string>('');
  const [errorRateHistory, setErrorRateHistory] = useState<any[]>([]);
  const [failedRecords, setFailedRecords] = useState<any[]>([]);

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    setError(null);
    
    try {
      // 运行完整性检查
      const checkReport = await runFullDataIntegrityCheck();
      setReport(checkReport);
      setLastCheck(new Date().toLocaleString('zh-CN'));

      // 加载错误率历史
      const history = await getErrorRateStats(7);
      setErrorRateHistory(history || []);

      // 加载失败记录
      const failed = await getFailedValidations(10);
      setFailedRecords(failed || []);

    } catch (err: any) {
      setError(err.message || '加载数据失败');
      console.error('加载数据完整性报告失败:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
    // 每5分钟自动刷新
    const interval = setInterval(loadData, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, []);

  // 状态图标
  const StatusIcon = ({ status }: { status: 'PASS' | 'FAIL' }) => {
    if (status === 'PASS') {
      return <CheckCircle className="w-6 h-6 text-emerald-500" />;
    }
    return <XCircle className="w-6 h-6 text-red-500" />;
  };

  // 错误率颜色
  const getErrorRateColor = (rate: number) => {
    if (rate <= 1) return 'text-emerald-600 bg-emerald-50';
    if (rate <= 5) return 'text-amber-600 bg-amber-50';
    return 'text-red-600 bg-red-50';
  };

  return (
    <div className="p-6 space-y-6">
      {/* 标题栏 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Shield className="w-8 h-8 text-blue-600" />
          <div>
            <h1 className="text-2xl font-bold text-gray-900">数据完整性监控</h1>
            <p className="text-sm text-gray-500">
              目标：错误率 ≤ 0.01% (万分之一) | 财务数据 100% 准确
            </p>
          </div>
        </div>
        <button
          onClick={loadData}
          disabled={loading}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          {loading ? '检查中...' : '立即检查'}
        </button>
      </div>

      {/* 错误提示 */}
      {error && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3"
        >
          <AlertTriangle className="w-5 h-5 text-red-600 mt-0.5" />
          <div>
            <p className="font-medium text-red-900">加载失败</p>
            <p className="text-sm text-red-700">{error}</p>
          </div>
        </motion.div>
      )}

      {/* 总体状态卡片 */}
      {report && (
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className={`p-6 rounded-xl border-2 ${
            report.overallStatus === 'PASS'
              ? 'bg-emerald-50 border-emerald-200'
              : 'bg-red-50 border-red-200'
          }`}
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <StatusIcon status={report.overallStatus} />
              <div>
                <h2 className="text-xl font-bold text-gray-900">
                  {report.overallStatus === 'PASS' ? '✓ 系统数据完整性达标' : '✗ 发现数据异常'}
                </h2>
                <p className="text-sm text-gray-600 mt-1">
                  最后检查时间: {lastCheck}
                </p>
              </div>
            </div>
            <div className="text-right">
              <div className="text-3xl font-bold text-gray-900">
                {(report.errorRate ?? 0).toFixed(2)}
                <span className="text-lg text-gray-600">/万</span>
              </div>
              <div className="text-sm text-gray-500">当前错误率</div>
            </div>
          </div>

          {/* 告警信息 */}
          {report.checks.planQuantity.status === 'FAIL' ||
           report.checks.paymentAmount.status === 'FAIL' ||
           report.checks.accountsPayable.status === 'FAIL' ? (
            <div className="mt-4 p-3 bg-white/50 rounded-lg">
              <p className="text-sm font-medium text-gray-900 mb-2">异常项目：</p>
              <ul className="space-y-1">
                {report.checks.planQuantity.status === 'FAIL' && (
                  <li className="text-sm text-red-700 flex items-center gap-2">
                    <XCircle className="w-4 h-4" />
                    计划数量一致性: {report.checks.planQuantity.inconsistentRecords} 条不一致
                  </li>
                )}
                {report.checks.paymentAmount.status === 'FAIL' && (
                  <li className="text-sm text-red-700 flex items-center gap-2">
                    <XCircle className="w-4 h-4" />
                    付款金额一致性: {report.checks.paymentAmount.inconsistentRecords} 条不一致
                  </li>
                )}
                {report.checks.accountsPayable.status === 'FAIL' && (
                  <li className="text-sm text-red-700 flex items-center gap-2">
                    <XCircle className="w-4 h-4" />
                    应付账款汇总: {report.checks.accountsPayable.inconsistentRecords} 条不一致
                  </li>
                )}
              </ul>
            </div>
          ) : null}
        </motion.div>
      )}

      {/* 详细检查项 */}
      {report && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {[
            { key: 'planQuantity', label: '计划数量一致性', icon: Database },
            { key: 'paymentAmount', label: '付款金额校验', icon: FileText },
            { key: 'accountsPayable', label: '应付账款汇总', icon: TrendingUp },
          ].map((item) => {
            const check = report.checks[item.key as keyof typeof report.checks];
            return (
              <motion.div
                key={item.key}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="p-4 bg-white rounded-lg border border-gray-200 shadow-sm"
              >
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <item.icon className="w-5 h-5 text-blue-600" />
                    <h3 className="font-medium text-gray-900">{item.label}</h3>
                  </div>
                  <StatusIcon status={check.status} />
                </div>
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">总记录数</span>
                    <span className="font-medium">{check.totalRecords}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">不一致记录</span>
                    <span className={`font-medium ${check.inconsistentRecords > 0 ? 'text-red-600' : 'text-emerald-600'}`}>
                      {check.inconsistentRecords}
                    </span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">错误率</span>
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${getErrorRateColor(check.errorRate)}`}>
                      {(check.errorRate ?? 0).toFixed(2)}/万
                    </span>
                  </div>
                </div>
              </motion.div>
            );
          })}
        </div>
      )}

      {/* 错误率趋势 */}
      {errorRateHistory.length > 0 && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="p-6 bg-white rounded-lg border border-gray-200 shadow-sm"
        >
          <div className="flex items-center gap-2 mb-4">
            <Activity className="w-5 h-5 text-blue-600" />
            <h3 className="font-medium text-gray-900">近7天错误率趋势</h3>
          </div>
          <div className="space-y-2">
            {errorRateHistory.slice(0, 7).map((record, idx) => (
              <div key={idx} className="flex items-center justify-between p-2 hover:bg-gray-50 rounded">
                <div className="flex items-center gap-3">
                  <Clock className="w-4 h-4 text-gray-400" />
                  <span className="text-sm text-gray-600">
                    {new Date(record.check_date).toLocaleDateString('zh-CN')}
                  </span>
                </div>
                <div className="flex items-center gap-4">
                  <span className="text-sm text-gray-500">{record.table_name}</span>
                  <span className={`text-sm font-medium ${
                    (record.error_rate_per_10k ?? 0) <= 1 ? 'text-emerald-600' : 'text-red-600'
                  }`}>
                    {(record.error_rate_per_10k ?? 0).toFixed(2)}/万
                  </span>
                  <span className="text-xs text-gray-400">
                    ({record.failed_operations ?? 0}/{record.total_operations ?? 0})
                  </span>
                </div>
              </div>
            ))}
          </div>
        </motion.div>
      )}

      {/* 最近失败记录 */}
      {failedRecords.length > 0 && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="p-6 bg-white rounded-lg border border-gray-200 shadow-sm"
        >
          <div className="flex items-center gap-2 mb-4">
            <AlertTriangle className="w-5 h-5 text-amber-600" />
            <h3 className="font-medium text-gray-900">最近验证失败记录</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="text-left p-2 font-medium text-gray-700">时间</th>
                  <th className="text-left p-2 font-medium text-gray-700">表名</th>
                  <th className="text-left p-2 font-medium text-gray-700">操作</th>
                  <th className="text-left p-2 font-medium text-gray-700">错误信息</th>
                </tr>
              </thead>
              <tbody>
                {failedRecords.map((record) => (
                  <tr key={record.id} className="border-t border-gray-100 hover:bg-gray-50">
                    <td className="p-2 text-gray-600">
                      {new Date(record.changed_at).toLocaleString('zh-CN')}
                    </td>
                    <td className="p-2 text-gray-900 font-mono text-xs">{record.table_name}</td>
                    <td className="p-2">
                      <span className="px-2 py-0.5 bg-gray-100 rounded text-xs">{record.operation}</span>
                    </td>
                    <td className="p-2 text-red-600 text-xs max-w-md truncate">
                      {record.error_message || '-'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </motion.div>
      )}
    </div>
  );
}
