'use client';

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

/**
 * D8. 争议处理
 *
 * 工单列表（买方申诉/卖方申诉/退款申请）、状态、处理时效
 * 工单详情：双方信息、链上交易记录（证据）、仲裁操作
 */

interface Dispute {
  id: string;
  type: string;
  order: string;
  plaintiff: string;
  defendant: string;
  amount: string;
  status: 'pending' | 'processing' | 'resolved' | 'rejected';
  createdAt: string;
  sla: string;
}

interface DisputeData {
  items: Dispute[];
  summary: { pending: number; processing: number; resolvedToday: number };
}

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

const getStatusConfig = (status: string) => {
  const map: Record<string, { label: () => string; bg: string; color: string }> = {
    pending: { label: () => t('dispute_pending'), bg: 'var(--color-warning-light)', color: 'var(--color-warning)' },
    processing: { label: () => t('dispute_processing'), bg: 'var(--color-info-light)', color: 'var(--color-info)' },
    resolved: { label: () => t('dispute_resolved'), bg: 'var(--color-success-light)', color: 'var(--color-success)' },
    rejected: { label: () => t('dispute_rejected'), bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' },
  };
  return map[status] ?? { label: () => status, bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
};

const getTypeConfig = (type: string) => {
  switch (type) {
    case 'buyer': return { bg: 'var(--color-error-light)', color: 'var(--color-error)', label: () => t('dispute_type_buyer') };
    case 'seller': return { bg: 'var(--color-warning-light)', color: 'var(--color-warning)', label: () => t('dispute_type_seller') };
    case 'refund': return { bg: 'var(--color-info-light)', color: 'var(--color-info)', label: () => t('dispute_type_refund') };
    default: return { bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)', label: () => type };
  }
};

export const DisputePage: React.FC = () => {
  const { data, isLoading, error } = useApi<DisputeData>('/api/v1/admin/disputes');

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

  const disputes = data?.items ?? [];
  const summary = data?.summary ?? { pending: 0, processing: 0, resolvedToday: 0 };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1 style={{ font: 'var(--text-h1)' }}>{t('dispute_title')}</h1>
        <div style={{ display: 'flex', gap: 12 }}>
          {/* Stats */}
          {[
            { label: t('dispute_pending'), value: String(summary.pending), color: 'var(--color-warning)' },
            { label: t('dispute_processing'), value: String(summary.processing), color: 'var(--color-info)' },
            { label: t('dispute_resolved_today'), value: String(summary.resolvedToday), color: 'var(--color-success)' },
          ].map(s => (
            <div key={s.label} style={{
              padding: '6px 14px',
              borderRadius: 'var(--radius-full)',
              background: `${s.color}15`,
              display: 'flex',
              alignItems: 'center',
              gap: 6,
            }}>
              <span style={{ font: 'var(--text-h3)', color: s.color }}>{s.value}</span>
              <span style={{ font: 'var(--text-caption)', color: s.color }}>{s.label}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Disputes Table */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        overflow: 'hidden',
      }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--color-gray-50)' }}>
              {[t('dispute_th_ticket_id'), t('dispute_th_type'), t('dispute_th_order'), t('dispute_th_plaintiff'), t('dispute_th_defendant'), t('dispute_th_amount'), t('dispute_th_status'), t('dispute_th_sla'), t('dispute_th_created'), t('actions')].map(h => (
                <th key={h} style={{
                  font: 'var(--text-label-sm)',
                  color: 'var(--color-text-tertiary)',
                  padding: '10px 12px',
                  textAlign: 'left',
                }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {disputes.map(d => {
              const sc = getStatusConfig(d.status);
              const tc = getTypeConfig(d.type);
              return (
                <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 12px' }}>{d.id}</td>
                  <td style={{ padding: '10px 12px' }}>
                    <span style={{
                      padding: '2px 8px', borderRadius: 'var(--radius-full)',
                      background: tc.bg, color: tc.color, font: 'var(--text-caption)',
                    }}>{tc.label()}</span>
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-link)', padding: '10px 12px', cursor: 'pointer' }}>{d.order}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 12px' }}>{d.plaintiff}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 12px' }}>{d.defendant}</td>
                  <td style={{ font: 'var(--text-label-sm)', color: 'var(--color-primary)', padding: '10px 12px' }}>{d.amount}</td>
                  <td style={{ padding: '10px 12px' }}>
                    <span style={{
                      padding: '2px 8px', borderRadius: 'var(--radius-full)',
                      background: sc.bg, color: sc.color, font: 'var(--text-caption)',
                    }}>{sc.label()}</span>
                  </td>
                  <td style={{ padding: '10px 12px' }}>
                    {d.sla !== '-' ? (
                      <span style={{
                        font: 'var(--text-label-sm)',
                        color: parseInt(d.sla) > 24 ? 'var(--color-error)' : 'var(--color-text-secondary)',
                      }}>{d.sla}</span>
                    ) : (
                      <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-disabled)' }}>-</span>
                    )}
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', padding: '10px 12px' }}>{d.createdAt}</td>
                  <td style={{ padding: '10px 12px' }}>
                    <button style={{
                      padding: '4px 12px', border: '1px solid var(--color-border)',
                      borderRadius: 'var(--radius-sm)', background: 'none', cursor: 'pointer',
                      font: 'var(--text-caption)', color: 'var(--color-primary)',
                    }}>
                      {d.status === 'pending' || d.status === 'processing' ? t('process') : t('view')}
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};
