import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';
import '../../../../app/i18n/app_localizations.dart';

/// 高级模式（Pro Mode）设置页
///
/// KYC L2+ 用户可开启，展示链上信息：
/// - WalletConnect 连接外部钱包
/// - 链上地址展示
/// - 交易Hash查看器
/// - 链上资产同步
/// 注：默认关闭，普通用户完全无感知区块链
class ProModePage extends StatefulWidget {
  const ProModePage({super.key});

  @override
  State<ProModePage> createState() => _ProModePageState();
}

class _ProModePageState extends State<ProModePage> {
  bool _proModeEnabled = false;
  bool _showChainAddress = false;
  bool _showTxHash = false;
  bool _walletConnected = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(context.t('profile.proMode'))),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Pro Mode Toggle
            _buildProModeCard(),
            const SizedBox(height: 20),

            if (_proModeEnabled) ...[
              // WalletConnect
              _buildWalletConnectCard(),
              const SizedBox(height: 16),

              // Chain Address Display
              _buildChainSettingsCard(),
              const SizedBox(height: 16),

              // Transaction Explorer
              _buildTxExplorerCard(),
              const SizedBox(height: 16),

              // Chain Assets
              _buildChainAssetsCard(),
              const SizedBox(height: 16),

              // Track Selection
              _buildTrackCard(),
            ],

            if (!_proModeEnabled) _buildProModeInfo(),
          ],
        ),
      ),
    );
  }

  Widget _buildProModeCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: _proModeEnabled ? AppColors.cardGradient : null,
        color: _proModeEnabled ? null : AppColors.surface,
        borderRadius: AppSpacing.borderRadiusLg,
        border: _proModeEnabled ? null : Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.code_rounded,
                color: _proModeEnabled ? Colors.white : AppColors.primary,
                size: 24,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '${context.t('profile.proMode')} (Pro)',
                      style: TextStyle(
                        fontSize: 17,
                        fontWeight: FontWeight.w700,
                        color: _proModeEnabled ? Colors.white : AppColors.textPrimary,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      context.t('proMode.toggleDesc'),
                      style: TextStyle(
                        fontSize: 12,
                        color: _proModeEnabled ? Colors.white70 : AppColors.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
              Switch(
                value: _proModeEnabled,
                onChanged: (v) => setState(() => _proModeEnabled = v),
                activeColor: Colors.white,
                activeTrackColor: Colors.white24,
              ),
            ],
          ),
          if (_proModeEnabled) ...[
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.white.withValues(alpha: 0.15),
                borderRadius: AppSpacing.borderRadiusFull,
              ),
              child: Text(
                context.t('proMode.requireKycL2'),
                style: const TextStyle(fontSize: 11, color: Colors.white70),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildWalletConnectCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.account_balance_wallet_rounded, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text('WalletConnect', style: AppTypography.labelLarge),
              const Spacer(),
              if (_walletConnected)
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                  decoration: BoxDecoration(
                    color: AppColors.successLight,
                    borderRadius: AppSpacing.borderRadiusFull,
                  ),
                  child: Text(context.t('proMode.connected'), style: const TextStyle(fontSize: 11, color: AppColors.success, fontWeight: FontWeight.w600)),
                ),
            ],
          ),
          const SizedBox(height: 12),
          if (_walletConnected) ...[
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: AppColors.gray50,
                borderRadius: AppSpacing.borderRadiusSm,
              ),
              child: Row(
                children: [
                  const CircleAvatar(radius: 16, backgroundColor: AppColors.primaryContainer, child: Text('M', style: TextStyle(fontSize: 14, color: AppColors.primary))),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('MetaMask', style: AppTypography.labelMedium),
                        Text('0x7a3b...c4f2', style: AppTypography.caption.copyWith(fontFamily: 'monospace')),
                      ],
                    ),
                  ),
                  TextButton(
                    onPressed: () => setState(() => _walletConnected = false),
                    child: Text(context.t('proMode.disconnect'), style: const TextStyle(color: AppColors.error, fontSize: 13)),
                  ),
                ],
              ),
            ),
          ] else
            SizedBox(
              width: double.infinity,
              child: OutlinedButton.icon(
                onPressed: () => setState(() => _walletConnected = true),
                icon: const Icon(Icons.link_rounded, size: 18),
                label: Text(context.t('proMode.connectWallet')),
              ),
            ),
          const SizedBox(height: 8),
          Text(
            context.t('proMode.walletDesc'),
            style: AppTypography.caption,
          ),
        ],
      ),
    );
  }

  Widget _buildChainSettingsCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        children: [
          SwitchListTile(
            title: Text(context.t('proMode.showChainAddress'), style: AppTypography.labelMedium),
            subtitle: Text(context.t('proMode.showChainAddressDesc'), style: AppTypography.caption),
            value: _showChainAddress,
            onChanged: (v) => setState(() => _showChainAddress = v),
            activeColor: AppColors.primary,
            contentPadding: EdgeInsets.zero,
          ),
          const Divider(height: 1),
          SwitchListTile(
            title: Text(context.t('proMode.showTxHash'), style: AppTypography.labelMedium),
            subtitle: Text(context.t('proMode.showTxHashDesc'), style: AppTypography.caption),
            value: _showTxHash,
            onChanged: (v) => setState(() => _showTxHash = v),
            activeColor: AppColors.primary,
            contentPadding: EdgeInsets.zero,
          ),
        ],
      ),
    );
  }

  Widget _buildTxExplorerCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.explore_rounded, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text(context.t('proMode.txExplorer'), style: AppTypography.labelLarge),
            ],
          ),
          const SizedBox(height: 12),
          _buildTxItem(context.t('proMode.txBuyExample'), '0xabc1...def3', context.t('proMode.confirmed'), AppColors.success),
          _buildTxItem(context.t('proMode.txSellExample'), '0x789a...bc12', context.t('proMode.confirmed'), AppColors.success),
          _buildTxItem('${context.t('txRecords.transferTo')} Alice', '0xdef4...5678', context.t('proMode.confirming'), AppColors.warning),
          const SizedBox(height: 8),
          Center(
            child: TextButton(
              onPressed: () {},
              child: Text(context.t('proMode.viewAllTx')),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTxItem(String title, String hash, String status, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(title, style: AppTypography.bodyMedium),
                Text(hash, style: AppTypography.caption.copyWith(fontFamily: 'monospace', color: AppColors.textLink)),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: AppSpacing.borderRadiusFull,
            ),
            child: Text(status, style: TextStyle(fontSize: 11, color: color, fontWeight: FontWeight.w600)),
          ),
        ],
      ),
    );
  }

  Widget _buildChainAssetsCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.token_rounded, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text(context.t('proMode.chainAssets'), style: AppTypography.labelLarge),
            ],
          ),
          const SizedBox(height: 12),
          _buildAssetRow(context.t('proMode.custodialWallet'), '0x1234...abcd', context.t('proMode.couponCount5')),
          if (_walletConnected) _buildAssetRow(context.t('proMode.externalWallet'), '0x7a3b...c4f2', context.t('proMode.couponCount0')),
          const SizedBox(height: 12),
          if (_walletConnected)
            SizedBox(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: () {},
                child: Text(context.t('proMode.extractToWallet')),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildAssetRow(String label, String address, String count) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(label, style: AppTypography.labelMedium),
                Text(address, style: AppTypography.caption.copyWith(fontFamily: 'monospace')),
              ],
            ),
          ),
          Text(count, style: AppTypography.labelMedium.copyWith(color: AppColors.primary)),
        ],
      ),
    );
  }

  Widget _buildTrackCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.swap_horiz_rounded, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text(context.t('proMode.tradeTrack'), style: AppTypography.labelLarge),
            ],
          ),
          const SizedBox(height: 12),
          _buildTrackOption('Utility Track', context.t('proMode.utilityTrackDesc'), AppColors.success, true),
          const SizedBox(height: 8),
          _buildTrackOption('Securities Track', context.t('proMode.securitiesTrackDesc'), AppColors.warning, false),
          const SizedBox(height: 8),
          Text(
            context.t('proMode.trackNote'),
            style: AppTypography.caption.copyWith(color: AppColors.textTertiary),
          ),
        ],
      ),
    );
  }

  Widget _buildTrackOption(String name, String desc, Color color, bool active) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: active ? color.withValues(alpha: 0.05) : AppColors.gray50,
        borderRadius: AppSpacing.borderRadiusSm,
        border: Border.all(color: active ? color : AppColors.borderLight),
      ),
      child: Row(
        children: [
          Container(
            width: 10,
            height: 10,
            decoration: BoxDecoration(
              color: active ? color : AppColors.textTertiary,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(name, style: AppTypography.labelMedium),
                Text(desc, style: AppTypography.caption),
              ],
            ),
          ),
          if (active) Icon(Icons.check_circle_rounded, color: color, size: 20),
          if (!active) Text(context.t('proMode.comingSoon'), style: AppTypography.caption.copyWith(color: AppColors.textTertiary)),
        ],
      ),
    );
  }

  Widget _buildProModeInfo() {
    return Container(
      margin: const EdgeInsets.only(top: 20),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: AppSpacing.borderRadiusMd,
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        children: [
          const Icon(Icons.info_outline_rounded, color: AppColors.textTertiary, size: 40),
          const SizedBox(height: 12),
          Text(context.t('proMode.whatIsTitle'), style: AppTypography.h3),
          const SizedBox(height: 8),
          Text(
            context.t('proMode.whatIsDesc'),
            style: AppTypography.bodyMedium.copyWith(color: AppColors.textSecondary, height: 1.6),
          ),
        ],
      ),
    );
  }
}
