'use client';

import React from 'react';
import { t } from '@/i18n/locales';
import { useApi } from '@/lib/use-api';

/**
 * SOX Compliance (Sarbanes-Oxley) - SOX合规管理
 */

interface SoxData {
  overallScore: number;
  controlCategories: {
    name: string;
    description: string;
    controls: { name: string; result: string; lastTest: string; nextTest: string }[];
  }[];
  deficiencies: { id: string; control: string; category: string; severity: string; description: string; foundDate: string; dueDate: string; status: string; owner: string }[];
  auditorReview: { phase: string; status: string; date: string; auditor: string }[];
  auditProgress: number;
}

const loadingBox: React.CSSProperties = {
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  padding: 40, color: 'var(--color-text-tertiary)', font: 'var(--text-body)',
};

const getResultStyle = (result: string) => {
  switch (result) {
    case 'passed': return { background: 'var(--color-success-light)', color: 'var(--color-success)' };
    case 'defect': return { background: 'var(--color-error-light)', color: 'var(--color-error)' };
    case 'pending': return { background: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
    default: return { background: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  }
};

const getResultLabel = (result: string) => {
  const map: Record<string, () => string> = {
    passed: () => t('sox_result_passed'),
    defect: () => t('sox_result_defect'),
    pending: () => t('sox_result_pending'),
  };
  return map[result]?.() ?? result;
};

const getSeverityStyle = (severity: string) => {
  switch (severity) {
    case 'major': return { background: 'var(--color-error-light)', color: 'var(--color-error)' };
    case 'minor': return { background: 'var(--color-warning-light)', color: 'var(--color-warning)' };
    case 'observation': return { background: 'var(--color-info-light)', color: 'var(--color-info)' };
    default: return { background: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  }
};

const getSeverityLabel = (severity: string) => {
  const map: Record<string, () => string> = {
    major: () => t('sox_severity_major'),
    minor: () => t('sox_severity_minor'),
    observation: () => t('sox_severity_observation'),
  };
  return map[severity]?.() ?? severity;
};

export const SoxCompliancePage: React.FC = () => {
  const { data, isLoading, error } = useApi<SoxData>('/api/v1/admin/compliance/reports');

  if (error) return <div style={loadingBox}>Error: {error.message}</div>;
  if (isLoading) return <div style={loadingBox}>Loading...</div>;

  const overallScore = data?.overallScore ?? 0;
  const controlCategories = data?.controlCategories ?? [];
  const deficiencies = data?.deficiencies ?? [];
  const auditorReview = data?.auditorReview ?? [];
  const auditProgress = data?.auditProgress ?? 0;

  const totalControls = controlCategories.reduce((sum, cat) => sum + cat.controls.length, 0);
  const passedControls = controlCategories.reduce((sum, cat) => sum + cat.controls.filter(c => c.result === 'passed').length, 0);
  const defectControls = controlCategories.reduce((sum, cat) => sum + cat.controls.filter(c => c.result === 'defect').length, 0);
  const pendingControls = controlCategories.reduce((sum, cat) => sum + cat.controls.filter(c => c.result === 'pending').length, 0);

  return (
    <div>
      <h1 style={{ font: 'var(--text-h1)', color: 'var(--color-text-primary)', marginBottom: 24 }}>{t('sox_title')}</h1>

      {/* Compliance Score Gauge + Summary Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 3fr', gap: 24, marginBottom: 24 }}>
        <div style={{
          background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)', padding: 24,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', marginBottom: 12 }}>{t('sox_overall_score')}</div>
          <div style={{
            width: 120, height: 120, borderRadius: '50%', position: 'relative',
            background: `conic-gradient(${overallScore >= 80 ? 'var(--color-success)' : overallScore >= 60 ? 'var(--color-warning)' : 'var(--color-error)'} ${overallScore * 3.6}deg, var(--color-gray-100) 0deg)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <div style={{
              width: 90, height: 90, borderRadius: '50%', background: 'var(--color-surface)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <span style={{ font: 'var(--text-h1)', color: overallScore >= 80 ? 'var(--color-success)' : overallScore >= 60 ? 'var(--color-warning)' : 'var(--color-error)' }}>
                {overallScore}
              </span>
            </div>
          </div>
          <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginTop: 8 }}>{t('sox_full_score')}</div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
          {[
            { label: t('sox_total_controls'), value: String(totalControls), color: 'var(--color-primary)' },
            { label: t('sox_test_passed'), value: String(passedControls), color: 'var(--color-success)' },
            { label: t('sox_defects_found'), value: String(defectControls), color: 'var(--color-error)' },
            { label: t('sox_pending_test'), value: String(pendingControls), color: 'var(--color-warning)' },
          ].map(s => (
            <div key={s.label} style={{
              background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
              border: '1px solid var(--color-border-light)', padding: 20,
            }}>
              <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', marginBottom: 8 }}>{s.label}</div>
              <div style={{ font: 'var(--text-h1)', color: s.color }}>{s.value}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Control Categories */}
      <div style={{
        background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)', marginBottom: 24, overflow: 'hidden',
      }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--color-border-light)' }}>
          <h2 style={{ font: 'var(--text-h2)', color: 'var(--color-text-primary)' }}>{t('sox_control_categories')}</h2>
        </div>
        {controlCategories.map((cat, catIdx) => (
          <div key={catIdx} style={{ borderBottom: catIdx < controlCategories.length - 1 ? '2px solid var(--color-border-light)' : 'none' }}>
            <div style={{ padding: '14px 20px', background: 'var(--color-gray-50)' }}>
              <div style={{ font: 'var(--text-h3)', color: 'var(--color-text-primary)', marginBottom: 4 }}>{cat.name}</div>
              <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{cat.description}</div>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  {[t('sox_th_control_point'), t('sox_th_test_result'), t('sox_th_last_test'), t('sox_th_next_test')].map(h => (
                    <th key={h} style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)', padding: '8px 20px', textAlign: 'left' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {cat.controls.map((ctrl, ctrlIdx) => (
                  <tr key={ctrlIdx} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                    <td style={{ font: 'var(--text-body-sm)', padding: '10px 20px', color: 'var(--color-text-primary)' }}>{ctrl.name}</td>
                    <td style={{ padding: '10px 20px' }}>
                      <span style={{
                        padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)', fontWeight: 600,
                        ...getResultStyle(ctrl.result),
                      }}>{getResultLabel(ctrl.result)}</span>
                    </td>
                    <td style={{ font: 'var(--text-body-sm)', padding: '10px 20px', color: 'var(--color-text-tertiary)' }}>{ctrl.lastTest}</td>
                    <td style={{ font: 'var(--text-body-sm)', padding: '10px 20px', color: 'var(--color-text-secondary)' }}>{ctrl.nextTest}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 24 }}>
        {/* Deficiency Tracking */}
        <div style={{
          background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)', overflow: 'hidden',
        }}>
          <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--color-border-light)' }}>
            <h2 style={{ font: 'var(--text-h2)', color: 'var(--color-text-primary)' }}>{t('sox_deficiency_tracking')}</h2>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: 'var(--color-gray-50)' }}>
                {[t('sox_th_id'), t('sox_th_control'), t('sox_th_severity'), t('sox_th_description'), t('sox_th_due_date'), t('sox_th_status'), t('sox_th_owner')].map(h => (
                  <th key={h} style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px', textAlign: 'left' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {deficiencies.map(d => (
                <tr key={d.id} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-body-sm)', fontFamily: 'var(--font-family-mono)', padding: '10px 14px' }}>{d.id}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-primary)' }}>{d.control}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{
                      padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)', fontWeight: 600,
                      ...getSeverityStyle(d.severity),
                    }}>{getSeverityLabel(d.severity)}</span>
                  </td>
                  <td style={{ font: 'var(--text-caption)', padding: '10px 14px', color: 'var(--color-text-secondary)', maxWidth: 200 }}>{d.description}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>{d.dueDate}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{
                      padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)', fontWeight: 600,
                      background: d.status === 'remediating' ? 'var(--color-warning-light)' : 'var(--color-error-light)',
                      color: d.status === 'remediating' ? 'var(--color-warning)' : 'var(--color-error)',
                    }}>
                      {d.status === 'remediating' ? t('sox_status_remediating') : t('sox_status_pending')}
                    </span>
                  </td>
                  <td style={{ font: 'var(--text-caption)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>{d.owner}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Auditor Review Status */}
        <div style={{ background: 'var(--color-surface)', borderRadius: 'var(--radius-md)', border: '1px solid var(--color-border-light)', padding: 20 }}>
          <h2 style={{ font: 'var(--text-h2)', marginBottom: 4 }}>{t('sox_auditor_progress')}</h2>
          <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginBottom: 16 }}>External Auditor: {auditorReview[0]?.auditor ?? 'N/A'}</div>
          {auditorReview.map((phase, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', padding: '10px 0', borderBottom: '1px solid var(--color-border-light)' }}>
              <div style={{
                width: 20, height: 20, borderRadius: '50%', marginRight: 12, marginTop: 2, flexShrink: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: phase.status === 'done' ? 'var(--color-success)' : phase.status === 'progress' ? 'var(--color-warning)' : 'var(--color-gray-200)',
                color: phase.status === 'pending' ? 'var(--color-text-tertiary)' : 'white', fontSize: 10,
              }}>
                {phase.status === 'done' ? '✓' : phase.status === 'progress' ? '...' : '○'}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ font: 'var(--text-body)', color: 'var(--color-text-primary)' }}>{phase.phase}</div>
                <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginTop: 2 }}>{phase.date}</div>
              </div>
              <span style={{
                font: 'var(--text-caption)',
                color: phase.status === 'done' ? 'var(--color-success)' : phase.status === 'progress' ? 'var(--color-warning)' : 'var(--color-text-tertiary)',
              }}>
                {phase.status === 'done' ? t('completed') : phase.status === 'progress' ? t('in_progress') : t('pending')}
              </span>
            </div>
          ))}
          <div style={{ marginTop: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-secondary)' }}>{t('sox_audit_progress')}</span>
              <span style={{ font: 'var(--text-label-sm)', color: 'var(--color-primary)' }}>{auditProgress}%</span>
            </div>
            <div style={{ height: 8, background: 'var(--color-gray-100)', borderRadius: 'var(--radius-full)', overflow: 'hidden' }}>
              <div style={{ width: `${auditProgress}%`, height: '100%', background: 'var(--color-primary)', borderRadius: 'var(--radius-full)' }} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
