import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../../../core/updater/updater.dart';

/// 关于我们页面
class AboutPage extends StatefulWidget {
  const AboutPage({super.key});

  @override
  State<AboutPage> createState() => _AboutPageState();
}

class _AboutPageState extends State<AboutPage> {
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _darkText = Color(0xFF1F2937);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _bgGray = Color(0xFFF3F4F6);

  String _version = '';
  String _buildNumber = '';
  bool _isCheckingUpdate = false;

  @override
  void initState() {
    super.initState();
    _loadPackageInfo();
  }

  Future<void> _loadPackageInfo() async {
    try {
      final info = await PackageInfo.fromPlatform();
      setState(() {
        _version = info.version;
        _buildNumber = info.buildNumber;
      });
    } catch (e) {
      setState(() {
        _version = '1.0.0';
        _buildNumber = '1';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _bgGray,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: _darkText, size: 20),
          onPressed: () => context.pop(),
        ),
        title: const Text(
          '关于我们',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: _darkText,
          ),
        ),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(height: 32),
            // Logo和应用名称
            _buildAppHeader(),
            const SizedBox(height: 32),
            // 应用简介
            _buildIntroSection(),
            const SizedBox(height: 16),
            // 功能特点
            _buildFeaturesSection(),
            const SizedBox(height: 16),
            // 联系信息
            _buildContactSection(),
            const SizedBox(height: 16),
            // 版本信息和法律条款
            _buildLegalSection(),
            const SizedBox(height: 24),
            // 版权信息
            _buildCopyright(),
            const SizedBox(height: 24),
          ],
        ),
      ),
    );
  }

  Widget _buildAppHeader() {
    return Column(
      children: [
        // 应用图标
        Container(
          width: 80,
          height: 80,
          decoration: BoxDecoration(
            color: _orange,
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                color: _orange.withOpacity(0.3),
                blurRadius: 20,
                offset: const Offset(0, 8),
              ),
            ],
          ),
          child: const Icon(
            Icons.eco,
            color: Colors.white,
            size: 48,
          ),
        ),
        const SizedBox(height: 16),
        // 应用名称
        const Text(
          '股行',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: _darkText,
          ),
        ),
        const SizedBox(height: 8),
        // 版本号
        Text(
          'Version $_version${_buildNumber.isNotEmpty ? ' ($_buildNumber)' : ''}',
          style: const TextStyle(
            fontSize: 14,
            color: _grayText,
          ),
        ),
      ],
    );
  }

  Widget _buildIntroSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle('应用简介'),
          const SizedBox(height: 12),
          Text(
            '股行是一家，致力于上市规划咨询，数字资产规划咨询，行业数据报告咨询，等相关的一系列咨询服务平台。'
            '用户可通过手机端平台支付积分值来享受相关联的各种服务以及各上市公司原始股的优先购买服务权，等一系列服务',
            style: TextStyle(
              fontSize: 14,
              color: _grayText.withOpacity(0.9),
              height: 1.6,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFeaturesSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle('核心功能'),
          const SizedBox(height: 16),
          _buildFeatureItem(
            icon: Icons.eco,
            title: '参与',
            description: '参与活动，获得贡献值奖励',
          ),
          const SizedBox(height: 12),
          _buildFeatureItem(
            icon: Icons.trending_up,
            title: '每日收益',
            description: '根据贡献值占比，每日自动分配积分股',
          ),
          const SizedBox(height: 12),
          _buildFeatureItem(
            icon: Icons.swap_horiz,
            title: '便捷交易',
            description: '支持积分股卖出兑换，积分值自由转账',
          ),
          const SizedBox(height: 12),
          _buildFeatureItem(
            icon: Icons.people,
            title: '同伴收益',
            description: '邀请好友，获得同伴贡献值奖励',
          ),
        ],
      ),
    );
  }

  Widget _buildFeatureItem({
    required IconData icon,
    required String title,
    required String description,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: _orange.withOpacity(0.1),
            borderRadius: BorderRadius.circular(10),
          ),
          child: Icon(icon, color: _orange, size: 22),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: _darkText,
                ),
              ),
              const SizedBox(height: 2),
              Text(
                description,
                style: TextStyle(
                  fontSize: 12,
                  color: _grayText.withOpacity(0.9),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildContactSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle('联系方式'),
          const SizedBox(height: 16),
          _buildContactItem(
            icon: Icons.email_outlined,
            label: '客服邮箱',
            value: 'support@guhang.com',
            onTap: () {
              Clipboard.setData(const ClipboardData(text: 'support@guhang.com'));
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('邮箱已复制'),
                  duration: Duration(seconds: 1),
                ),
              );
            },
          ),
          const Divider(height: 24),
          _buildContactItem(
            icon: Icons.language,
            label: '官方网站',
            value: 'www.guhang.com',
            onTap: () {
              // TODO: 打开官网
            },
          ),
        ],
      ),
    );
  }

  Widget _buildContactItem({
    required IconData icon,
    required String label,
    required String value,
    VoidCallback? onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          children: [
            Icon(icon, size: 20, color: _orange),
            const SizedBox(width: 12),
            Text(
              '$label: ',
              style: const TextStyle(
                fontSize: 14,
                color: _grayText,
              ),
            ),
            Expanded(
              child: Text(
                value,
                style: const TextStyle(
                  fontSize: 14,
                  color: _darkText,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            if (onTap != null)
              const Icon(Icons.chevron_right, size: 20, color: _grayText),
          ],
        ),
      ),
    );
  }

  Future<void> _checkForUpdate() async {
    if (_isCheckingUpdate) return;

    setState(() {
      _isCheckingUpdate = true;
    });

    try {
      final result = await UpdateService.instance.checkForUpdate(force: true);

      if (!mounted) return;

      if (result.hasUpdate && result.versionInfo != null) {
        SelfHostedUpdater.show(
          context,
          versionInfo: result.versionInfo!,
          isForceUpdate: result.versionInfo!.isForceUpdate,
        );
      } else if (result.error != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(result.error!)),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('已是最新版本')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isCheckingUpdate = false;
        });
      }
    }
  }

  Widget _buildLegalSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle('法律条款'),
          const SizedBox(height: 16),
          _buildLegalItem(
            title: '检查更新',
            trailing: _isCheckingUpdate
                ? const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                : null,
            onTap: _checkForUpdate,
          ),
          const Divider(height: 24),
          _buildLegalItem(
            title: '用户协议',
            onTap: () {
              // TODO: 跳转用户协议页面
            },
          ),
          const Divider(height: 24),
          _buildLegalItem(
            title: '隐私政策',
            onTap: () {
              // TODO: 跳转隐私政策页面
            },
          ),
        ],
      ),
    );
  }

  Widget _buildLegalItem({
    required String title,
    required VoidCallback onTap,
    Widget? trailing,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(
                title,
                style: const TextStyle(
                  fontSize: 14,
                  color: _darkText,
                ),
              ),
            ),
            if (trailing != null) trailing else const Icon(Icons.chevron_right, size: 20, color: _grayText),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Row(
      children: [
        Container(
          width: 4,
          height: 16,
          decoration: BoxDecoration(
            color: _orange,
            borderRadius: BorderRadius.circular(2),
          ),
        ),
        const SizedBox(width: 8),
        Text(
          title,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: _darkText,
          ),
        ),
      ],
    );
  }

  Widget _buildCopyright() {
    return Column(
      children: [
        Text(
          'Copyright © ${DateTime.now().year} 股行',
          style: const TextStyle(
            fontSize: 12,
            color: _grayText,
          ),
        ),
        const SizedBox(height: 4),
        const Text(
          'All Rights Reserved',
          style: TextStyle(
            fontSize: 12,
            color: _grayText,
          ),
        ),
      ],
    );
  }
}
