import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.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: const Text('高级模式')),
      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(
                      '高级模式 (Pro)',
                      style: TextStyle(
                        fontSize: 17,
                        fontWeight: FontWeight.w700,
                        color: _proModeEnabled ? Colors.white : AppColors.textPrimary,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      '开启后可查看链上信息和连接外部钱包',
                      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: const Text(
                '需要 KYC L2 及以上认证',
                style: 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: const Text('已连接', style: 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: const Text('断开', style: 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: const Text('连接外部钱包'),
              ),
            ),
          const SizedBox(height: 8),
          Text(
            '连接外部钱包后可将平台资产提取至自有地址',
            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('显示链上地址', style: AppTypography.labelMedium),
            subtitle: Text('在券详情中展示合约地址', style: AppTypography.caption),
            value: _showChainAddress,
            onChanged: (v) => setState(() => _showChainAddress = v),
            activeColor: AppColors.primary,
            contentPadding: EdgeInsets.zero,
          ),
          const Divider(height: 1),
          SwitchListTile(
            title: Text('显示交易Hash', style: AppTypography.labelMedium),
            subtitle: Text('在交易记录中展示链上Hash', 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('交易浏览器', style: AppTypography.labelLarge),
            ],
          ),
          const SizedBox(height: 12),
          _buildTxItem('购买 星巴克 \$25 礼品卡', '0xabc1...def3', '已确认', AppColors.success),
          _buildTxItem('出售 Amazon \$100 券', '0x789a...bc12', '已确认', AppColors.success),
          _buildTxItem('转赠给 Alice', '0xdef4...5678', '确认中', AppColors.warning),
          const SizedBox(height: 8),
          Center(
            child: TextButton(
              onPressed: () {},
              child: const Text('查看全部链上交易'),
            ),
          ),
        ],
      ),
    );
  }

  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('链上资产', style: AppTypography.labelLarge),
            ],
          ),
          const SizedBox(height: 12),
          _buildAssetRow('平台托管钱包', '0x1234...abcd', '5 张券'),
          if (_walletConnected) _buildAssetRow('外部钱包 (MetaMask)', '0x7a3b...c4f2', '0 张券'),
          const SizedBox(height: 12),
          if (_walletConnected)
            SizedBox(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: () {},
                child: const Text('提取至外部钱包'),
              ),
            ),
        ],
      ),
    );
  }

  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('交易轨道', style: AppTypography.labelLarge),
            ],
          ),
          const SizedBox(height: 12),
          _buildTrackOption('Utility Track', '券有效期≤12个月，无需证券牌照', AppColors.success, true),
          const SizedBox(height: 8),
          _buildTrackOption('Securities Track', '长期投资型券产品（即将推出）', AppColors.warning, false),
          const SizedBox(height: 8),
          Text(
            '当前MVP版本仅支持Utility Track',
            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('敬请期待', 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('什么是高级模式？', style: AppTypography.h3),
          const SizedBox(height: 8),
          Text(
            '高级模式面向有区块链经验的用户，开启后可以：\n'
            '• 连接外部钱包（MetaMask等）\n'
            '• 查看链上地址和交易Hash\n'
            '• 将资产提取至自有钱包\n'
            '• 查看底层链上数据\n\n'
            '需要完成 KYC L2 认证后方可开启。',
            style: AppTypography.bodyMedium.copyWith(color: AppColors.textSecondary, height: 1.6),
          ),
        ],
      ),
    );
  }
}
