'use client';

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

/**
 * D3. 用户管理
 *
 * 用户列表（搜索/KYC筛选）、用户详情、KYC审核
 */

interface User {
  id: string;
  phone: string;
  email: string;
  kycLevel: number;
  couponCount: number;
  totalTraded: number;
  riskTags: string[];
  createdAt: string;
  status?: 'ACTIVE' | 'FROZEN';
  loginFailCount?: number;
  lockedUntil?: string | null;
}

interface UsersResponse {
  items: User[];
  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 UserManagementPage: React.FC = () => {
  const [search, setSearch] = useState('');
  const [kycFilter, setKycFilter] = useState<number | null>(null);
  const [page] = useState(1);
  const [limit] = useState(20);

  const { data, isLoading, error } = useApi<UsersResponse>('/api/v1/admin/users', {
    params: { page, limit, search: search || undefined, kycLevel: kycFilter ?? undefined },
  });

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

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

  const maskPhone = (phone: string) => {
    if (!phone) return '-';
    const raw = phone.startsWith('+86') ? phone.slice(3) : phone;
    if (raw.length < 7) return phone;
    return (phone.startsWith('+86') ? '+86 ' : '') + raw.slice(0, 3) + '****' + raw.slice(-4);
  };

  const isLocked = (user: User) => user.lockedUntil && new Date(user.lockedUntil) > new Date();

  const statusBadge = (user: User) => {
    if (user.status === 'FROZEN') {
      return <span style={{ padding: '2px 8px', borderRadius: 'var(--radius-full)', background: 'var(--color-error-light)', color: 'var(--color-error)', font: 'var(--text-label-sm)', fontWeight: 600 }}>{t('user_frozen')}</span>;
    }
    if (isLocked(user)) {
      return <span style={{ padding: '2px 8px', borderRadius: 'var(--radius-full)', background: 'var(--color-warning-light)', color: 'var(--color-warning)', font: 'var(--text-label-sm)', fontWeight: 600 }}>{t('user_locked')}</span>;
    }
    return <span style={{ padding: '2px 8px', borderRadius: 'var(--radius-full)', background: 'var(--color-success-light)', color: 'var(--color-success)', font: 'var(--text-label-sm)', fontWeight: 600 }}>{t('user_active')}</span>;
  };

  const kycBadge = (level: number) => {
    const colors = ['var(--color-gray-400)', 'var(--color-info)', 'var(--color-primary)', 'var(--color-success)'];
    return (
      <span style={{
        padding: '2px 8px',
        borderRadius: 'var(--radius-full)',
        background: `${colors[level]}15`,
        color: colors[level],
        font: 'var(--text-label-sm)',
        fontWeight: 600,
      }}>
        L{level}
      </span>
    );
  };

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

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

      {/* Search + Filters */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 20 }}>
        <input
          placeholder={t('user_search_placeholder')}
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{
            flex: 1,
            maxWidth: 360,
            height: 40,
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-sm)',
            padding: '0 16px',
            font: 'var(--text-body)',
          }}
        />
        {[null, 0, 1, 2, 3].map(level => (
          <button
            key={level ?? 'all'}
            onClick={() => setKycFilter(level)}
            style={{
              padding: '8px 14px',
              border: 'none',
              borderRadius: 'var(--radius-full)',
              background: kycFilter === level ? 'var(--color-primary)' : 'var(--color-gray-50)',
              color: kycFilter === level ? 'white' : 'var(--color-text-secondary)',
              cursor: 'pointer',
              font: 'var(--text-label-sm)',
            }}
          >
            {level === null ? t('all') : `L${level}`}
          </button>
        ))}
      </div>

      {/* Users 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)' }}>
                {[t('user_id'), t('user_phone'), t('user_email'), t('user_status'), t('user_kyc_level'), t('user_coupon_count'), t('user_total_traded'), t('user_risk_tags'), t('user_created_at'), t('actions')].map(h => (
                  <th key={h} style={{
                    font: 'var(--text-label-sm)',
                    color: 'var(--color-text-tertiary)',
                    padding: '12px 14px',
                    textAlign: 'left',
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {users.map(user => (
                <tr key={user.id} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-body-sm)', fontFamily: 'var(--font-family-mono)', padding: '12px 14px', color: 'var(--color-text-tertiary)' }}>{user.id}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '12px 14px' }}>{maskPhone(user.phone)}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '12px 14px' }}>{user.email}</td>
                  <td style={{ padding: '12px 14px' }}>{statusBadge(user)}</td>
                  <td style={{ padding: '12px 14px' }}>{kycBadge(user.kycLevel)}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '12px 14px' }}>{user.couponCount}</td>
                  <td style={{ font: 'var(--text-label-sm)', color: 'var(--color-primary)', padding: '12px 14px' }}>{formatCurrency(user.totalTraded)}</td>
                  <td style={{ padding: '12px 14px' }}>
                    {user.riskTags.length > 0
                      ? user.riskTags.map(tag => (
                          <span key={tag} style={{
                            padding: '2px 6px',
                            borderRadius: 'var(--radius-full)',
                            background: 'var(--color-error-light)',
                            color: 'var(--color-error)',
                            font: 'var(--text-caption)',
                            marginRight: 4,
                          }}>{tag}</span>
                        ))
                      : <span style={{ color: 'var(--color-text-disabled)', font: 'var(--text-caption)' }}>-</span>
                    }
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', padding: '12px 14px' }}>{user.createdAt}</td>
                  <td style={{ padding: '12px 14px', whiteSpace: 'nowrap' }}>
                    <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>
                    {user.status === 'FROZEN' ? (
                      <button
                        onClick={() => freezeMutation.mutate({ userId: user.id })}
                        style={{
                          marginLeft: 6,
                          padding: '4px 12px',
                          border: 'none',
                          borderRadius: 'var(--radius-sm)',
                          background: 'var(--color-success)',
                          cursor: 'pointer',
                          font: 'var(--text-caption)',
                          color: 'white',
                        }}>{t('user_unfreeze')}</button>
                    ) : (
                      <button
                        onClick={() => freezeMutation.mutate({ userId: user.id })}
                        style={{
                          marginLeft: 6,
                          padding: '4px 12px',
                          border: 'none',
                          borderRadius: 'var(--radius-sm)',
                          background: 'var(--color-error)',
                          cursor: 'pointer',
                          font: 'var(--text-caption)',
                          color: 'white',
                        }}>{t('user_freeze')}</button>
                    )}
                    {isLocked(user) && (
                      <button
                        onClick={() => unlockMutation.mutate(undefined, {
                          onSuccess: () => {},
                        })}
                        style={{
                          marginLeft: 6,
                          padding: '4px 12px',
                          border: '1px solid var(--color-warning)',
                          borderRadius: 'var(--radius-sm)',
                          background: 'none',
                          cursor: 'pointer',
                          font: 'var(--text-caption)',
                          color: 'var(--color-warning)',
                        }}>{t('user_unlock')}</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};
