'use client';

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

/**
 * D2. 券管理 - 平台券审核与管理
 *
 * 发行方提交的券审核、已上架券管理、券数据统计
 */

interface CouponBatch {
  id: string;
  issuer: string;
  name: string;
  template: string;
  faceValue: number;
  quantity: number;
  sold: number;
  redeemed: number;
  status: 'pending' | 'active' | 'suspended' | 'expired';
  createdAt: string;
}

interface CouponsResponse {
  items: CouponBatch[];
  total: number;
}

const statusColors: Record<string, string> = {
  pending: 'var(--color-warning)',
  active: 'var(--color-success)',
  suspended: 'var(--color-error)',
  expired: 'var(--color-text-tertiary)',
};

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

export const CouponManagementPage: React.FC = () => {
  const [filter, setFilter] = useState('all');
  const [page] = useState(1);
  const [limit] = useState(20);

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

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

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

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

  const coupons = data?.items ?? [];

  const statusLabels: Record<string, string> = {
    pending: t('coupon_pending_review'),
    active: t('coupon_active'),
    suspended: t('coupon_suspended'),
    expired: t('coupon_expired'),
  };

  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('coupon_management_title')}</h1>
        <div style={{ display: 'flex', gap: 8 }}>
          {['all', 'pending', 'active', 'suspended', 'expired'].map(f => (
            <button key={f} onClick={() => setFilter(f)} style={{
              padding: '6px 14px', border: 'none', borderRadius: 'var(--radius-full)',
              background: filter === f ? 'var(--color-primary)' : 'var(--color-gray-100)',
              color: filter === f ? 'white' : 'var(--color-text-secondary)',
              cursor: 'pointer', font: 'var(--text-label-sm)',
            }}>
              {f === 'all' ? t('all') : statusLabels[f]}
            </button>
          ))}
        </div>
      </div>

      {/* Coupon 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={{ borderBottom: '1px solid var(--color-border-light)' }}>
                {[t('coupon_id'), t('coupon_issuer'), t('coupon_name'), t('coupon_template'), t('coupon_face_value'), t('coupon_quantity'), t('coupon_sold'), t('coupon_redeemed'), t('status'), t('actions')].map(h => (
                  <th key={h} style={{ padding: '12px 16px', textAlign: 'left', font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {coupons.map(coupon => (
                <tr key={coupon.id} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={cellStyle}><span style={{ font: 'var(--text-label-sm)', fontFamily: 'var(--font-family-mono)' }}>{coupon.id}</span></td>
                  <td style={cellStyle}>{coupon.issuer}</td>
                  <td style={cellStyle}><strong>{coupon.name}</strong></td>
                  <td style={cellStyle}>{coupon.template}</td>
                  <td style={cellStyle}>${coupon.faceValue}</td>
                  <td style={cellStyle}>{coupon.quantity.toLocaleString()}</td>
                  <td style={cellStyle}>{coupon.sold.toLocaleString()}</td>
                  <td style={cellStyle}>{coupon.redeemed.toLocaleString()}</td>
                  <td style={cellStyle}>
                    <span style={{
                      display: 'inline-block', padding: '2px 8px', borderRadius: 'var(--radius-full)',
                      background: `${statusColors[coupon.status]}15`, color: statusColors[coupon.status],
                      font: 'var(--text-caption)', fontWeight: 600,
                    }}>{statusLabels[coupon.status]}</span>
                  </td>
                  <td style={cellStyle}>
                    {coupon.status === 'pending' && (
                      <div style={{ display: 'flex', gap: 8 }}>
                        <button
                          onClick={() => approveMutation.mutate({ couponId: coupon.id, action: 'approve' })}
                          style={btnStyle('var(--color-success)')}>{t('coupon_approve')}</button>
                        <button
                          onClick={() => rejectMutation.mutate({ couponId: coupon.id, action: 'reject' })}
                          style={btnStyle('var(--color-error)')}>{t('coupon_reject')}</button>
                      </div>
                    )}
                    {coupon.status === 'active' && (
                      <button
                        onClick={() => suspendMutation.mutate({ couponId: coupon.id, action: 'suspend' })}
                        style={btnStyle('var(--color-warning)')}>{t('suspend')}</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

const cellStyle: React.CSSProperties = { padding: '12px 16px', font: 'var(--text-body)', color: 'var(--color-text-primary)' };
const btnStyle = (color: string): React.CSSProperties => ({
  padding: '4px 12px', border: `1px solid ${color}`, borderRadius: 'var(--radius-sm)',
  background: 'transparent', color, cursor: 'pointer', font: 'var(--text-label-sm)',
});
