'use client';

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

/**
 * D2. 发行方管理
 *
 * 入驻审核列表、发行方详情、券审核列表
 */

interface Issuer {
  id: string;
  name: string;
  creditRating: string;
  status: 'pending' | 'approved' | 'rejected';
  submittedAt: string;
  couponCount: number;
  totalVolume: number;
}

interface IssuersResponse {
  items: Issuer[];
  total: number;
}

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

export const IssuerManagementPage: React.FC = () => {
  const [tab, setTab] = useState<'all' | 'pending' | 'approved' | 'rejected'>('all');
  const [page] = useState(1);
  const [limit] = useState(20);

  const { data, isLoading, error } = useApi<IssuersResponse>('/api/v1/admin/issuers', {
    params: { page, limit, status: tab === 'all' ? undefined : tab },
  });

  const approveMutation = useApiMutation<void>('POST', '', {
    invalidateKeys: ['/api/v1/admin/issuers'],
  });

  const rejectMutation = useApiMutation<void>('POST', '', {
    invalidateKeys: ['/api/v1/admin/issuers'],
  });

  const issuers = data?.items ?? [];
  const pendingCount = issuers.filter(i => i.status === 'pending').length;

  const creditColor = (rating: string) => {
    const map: Record<string, string> = {
      'AAA': 'var(--color-credit-aaa)',
      'AA': 'var(--color-credit-aa)',
      'A': 'var(--color-credit-a)',
      'BBB': 'var(--color-credit-bbb)',
    };
    return map[rating] || 'var(--color-text-tertiary)';
  };

  const statusStyle = (status: string) => {
    const map: Record<string, { bg: string; color: string }> = {
      pending: { bg: 'var(--color-warning-light)', color: 'var(--color-warning)' },
      approved: { bg: 'var(--color-success-light)', color: 'var(--color-success)' },
      rejected: { bg: 'var(--color-error-light)', color: 'var(--color-error)' },
    };
    return map[status] || { bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  };

  const statusLabel = (status: string) => {
    const map: Record<string, string> = { pending: t('issuer_onboarding_pending'), approved: t('issuer_onboarding_approved'), rejected: t('issuer_onboarding_rejected') };
    return map[status] || status;
  };

  const formatCurrency = (n: number) => n > 0 ? `$${n.toLocaleString()}` : '-';

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1 style={{ font: 'var(--text-h1)' }}>{t('issuer_management_title')}</h1>
        <div style={{ display: 'flex', gap: 8 }}>
          <button style={{
            padding: '6px 16px',
            border: '1px solid var(--color-primary)',
            borderRadius: 'var(--radius-full)',
            background: 'var(--color-primary-surface)',
            color: 'var(--color-primary)',
            cursor: 'pointer',
            font: 'var(--text-label-sm)',
          }}>
            ✨ {t('issuer_ai_pre_review')}
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 20 }}>
        {(['all', 'pending', 'approved', 'rejected'] as const).map(tabKey => (
          <button
            key={tabKey}
            onClick={() => setTab(tabKey)}
            style={{
              padding: '8px 16px',
              border: 'none',
              borderRadius: 'var(--radius-full)',
              background: tab === tabKey ? 'var(--color-primary)' : 'var(--color-gray-50)',
              color: tab === tabKey ? 'white' : 'var(--color-text-secondary)',
              cursor: 'pointer',
              font: 'var(--text-label-sm)',
            }}
          >
            {tabKey === 'all' ? t('all') : statusLabel(tabKey)}
            {tabKey === 'pending' && pendingCount > 0 && (
              <span style={{
                marginLeft: 4, padding: '0 5px',
                background: 'var(--color-error)',
                color: 'white',
                borderRadius: 'var(--radius-full)',
                fontSize: 10,
              }}>
                {pendingCount}
              </span>
            )}
          </button>
        ))}
      </div>

      {/* Table */}
      {error ? (
        <div style={loadingBox}>Error: {error.message}</div>
      ) : isLoading ? (
        <div style={loadingBox}>Loading...</div>
      ) : (
        <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)', borderBottom: '1px solid var(--color-border)' }}>
                {['ID', t('issuer_company_name'), t('issuer_credit_rating'), t('status'), t('issuer_submit_time'), t('issuer_coupon_count'), t('issuer_total_volume'), t('actions')].map(h => (
                  <th key={h} style={{
                    font: 'var(--text-label-sm)',
                    color: 'var(--color-text-tertiary)',
                    padding: '12px 16px',
                    textAlign: 'left',
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {issuers.map(issuer => {
                const ss = statusStyle(issuer.status);
                return (
                  <tr key={issuer.id} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                    <td style={{ font: 'var(--text-body-sm)', fontFamily: 'var(--font-family-mono)', padding: '12px 16px', color: 'var(--color-text-tertiary)' }}>
                      {issuer.id}
                    </td>
                    <td style={{ font: 'var(--text-label)', padding: '12px 16px' }}>{issuer.name}</td>
                    <td style={{ padding: '12px 16px' }}>
                      <span style={{
                        padding: '2px 8px',
                        borderRadius: 'var(--radius-full)',
                        border: `1px solid ${creditColor(issuer.creditRating)}33`,
                        background: `${creditColor(issuer.creditRating)}11`,
                        color: creditColor(issuer.creditRating),
                        font: 'var(--text-label-sm)',
                        fontWeight: 700,
                      }}>
                        {issuer.creditRating || '-'}
                      </span>
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <span style={{
                        padding: '2px 10px',
                        borderRadius: 'var(--radius-full)',
                        background: ss.bg,
                        color: ss.color,
                        font: 'var(--text-caption)',
                        fontWeight: 500,
                      }}>
                        {statusLabel(issuer.status)}
                      </span>
                    </td>
                    <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', padding: '12px 16px' }}>
                      {issuer.submittedAt}
                    </td>
                    <td style={{ font: 'var(--text-body-sm)', padding: '12px 16px' }}>{issuer.couponCount}</td>
                    <td style={{ font: 'var(--text-label-sm)', color: 'var(--color-primary)', padding: '12px 16px' }}>
                      {formatCurrency(issuer.totalVolume)}
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <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)',
                      }}>
                        {t('details')}
                      </button>
                      {issuer.status === 'pending' && (
                        <>
                          <button
                            onClick={() => approveMutation.mutate({ issuerId: issuer.id, action: 'approve' })}
                            style={{
                              marginLeft: 8,
                              padding: '4px 12px',
                              border: 'none',
                              borderRadius: 'var(--radius-sm)',
                              background: 'var(--color-primary)',
                              cursor: 'pointer',
                              font: 'var(--text-caption)',
                              color: 'white',
                            }}>
                            {t('review')}
                          </button>
                          <button
                            onClick={() => rejectMutation.mutate({ issuerId: issuer.id, action: 'reject' })}
                            style={{
                              marginLeft: 4,
                              padding: '4px 12px',
                              border: 'none',
                              borderRadius: 'var(--radius-sm)',
                              background: 'var(--color-error)',
                              cursor: 'pointer',
                              font: 'var(--text-caption)',
                              color: 'white',
                            }}>
                            {t('issuer_onboarding_rejected')}
                          </button>
                        </>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};
