'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { useTranslation } from '@/hooks/useTranslation';
import {
  getAuditLogById,
  verifySingleAuditLog,
  AuditLogDetail,
  SingleLogVerifyResult,
  getActionLabel,
  getActionColor,
  getRiskLevelLabel,
  getStatusLabel,
  getStatusColor,
  formatModuleName,
} from '@/services/api/audit';
import { ApiClientError } from '@/lib/api-client';
import { resolveBusinessRoute } from '@/lib/audit-business-routes';
import { AuditDiffView } from '@/components/audit/AuditDiffView';
import Link from 'next/link';
import {
  ArrowLeft,
  ExternalLink,
  FileText,
  User,
  Clock,
  MapPin,
  Monitor,
  Hash,
  Shield,
  AlertTriangle,
  DollarSign,
  ChevronDown,
  ChevronUp,
  Copy,
  Check,
  RefreshCw,
  XCircle,
} from 'lucide-react';

/**
 * 审计日志详情页面
 */
export default function AuditLogDetailPage() {
  const router = useRouter();
  const params = useParams();
  const { t } = useTranslation();
  const logId = params.id as string;

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [log, setLog] = useState<AuditLogDetail | null>(null);
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    basic: true,
    context: true,
    changes: true,
    integrity: false,
  });
  const [copiedField, setCopiedField] = useState<string | null>(null);
  const [verifying, setVerifying] = useState(false);
  const [verifyResult, setVerifyResult] = useState<SingleLogVerifyResult | null>(null);
  const [verifyError, setVerifyError] = useState<string | null>(null);

  const handleVerifyIntegrity = async () => {
    if (!log) return;
    setVerifying(true);
    setVerifyError(null);
    setVerifyResult(null);
    try {
      const result = await verifySingleAuditLog(log.id);
      setVerifyResult(result);
    } catch (err) {
      console.error('Failed to verify integrity:', err);
      setVerifyError(err instanceof ApiClientError ? err.message : t.audit.detail.integrityVerifyFailed);
    } finally {
      setVerifying(false);
    }
  };

  useEffect(() => {
    loadData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [logId]);

  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getAuditLogById(logId);
      setLog(data);
    } catch (err) {
      console.error('Failed to load audit log:', err);
      if (err instanceof ApiClientError) {
        setError(err.message);
      } else {
        setError('加载失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const toggleSection = (section: string) => {
    setExpandedSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }));
  };

  const copyToClipboard = async (text: string, field: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedField(field);
      setTimeout(() => setCopiedField(null), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  };

  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',
      timeZoneName: 'short',
    });
  };

  const formatJson = (obj: Record<string, unknown> | null | undefined) => {
    if (!obj) return null;
    return JSON.stringify(obj, null, 2);
  };

  const parseUserAgent = (ua: string): { browser: string; os: string; device: string } => {
    if (!ua) return { browser: '-', os: '-', device: '-' };
    let browser = '-';
    if (/Edg\//.test(ua)) browser = 'Edge';
    else if (/Chrome\//.test(ua) && !/Chromium/.test(ua)) browser = 'Chrome';
    else if (/Firefox\//.test(ua)) browser = 'Firefox';
    else if (/Safari\//.test(ua) && !/Chrome\//.test(ua)) browser = 'Safari';
    else if (/MSIE|Trident/.test(ua)) browser = 'IE';
    const browserVersion = ua.match(/(?:Edg|Chrome|Firefox|Version)\/([\d.]+)/);
    if (browserVersion) browser = `${browser} ${browserVersion[1].split('.')[0]}`;

    let os = '-';
    if (/Windows NT 10/.test(ua)) os = 'Windows 10/11';
    else if (/Windows NT/.test(ua)) os = 'Windows';
    else if (/Mac OS X/.test(ua)) os = 'macOS';
    else if (/Android/.test(ua)) os = 'Android';
    else if (/iPhone|iPad|iOS/.test(ua)) os = 'iOS';
    else if (/Linux/.test(ua)) os = 'Linux';

    const isMobile = /Mobile|Android|iPhone|iPad/.test(ua);
    const device = isMobile ? t.audit.detail.deviceTypeMobile : t.audit.detail.deviceTypeDesktop;
    return { browser, os, device };
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <RefreshCw className="w-8 h-8 text-indigo-600 animate-spin mx-auto mb-4" />
          <p className="text-gray-500">{t.common.loading}</p>
        </div>
      </div>
    );
  }

  if (error || !log) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <XCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <p className="text-gray-900 font-medium mb-2">{t.audit.detail.loadFailed}</p>
          <p className="text-gray-500 mb-4">{error || t.audit.detail.logNotFound}</p>
          <div className="flex items-center justify-center space-x-3">
            <button
              onClick={() => router.back()}
              className="px-4 py-2 border border-gray-200 rounded-lg text-gray-600 hover:bg-gray-50 transition-colors"
            >
              {t.common.back}
            </button>
            <button
              onClick={loadData}
              className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
            >
              {t.common.retry}
            </button>
          </div>
        </div>
      </div>
    );
  }

  const actionColor = getActionColor(log.action);
  const statusColor = getStatusColor(log.status);

  return (
    <div className="p-6 space-y-6">
      {/* 顶部操作栏 */}
      <div className="flex items-center justify-between">
        <button
          onClick={() => router.back()}
          className="flex items-center px-3 py-2 hover:bg-gray-100 rounded-lg transition-colors text-gray-600"
        >
          <ArrowLeft className="w-5 h-5 mr-2" />
          {t.common.back}
        </button>
        <div className="flex items-center space-x-2">
          <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${actionColor.bg} ${actionColor.text}`}>
            {getActionLabel(log.action, t)}
          </span>
          <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${statusColor.bg} ${statusColor.text}`}>
            {getStatusLabel(log.status, t)}
          </span>
          {log.isSensitive && (
            <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-amber-50 text-amber-600">
              <AlertTriangle className="w-4 h-4 mr-1" />
              {t.audit.detail.sensitive}
            </span>
          )}
          {log.isFinancial && (
            <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-emerald-50 text-emerald-600">
              <DollarSign className="w-4 h-4 mr-1" />
              {t.audit.detail.financial}
            </span>
          )}
        </div>
      </div>

      {/* 5W1H 概览卡片 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">{t.audit.detail.operationOverview} (5W1H)</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div className="flex items-start space-x-3">
            <div className="w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center">
              <User className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">{t.audit.detail.who}</p>
              <p className="text-gray-900 font-medium">{log.who}</p>
              {log.user && (
                <p className="text-sm text-gray-500">{log.user.displayName || log.user.username}</p>
              )}
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-10 h-10 bg-purple-50 rounded-lg flex items-center justify-center">
              <FileText className="w-5 h-5 text-purple-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">{t.audit.detail.what}</p>
              <p className="text-gray-900 font-medium">{log.what}</p>
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-10 h-10 bg-green-50 rounded-lg flex items-center justify-center">
              <Clock className="w-5 h-5 text-green-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">{t.audit.detail.when}</p>
              <p className="text-gray-900 font-medium">{formatDateTime(log.when)}</p>
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-10 h-10 bg-orange-50 rounded-lg flex items-center justify-center">
              <MapPin className="w-5 h-5 text-orange-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">{t.audit.detail.where}</p>
              <p className="text-gray-900 font-medium">{log.where}</p>
              {log.geoLocation && (
                <p className="text-sm text-gray-500">{log.geoLocation}</p>
              )}
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-10 h-10 bg-pink-50 rounded-lg flex items-center justify-center">
              <Monitor className="w-5 h-5 text-pink-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">{t.audit.detail.how}</p>
              <p className="text-gray-900 font-medium">{log.how}</p>
            </div>
          </div>
          {log.why && (
            <div className="flex items-start space-x-3">
              <div className="w-10 h-10 bg-cyan-50 rounded-lg flex items-center justify-center">
                <Hash className="w-5 h-5 text-cyan-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">{t.audit.detail.why}</p>
                <p className="text-gray-900 font-medium">{log.why}</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 基本信息 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <button
          onClick={() => toggleSection('basic')}
          className="w-full px-6 py-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
        >
          <h3 className="text-lg font-semibold text-gray-900">{t.audit.detail.basicInfo}</h3>
          {expandedSections.basic ? (
            <ChevronUp className="w-5 h-5 text-gray-400" />
          ) : (
            <ChevronDown className="w-5 h-5 text-gray-400" />
          )}
        </button>
        {expandedSections.basic && (
          <div className="px-6 pb-6 border-t border-gray-100">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4">
              <InfoRow label={t.audit.detail.module} value={formatModuleName(log.module, t)} />
              <InfoRow label={t.audit.detail.actionType} value={getActionLabel(log.action, t)} />
              <InfoRow label={t.audit.detail.entityType} value={log.entityType} />
              <InfoRow label={t.audit.detail.entityId} value={log.entityId} copyable onCopy={copyToClipboard} copiedField={copiedField} />
              <InfoRow label={t.audit.detail.status} value={getStatusLabel(log.status, t)} />
              <InfoRow label={t.audit.detail.riskLevel} value={getRiskLevelLabel(log.riskLevel, t)} />
              <InfoRow label={t.audit.detail.complianceLevel} value={log.complianceLevel} />
              <InfoRow label={t.audit.detail.retentionYears} value={`${log.retentionYears} ${t.audit.detail.years}`} />
              {log.duration && <InfoRow label={t.audit.detail.duration} value={`${log.duration} ms`} />}
              {log.errorMessage && (
                <div className="md:col-span-2">
                  <InfoRow label={t.audit.detail.errorMessage} value={log.errorMessage} className="text-red-600" />
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* 上下文信息 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <button
          onClick={() => toggleSection('context')}
          className="w-full px-6 py-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
        >
          <h3 className="text-lg font-semibold text-gray-900">{t.audit.detail.contextInfo}</h3>
          {expandedSections.context ? (
            <ChevronUp className="w-5 h-5 text-gray-400" />
          ) : (
            <ChevronDown className="w-5 h-5 text-gray-400" />
          )}
        </button>
        {expandedSections.context && (
          <div className="px-6 pb-6 border-t border-gray-100">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4">
              <InfoRow label={t.audit.detail.userId} value={log.userId} copyable onCopy={copyToClipboard} copiedField={copiedField} />
              <InfoRow label={t.audit.detail.sessionId} value={log.sessionId} copyable onCopy={copyToClipboard} copiedField={copiedField} />
              <InfoRow label={t.audit.detail.traceId} value={log.traceId} copyable onCopy={copyToClipboard} copiedField={copiedField} />
              <InfoRow label={t.audit.detail.requestId} value={log.requestId} copyable onCopy={copyToClipboard} copiedField={copiedField} />
              <InfoRow label={t.audit.detail.ipAddress} value={log.ipAddress} />
              <InfoRow label={t.audit.detail.geoLocation} value={log.geoLocation || '-'} />
              {(() => {
                const ua = parseUserAgent(log.userAgent);
                return (
                  <>
                    <InfoRow label={t.audit.detail.deviceType} value={ua.device} />
                    <InfoRow label={t.audit.detail.operatingSystem} value={ua.os} />
                    <InfoRow label={t.audit.detail.browser} value={ua.browser} />
                  </>
                );
              })()}
              <InfoRow label={t.audit.detail.operationSource} value={log.how} />
              <InfoRow label={t.audit.detail.userAgent} value={log.userAgent} className="break-all" />
              {log.deviceId && <InfoRow label={t.audit.detail.deviceId} value={log.deviceId} copyable onCopy={copyToClipboard} copiedField={copiedField} />}
              {log.businessType && <InfoRow label={t.audit.detail.businessType} value={log.businessType} />}
              {log.businessKey && <InfoRow label={t.audit.detail.businessKey} value={log.businessKey} />}
              {(() => {
                const route = resolveBusinessRoute(log.entityType, log.entityId, log.businessKey, log.businessType);
                if (!route) return null;
                return (
                  <div className="flex items-start justify-between py-2 border-b border-gray-50">
                    <span className="text-sm text-gray-500 min-w-[120px]">{t.audit.detail.viewSource}</span>
                    <Link
                      href={route}
                      className="text-sm text-indigo-600 hover:text-indigo-700 hover:underline inline-flex items-center"
                    >
                      {log.businessKey || log.entityId.slice(0, 8)}
                      <ExternalLink className="w-3.5 h-3.5 ml-1" />
                    </Link>
                  </div>
                );
              })()}
              <InfoRow label={t.audit.detail.region} value={log.region} />
              <InfoRow label={t.audit.detail.tenantId} value={log.tenantId} />
            </div>
          </div>
        )}
      </div>

      {/* 变更内容 */}
      {(log.oldValue || log.newValue || log.changes) && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <button
            onClick={() => toggleSection('changes')}
            className="w-full px-6 py-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
          >
            <h3 className="text-lg font-semibold text-gray-900">{t.audit.detail.changes}</h3>
            {expandedSections.changes ? (
              <ChevronUp className="w-5 h-5 text-gray-400" />
            ) : (
              <ChevronDown className="w-5 h-5 text-gray-400" />
            )}
          </button>
          {expandedSections.changes && (
            <div className="px-6 pb-6 border-t border-gray-100 space-y-4 pt-4">
              {(log.oldValue || log.newValue) && (
                <AuditDiffView oldValue={log.oldValue} newValue={log.newValue} />
              )}
              {log.changes && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 mb-2">{t.audit.detail.changeDetails}</h4>
                  <pre className="bg-blue-50 border border-blue-100 rounded-lg p-4 overflow-auto text-sm text-blue-800">
                    {formatJson(log.changes)}
                  </pre>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* 完整性信息 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <button
          onClick={() => toggleSection('integrity')}
          className="w-full px-6 py-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
        >
          <div className="flex items-center">
            <Shield className="w-5 h-5 text-indigo-600 mr-2" />
            <h3 className="text-lg font-semibold text-gray-900">{t.audit.detail.integrityInfo}</h3>
            {verifyResult && (
              <span
                className={`ml-3 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                  verifyResult.valid
                    ? 'bg-green-50 text-green-700'
                    : 'bg-red-50 text-red-700'
                }`}
              >
                {verifyResult.valid ? t.audit.detail.integrityValid : t.audit.detail.integrityInvalid}
              </span>
            )}
          </div>
          {expandedSections.integrity ? (
            <ChevronUp className="w-5 h-5 text-gray-400" />
          ) : (
            <ChevronDown className="w-5 h-5 text-gray-400" />
          )}
        </button>
        {expandedSections.integrity && (
          <div className="px-6 pb-6 border-t border-gray-100">
            <div className="pt-4 mb-4 flex items-center gap-3">
              <button
                onClick={(e) => { e.stopPropagation(); handleVerifyIntegrity(); }}
                disabled={verifying}
                className="inline-flex items-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 text-sm"
              >
                {verifying ? (
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                ) : (
                  <Shield className="w-4 h-4 mr-2" />
                )}
                {verifying ? t.audit.detail.verifying : t.audit.detail.verifyIntegrity}
              </button>
              {verifyResult && !verifyResult.valid && (
                <span className="text-sm text-red-600">
                  {t.audit.detail.integrityTamperedHint}
                </span>
              )}
              {verifyError && (
                <span className="text-sm text-red-600">{verifyError}</span>
              )}
            </div>
            <div className="grid grid-cols-1 gap-4">
              <InfoRow
                label={t.audit.detail.currentHash}
                value={log.currentHash} 
                copyable 
                onCopy={copyToClipboard} 
                copiedField={copiedField}
                className="font-mono text-sm"
              />
              {log.previousHash && (
                <InfoRow 
                  label={t.audit.detail.previousHash}
                  value={log.previousHash} 
                  copyable 
                  onCopy={copyToClipboard} 
                  copiedField={copiedField}
                  className="font-mono text-sm"
                />
              )}
              {log.signature && (
                <InfoRow 
                  label={t.audit.detail.signature}
                  value={log.signature} 
                  copyable 
                  onCopy={copyToClipboard} 
                  copiedField={copiedField}
                  className="font-mono text-sm"
                />
              )}
              <InfoRow label={t.audit.detail.createdAt} value={formatDateTime(log.createdAt)} />
              {log.archivedAt && (
                <InfoRow label={t.audit.detail.archivedAt} value={formatDateTime(log.archivedAt)} />
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/**
 * 信息行组件
 */
function InfoRow({
  label,
  value,
  copyable,
  onCopy,
  copiedField,
  className,
}: {
  label: string;
  value: string;
  copyable?: boolean;
  onCopy?: (text: string, field: string) => void;
  copiedField?: string | null;
  className?: string;
}) {
  const isCopied = copiedField === label;

  return (
    <div className="flex items-start justify-between py-2 border-b border-gray-50 last:border-0">
      <span className="text-sm text-gray-500 min-w-[120px]">{label}</span>
      <div className="flex items-center space-x-2 flex-1 justify-end">
        <span className={`text-sm text-gray-900 text-right ${className || ''}`}>
          {value}
        </span>
        {copyable && onCopy && (
          <button
            onClick={() => onCopy(value, label)}
            className="p-1 hover:bg-gray-100 rounded transition-colors"
          >
            {isCopied ? (
              <Check className="w-4 h-4 text-green-500" />
            ) : (
              <Copy className="w-4 h-4 text-gray-400" />
            )}
          </button>
        )}
      </div>
    </div>
  );
}

