'use client';

import { useEffect, useState } from 'react';
import { useTranslation } from '@/hooks/useTranslation';
import {
  verifyIntegrity,
  triggerIntegrityCheck,
  getIntegrityCheckJob,
  IntegrityVerifyResponse,
  IntegrityCheckJob,
  IntegrityCheckScope,
  IntegrityCheckStatus,
} from '@/services/api/audit';
import { ApiClientError } from '@/lib/api-client';
import {
  Shield,
  CheckCircle,
  XCircle,
  AlertTriangle,
  Clock,
  RefreshCw,
  Play,
  FileWarning,
  ShieldCheck,
  ShieldAlert,
  Loader2,
} from 'lucide-react';

/**
 * 完整性验证页面
 */
export default function AuditIntegrityPage() {
  const { t } = useTranslation();

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [verifyResult, setVerifyResult] = useState<IntegrityVerifyResponse | null>(null);
  const [asyncJob, setAsyncJob] = useState<IntegrityCheckJob | null>(null);
  const [pollingJobId, setPollingJobId] = useState<string | null>(null);

  // 同步验证参数
  const [verifyParams, setVerifyParams] = useState(() => {
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 7);
    return {
      startDate: start.toISOString().split('T')[0],
      endDate: end.toISOString().split('T')[0],
    };
  });

  // 异步检查参数
  const [checkParams, setCheckParams] = useState<{
    scope: IntegrityCheckScope;
    startDate?: string;
    endDate?: string;
  }>({
    scope: IntegrityCheckScope.ALL,
  });

  // 轮询异步任务状态
  useEffect(() => {
    if (!pollingJobId) return;

    const interval = setInterval(async () => {
      try {
        const job = await getIntegrityCheckJob(pollingJobId);
        setAsyncJob(job);

        if (
          job.status === IntegrityCheckStatus.COMPLETED ||
          job.status === IntegrityCheckStatus.FAILED
        ) {
          setPollingJobId(null);
        }
      } catch (err) {
        console.error('Failed to poll job status:', err);
        setPollingJobId(null);
      }
    }, 3000);

    return () => clearInterval(interval);
  }, [pollingJobId]);

  // 执行同步验证
  const handleVerify = async () => {
    try {
      setLoading(true);
      setError(null);
      setVerifyResult(null);

      const result = await verifyIntegrity({
        startDate: `${verifyParams.startDate}T00:00:00.000Z`,
        endDate: `${verifyParams.endDate}T23:59:59.999Z`,
      });

      setVerifyResult(result);
    } catch (err) {
      console.error('Verification failed:', err);
      if (err instanceof ApiClientError) {
        setError(err.message);
      } else {
        setError('验证失败');
      }
    } finally {
      setLoading(false);
    }
  };

  // 触发异步检查
  const handleTriggerCheck = async () => {
    try {
      setLoading(true);
      setError(null);
      setAsyncJob(null);

      const job = await triggerIntegrityCheck(checkParams);
      setAsyncJob(job);
      setPollingJobId(job.jobId);
    } catch (err) {
      console.error('Failed to trigger check:', err);
      if (err instanceof ApiClientError) {
        setError(err.message);
      } else {
        setError('触发检查失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const formatDateTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    });
  };

  const getStatusIcon = (status: IntegrityCheckStatus) => {
    switch (status) {
      case IntegrityCheckStatus.QUEUED:
        return <Clock className="w-5 h-5 text-gray-500" />;
      case IntegrityCheckStatus.RUNNING:
        return <Loader2 className="w-5 h-5 text-blue-500 animate-spin" />;
      case IntegrityCheckStatus.COMPLETED:
        return <CheckCircle className="w-5 h-5 text-green-500" />;
      case IntegrityCheckStatus.FAILED:
        return <XCircle className="w-5 h-5 text-red-500" />;
    }
  };

  const getStatusLabel = (status: IntegrityCheckStatus) => {
    switch (status) {
      case IntegrityCheckStatus.QUEUED:
        return '排队中';
      case IntegrityCheckStatus.RUNNING:
        return '执行中';
      case IntegrityCheckStatus.COMPLETED:
        return '已完成';
      case IntegrityCheckStatus.FAILED:
        return '失败';
    }
  };

  return (
    <div className="p-6 space-y-6">

      {/* 说明卡片 */}
      <div className="bg-indigo-50 border border-indigo-100 rounded-xl p-6">
        <div className="flex items-start space-x-4">
          <div className="w-12 h-12 bg-indigo-100 rounded-lg flex items-center justify-center flex-shrink-0">
            <Shield className="w-6 h-6 text-indigo-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-indigo-900">{t.audit?.integrity?.hashChainIntegrity}</h3>
            <p className="text-indigo-700 mt-1">
              {t.audit?.integrity?.hashChainDesc}
            </p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 即时验证 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center space-x-3 mb-6">
            <div className="w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center">
              <ShieldCheck className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900">{t.audit?.integrity?.immediateVerification}</h3>
              <p className="text-sm text-gray-500">{t.audit?.integrity?.immediateVerificationDesc}</p>
            </div>
          </div>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.audit?.integrity?.startDate}
                </label>
                <input
                  type="date"
                  value={verifyParams.startDate}
                  onChange={(e) =>
                    setVerifyParams((prev) => ({ ...prev, startDate: e.target.value }))
                  }
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.audit?.integrity?.endDate}
                </label>
                <input
                  type="date"
                  value={verifyParams.endDate}
                  onChange={(e) =>
                    setVerifyParams((prev) => ({ ...prev, endDate: e.target.value }))
                  }
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                />
              </div>
            </div>

            <div className="bg-amber-50 border border-amber-100 rounded-lg p-3">
              <div className="flex items-center text-amber-700 text-sm">
                <AlertTriangle className="w-4 h-4 mr-2" />
                {t.audit?.integrity?.recommendedTimespan}
              </div>
            </div>

            <button
              onClick={handleVerify}
              disabled={loading}
              className="w-full flex items-center justify-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {loading ? (
                <>
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                  {t.audit?.integrity?.verifying}
                </>
              ) : (
                <>
                  <Play className="w-4 h-4 mr-2" />
                  {t.audit?.integrity?.startVerification}
                </>
              )}
            </button>
          </div>
        </div>

        {/* 后台检查 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center space-x-3 mb-6">
            <div className="w-10 h-10 bg-purple-50 rounded-lg flex items-center justify-center">
              <ShieldAlert className="w-5 h-5 text-purple-600" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900">{t.audit?.integrity?.backgroundCheck}</h3>
              <p className="text-sm text-gray-500">{t.audit?.integrity?.backgroundCheckDesc}</p>
            </div>
          </div>

          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                检查范围
              </label>
              <select
                value={checkParams.scope}
                onChange={(e) =>
                  setCheckParams((prev) => ({
                    ...prev,
                    scope: e.target.value as IntegrityCheckScope,
                  }))
                }
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                <option value={IntegrityCheckScope.ALL}>全部日志</option>
                <option value={IntegrityCheckScope.FINANCIAL_ONLY}>仅财务操作</option>
                <option value={IntegrityCheckScope.SENSITIVE_ONLY}>仅敏感操作</option>
                <option value={IntegrityCheckScope.HIGH_RISK_ONLY}>仅高风险操作</option>
              </select>
            </div>

            <div className="bg-blue-50 border border-blue-100 rounded-lg p-3">
              <div className="flex items-center text-blue-700 text-sm">
                <Clock className="w-4 h-4 mr-2" />
                {'后台任务可能需要几分钟完成'}
              </div>
            </div>

            <button
              onClick={handleTriggerCheck}
              disabled={loading || !!pollingJobId}
              className="w-full flex items-center justify-center px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {pollingJobId ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  {t.audit?.integrity?.executing}...
                </>
              ) : (
                <>
                  <Play className="w-4 h-4 mr-2" />
                  {'触发检查'}
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center">
          <XCircle className="w-5 h-5 text-red-500 mr-3" />
          <span className="text-red-700">{error}</span>
        </div>
      )}

      {/* 即时验证结果 */}
      {verifyResult && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="p-6 border-b border-gray-100">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-gray-900">{t.audit?.integrity?.verified}</h3>
              <span className="text-sm text-gray-500">
                {formatDateTime(verifyResult.verifiedAt)}
              </span>
            </div>
          </div>

          <div className="p-6">
            {/* 结果概览 */}
            <div className={`p-6 rounded-xl mb-6 ${
              verifyResult.verified
                ? 'bg-green-50 border border-green-200'
                : 'bg-red-50 border border-red-200'
            }`}>
              <div className="flex items-center space-x-4">
                {verifyResult.verified ? (
                  <CheckCircle className="w-12 h-12 text-green-500" />
                ) : (
                  <XCircle className="w-12 h-12 text-red-500" />
                )}
                <div>
                  <h4 className={`text-xl font-bold ${
                    verifyResult.verified ? 'text-green-900' : 'text-red-900'
                  }`}>
                    {verifyResult.verified ? '验证通过' : '验证失败'}
                  </h4>
                  <p className={verifyResult.verified ? 'text-green-700' : 'text-red-700'}>
                    {verifyResult.verified
                      ? '所有审计日志完整性验证通过，未检测到篡改'
                      : `检测到 ${verifyResult.failCount} 条记录异常`}
                  </p>
                </div>
              </div>
            </div>

            {/* 统计数据 */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
              <div className="bg-gray-50 rounded-lg p-4">
                <p className="text-sm text-gray-500">总记录数</p>
                <p className="text-2xl font-bold text-gray-900">
                  {verifyResult.totalRecords.toLocaleString()}
                </p>
              </div>
              <div className="bg-green-50 rounded-lg p-4">
                <p className="text-sm text-green-600">通过</p>
                <p className="text-2xl font-bold text-green-700">
                  {verifyResult.passCount.toLocaleString()}
                </p>
              </div>
              <div className="bg-red-50 rounded-lg p-4">
                <p className="text-sm text-red-600">失败</p>
                <p className="text-2xl font-bold text-red-700">
                  {verifyResult.failCount.toLocaleString()}
                </p>
              </div>
              <div className="bg-blue-50 rounded-lg p-4">
                <p className="text-sm text-blue-600">耗时</p>
                <p className="text-2xl font-bold text-blue-700">
                  {verifyResult.duration}ms
                </p>
              </div>
            </div>

            {/* 失败详情 */}
            {verifyResult.failures && verifyResult.failures.length > 0 && (
              <div>
                <h4 className="text-lg font-semibold text-gray-900 mb-4">
                  异常记录详情
                </h4>
                <div className="space-y-3">
                  {verifyResult.failures.map((failure, index) => (
                    <div
                      key={index}
                      className="bg-red-50 border border-red-100 rounded-lg p-4"
                    >
                      <div className="flex items-start space-x-3">
                        <FileWarning className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" />
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium text-red-900">
                            [{failure.type}] 日志 ID: {failure.logId}
                          </p>
                          <p className="text-sm text-red-700 mt-1">{failure.message}</p>
                          {(failure.expectedHash || failure.actualHash) && (
                            <div className="mt-2 space-y-1">
                              {failure.expectedHash && (
                                <p className="text-xs text-red-600 font-mono">
                                  期望: {failure.expectedHash.substring(0, 32)}...
                                </p>
                              )}
                              {failure.actualHash && (
                                <p className="text-xs text-red-600 font-mono">
                                  实际: {failure.actualHash.substring(0, 32)}...
                                </p>
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* 异步任务状态 */}
      {asyncJob && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="p-6 border-b border-gray-100">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-gray-900">后台任务状态</h3>
              <div className="flex items-center space-x-2">
                {getStatusIcon(asyncJob.status)}
                <span className="text-sm text-gray-600">
                  {getStatusLabel(asyncJob.status)}
                </span>
              </div>
            </div>
          </div>

          <div className="p-6">
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <p className="text-sm text-gray-500">任务 ID</p>
                <p className="text-sm font-mono text-gray-900">{asyncJob.jobId}</p>
              </div>
              <div>
                <p className="text-sm text-gray-500">创建时间</p>
                <p className="text-sm text-gray-900">
                  {formatDateTime(asyncJob.createdAt)}
                </p>
              </div>
              {asyncJob.startedAt && (
                <div>
                  <p className="text-sm text-gray-500">开始时间</p>
                  <p className="text-sm text-gray-900">
                    {formatDateTime(asyncJob.startedAt)}
                  </p>
                </div>
              )}
              {asyncJob.completedAt && (
                <div>
                  <p className="text-sm text-gray-500">完成时间</p>
                  <p className="text-sm text-gray-900">
                    {formatDateTime(asyncJob.completedAt)}
                  </p>
                </div>
              )}
            </div>

            {asyncJob.error && (
              <div className="bg-red-50 border border-red-100 rounded-lg p-4">
                <div className="flex items-center text-red-700">
                  <XCircle className="w-5 h-5 mr-2" />
                  {asyncJob.error}
                </div>
              </div>
            )}

            {asyncJob.result && (
              <div className={`p-4 rounded-lg ${
                asyncJob.result.verified
                  ? 'bg-green-50 border border-green-200'
                  : 'bg-red-50 border border-red-200'
              }`}>
                <div className="flex items-center space-x-3">
                  {asyncJob.result.verified ? (
                    <CheckCircle className="w-6 h-6 text-green-500" />
                  ) : (
                    <XCircle className="w-6 h-6 text-red-500" />
                  )}
                  <div>
                    <p className={`font-medium ${
                      asyncJob.result.verified ? 'text-green-900' : 'text-red-900'
                    }`}>
                      {asyncJob.result.verified ? '验证通过' : '验证失败'}
                    </p>
                    <p className={`text-sm ${
                      asyncJob.result.verified ? 'text-green-700' : 'text-red-700'
                    }`}>
                      共 {asyncJob.result.totalRecords} 条记录，
                      通过 {asyncJob.result.passCount} 条，
                      失败 {asyncJob.result.failCount} 条
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

