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

/// AI Agent 全屏对话页面（消费者端）
///
/// 场景：智能推券、比价分析、组合建议、投资教育
class AgentChatPage extends StatefulWidget {
  const AgentChatPage({super.key});

  @override
  State<AgentChatPage> createState() => _AgentChatPageState();
}

class _AgentChatPageState extends State<AgentChatPage> {
  final _controller = TextEditingController();
  final _scrollController = ScrollController();
  final List<_Msg> _messages = [
    _Msg(true, '你好！我是 Genex AI 助手，可以帮你发现高性价比好券、比价分析、组合推荐。试试问我：'),
  ];
  final _suggestions = ['推荐适合我的券', '星巴克券值不值得买？', '帮我做比价分析', '我的券快到期了怎么办？'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.auto_awesome_rounded, color: AppColors.primary, size: 20),
            SizedBox(width: 8),
            Text('AI 助手'),
          ],
        ),
        actions: [
          IconButton(icon: const Icon(Icons.more_horiz_rounded), onPressed: () {}),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              controller: _scrollController,
              padding: const EdgeInsets.all(16),
              itemCount: _messages.length,
              itemBuilder: (context, i) => _buildBubble(_messages[i]),
            ),
          ),

          // Suggestion Chips
          if (_messages.length <= 2)
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
              child: Row(
                children: _suggestions.map((s) => Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: ActionChip(
                    label: Text(s, style: const TextStyle(fontSize: 12)),
                    onPressed: () => _send(s),
                    backgroundColor: AppColors.primarySurface,
                    side: BorderSide.none,
                  ),
                )).toList(),
              ),
            ),

          // Input
          Container(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
            decoration: const BoxDecoration(
              color: AppColors.surface,
              border: Border(top: BorderSide(color: AppColors.borderLight)),
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: InputDecoration(
                      hintText: '问我任何关于券的问题...',
                      border: OutlineInputBorder(
                        borderRadius: AppSpacing.borderRadiusFull,
                        borderSide: const BorderSide(color: AppColors.borderLight),
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    ),
                    onSubmitted: _send,
                  ),
                ),
                const SizedBox(width: 8),
                Container(
                  decoration: const BoxDecoration(color: AppColors.primary, shape: BoxShape.circle),
                  child: IconButton(
                    icon: const Icon(Icons.send_rounded, color: Colors.white, size: 20),
                    onPressed: () => _send(_controller.text),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBubble(_Msg msg) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: msg.isAi ? MainAxisAlignment.start : MainAxisAlignment.end,
        children: [
          if (msg.isAi) ...[
            Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                gradient: AppColors.primaryGradient,
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Icon(Icons.auto_awesome_rounded, color: Colors.white, size: 16),
            ),
            const SizedBox(width: 8),
          ],
          Flexible(
            child: Container(
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: msg.isAi ? AppColors.gray50 : AppColors.primary,
                borderRadius: BorderRadius.circular(16).copyWith(
                  topLeft: msg.isAi ? const Radius.circular(4) : null,
                  topRight: !msg.isAi ? const Radius.circular(4) : null,
                ),
              ),
              child: Text(
                msg.text,
                style: AppTypography.bodyMedium.copyWith(
                  color: msg.isAi ? AppColors.textPrimary : Colors.white,
                  height: 1.5,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _send(String text) {
    if (text.trim().isEmpty) return;
    setState(() {
      _messages.add(_Msg(false, text));
      _controller.clear();
    });
    Future.delayed(const Duration(milliseconds: 800), () {
      if (mounted) {
        setState(() {
          _messages.add(_Msg(true, '根据您的偏好和消费习惯，推荐以下高性价比券：\n\n1. 星巴克 \$25 礼品卡 - 当前售价 \$21.25（8.5折），信用AAA\n2. Amazon \$100 购物券 - 当前售价 \$85（8.5折），信用AA\n\n这两张券的折扣率在同类中最优，且发行方信用等级高。'));
        });
      }
    });
  }
}

class _Msg {
  final bool isAi;
  final String text;
  _Msg(this.isAi, this.text);
}
