'use client';

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

/**
 * 消费者保护分析仪表盘
 *
 * 投诉统计、分类分析、满意度趋势、保障基金、退款合规
 */

interface ConsumerProtectionData {
  stats: { label: string; value: string; change: string; trend: 'up' | 'down'; color: string; invertTrend?: boolean }[];
  complaintCategories: { name: string; count: number; percent: number; color: string }[];
  csatTrend: { month: string; score: number }[];
  recentComplaints: { id: string; severity: string; category: string; title: string; status: string; assignee: string; created: string }[];
  nonCompliantIssuers: { rank: number; issuer: string; violations: number; refundRate: string; avgDelay: string; riskLevel: string }[];
}

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

const getSeverityStyle = (severity: string) => {
  switch (severity) {
    case 'high': return { bg: 'var(--color-error-light)', color: 'var(--color-error)' };
    case 'medium': return { bg: 'var(--color-warning-light)', color: 'var(--color-warning)' };
    case 'low': return { bg: 'var(--color-info-light)', color: 'var(--color-info)' };
    default: return { bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  }
};

const getSeverityLabel = (severity: string) => {
  const map: Record<string, () => string> = {
    high: () => t('severity_high'),
    medium: () => t('severity_medium'),
    low: () => t('severity_low'),
  };
  return map[severity]?.() ?? severity;
};

const getComplaintStatusStyle = (status: string) => {
  switch (status) {
    case 'processing': return { bg: 'var(--color-warning-light)', color: 'var(--color-warning)' };
    case 'resolved': return { bg: 'var(--color-success-light)', color: 'var(--color-success)' };
    case 'completed': return { bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
    default: return { bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  }
};

const getComplaintStatusLabel = (status: string) => {
  const map: Record<string, () => string> = {
    processing: () => t('cp_processing'),
    resolved: () => t('cp_resolved'),
    completed: () => t('completed'),
  };
  return map[status]?.() ?? status;
};

export const ConsumerProtectionPage: React.FC = () => {
  const { data, isLoading, error } = useApi<ConsumerProtectionData>('/api/v1/admin/insurance/stats');

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

  const stats = data?.stats ?? [];
  const complaintCategories = data?.complaintCategories ?? [];
  const csatTrend = data?.csatTrend ?? [];
  const recentComplaints = data?.recentComplaints ?? [];
  const nonCompliantIssuers = data?.nonCompliantIssuers ?? [];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1 style={{ font: 'var(--text-h1)', color: 'var(--color-text-primary)' }}>{t('cp_title')}</h1>
        <button style={{
          padding: '8px 16px', border: 'none', borderRadius: 'var(--radius-sm)',
          background: 'var(--color-primary)', color: 'white', cursor: 'pointer', font: 'var(--text-label)',
        }}>{t('export_report')}</button>
      </div>

      {/* Stats Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {stats.map(stat => (
          <div key={stat.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 }}>
              {stat.label}
            </div>
            <div style={{ font: 'var(--text-h1)', color: stat.color }}>
              {stat.value}
            </div>
            <div style={{
              font: 'var(--text-label-sm)',
              color: stat.invertTrend
                ? (stat.trend === 'down' ? 'var(--color-success)' : 'var(--color-error)')
                : (stat.trend === 'up' ? 'var(--color-success)' : 'var(--color-error)'),
              marginTop: 4,
            }}>
              {stat.change}
            </div>
          </div>
        ))}
      </div>

      {/* Complaint Categories + CSAT Trend */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
        {/* Complaint Category Breakdown */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ font: 'var(--text-h3)', marginBottom: 16 }}>{t('cp_complaint_categories')}</div>
          {complaintCategories.map(cat => (
            <div key={cat.name} style={{ marginBottom: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-primary)' }}>{cat.name}</span>
                <span style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>
                  {cat.count} {t('cp_unit_cases')} ({cat.percent}%)
                </span>
              </div>
              <div style={{
                width: '100%', height: 8,
                background: 'var(--color-gray-100)',
                borderRadius: 4,
                overflow: 'hidden',
              }}>
                <div style={{
                  width: `${cat.percent}%`,
                  height: '100%',
                  background: cat.color,
                  borderRadius: 4,
                }} />
              </div>
            </div>
          ))}
        </div>

        {/* CSAT Trend + Protection Fund */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Consumer Satisfaction Trend */}
          <div style={{
            background: 'var(--color-surface)',
            borderRadius: 'var(--radius-md)',
            border: '1px solid var(--color-border-light)',
            padding: 20,
            flex: 1,
          }}>
            <div style={{ font: 'var(--text-h3)', marginBottom: 12 }}>{t('cp_csat')}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 12 }}>
              <span style={{ font: 'var(--text-h1)', color: 'var(--color-success)' }}>
                {csatTrend.length > 0 ? csatTrend[csatTrend.length - 1].score : '-'}
              </span>
              <span style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>/5.0</span>
              {csatTrend.length >= 2 && (
                <span style={{ font: 'var(--text-label-sm)', color: 'var(--color-success)' }}>
                  {(csatTrend[csatTrend.length - 1].score - csatTrend[csatTrend.length - 2].score) >= 0 ? '+' : ''}
                  {(csatTrend[csatTrend.length - 1].score - csatTrend[csatTrend.length - 2].score).toFixed(1)}
                </span>
              )}
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              {csatTrend.map(item => (
                <div key={item.month} style={{ flex: 1, textAlign: 'center' }}>
                  <div style={{
                    height: 80,
                    display: 'flex',
                    alignItems: 'flex-end',
                    justifyContent: 'center',
                    marginBottom: 4,
                  }}>
                    <div style={{
                      width: '100%',
                      height: `${(item.score / 5) * 100}%`,
                      background: item.score >= 4.4 ? 'var(--color-success)' : item.score >= 4.2 ? 'var(--color-info)' : 'var(--color-warning)',
                      borderRadius: '4px 4px 0 0',
                      opacity: 0.7,
                    }} />
                  </div>
                  <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{item.month}</div>
                  <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-secondary)', fontWeight: 600 }}>{item.score}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Protection Fund Utilization */}
          <div style={{
            background: 'var(--color-surface)',
            borderRadius: 'var(--radius-md)',
            border: '1px solid var(--color-border-light)',
            padding: 20,
          }}>
            <div style={{ font: 'var(--text-h3)', marginBottom: 12 }}>{t('cp_protection_fund')}</div>
            <div style={{
              height: 100,
              background: 'var(--color-gray-50)',
              borderRadius: 'var(--radius-sm)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: 'var(--color-text-tertiary)',
            }}>
              Recharts 仪表盘图 (基金池 / 已用 / 使用率)
            </div>
          </div>
        </div>
      </div>

      {/* Recent Complaints Table */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        overflow: 'hidden',
        marginBottom: 24,
      }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--color-border-light)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ font: 'var(--text-h3)' }}>{t('cp_recent_complaints')}</span>
          <input
            placeholder={t('cp_search_complaints')}
            style={{
              width: 240, height: 32,
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              padding: '0 12px',
              font: 'var(--text-body-sm)',
            }}
          />
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--color-gray-50)' }}>
              {[t('cp_th_id'), t('cp_th_severity'), t('cp_th_category'), t('cp_th_description'), t('cp_th_status'), t('cp_th_assignee'), t('cp_th_date')].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>
            {recentComplaints.map(row => {
              const sev = getSeverityStyle(row.severity);
              const st = getComplaintStatusStyle(row.status);
              return (
                <tr key={row.id} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-body-sm)', fontFamily: 'var(--font-family-mono)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>
                    {row.id}
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{
                      padding: '2px 8px',
                      borderRadius: 'var(--radius-full)',
                      background: sev.bg,
                      color: sev.color,
                      font: 'var(--text-caption)',
                    }}>{getSeverityLabel(row.severity)}</span>
                  </td>
                  <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px' }}>{row.category}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', maxWidth: 280 }}>{row.title}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{
                      padding: '2px 8px',
                      borderRadius: 'var(--radius-full)',
                      background: st.bg,
                      color: st.color,
                      font: 'var(--text-caption)',
                    }}>{getComplaintStatusLabel(row.status)}</span>
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>{row.assignee}</td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px' }}>{row.created}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Refund Policy Compliance */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        overflow: 'hidden',
      }}>
        <div style={{ padding: '16px 20px', font: 'var(--text-h3)', borderBottom: '1px solid var(--color-border-light)' }}>
          {t('cp_refund_compliance')}
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--color-gray-50)' }}>
              {[t('cp_th_rank'), t('cp_th_issuer'), t('cp_th_violations'), t('cp_th_refund_rate'), t('cp_th_avg_delay'), t('cp_th_risk_level'), t('actions')].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>
            {nonCompliantIssuers.map(row => {
              const risk = getSeverityStyle(row.riskLevel);
              return (
                <tr key={row.rank} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{
                    font: 'var(--text-label-sm)',
                    padding: '10px 14px',
                    color: row.rank <= 2 ? 'var(--color-error)' : 'var(--color-text-tertiary)',
                    fontWeight: row.rank <= 2 ? 700 : 400,
                  }}>{row.rank}</td>
                  <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px' }}>{row.issuer}</td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-error)', padding: '10px 14px' }}>{row.violations}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{
                        width: 60, height: 6,
                        background: 'var(--color-gray-100)',
                        borderRadius: 3,
                        overflow: 'hidden',
                      }}>
                        <div style={{
                          width: row.refundRate,
                          height: '100%',
                          background: parseInt(row.refundRate) < 60 ? 'var(--color-error)' : parseInt(row.refundRate) < 75 ? 'var(--color-warning)' : 'var(--color-success)',
                          borderRadius: 3,
                        }} />
                      </div>
                      <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-secondary)' }}>{row.refundRate}</span>
                    </div>
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-warning)', padding: '10px 14px' }}>{row.avgDelay}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{
                      padding: '2px 8px',
                      borderRadius: 'var(--radius-full)',
                      background: risk.bg,
                      color: risk.color,
                      font: 'var(--text-caption)',
                    }}>{getSeverityLabel(row.riskLevel)}</span>
                  </td>
                  <td style={{ padding: '10px 14px', display: 'flex', gap: 4 }}>
                    <button style={{ padding: '4px 10px', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', background: 'none', cursor: 'pointer', font: 'var(--text-caption)', color: 'var(--color-text-secondary)' }}>{t('investigate')}</button>
                    <button style={{ padding: '4px 10px', border: 'none', borderRadius: 'var(--radius-sm)', background: 'var(--color-warning)', cursor: 'pointer', font: 'var(--text-caption)', color: 'white' }}>{t('warning_label')}</button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};
