import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:provider/provider.dart';
import '../../../data/models/coin.dart';
import '../../../providers/market_provider.dart';

/// 行情页面 - 使用 shadcn_ui 现代化设计
class MarketPage extends StatefulWidget {
  const MarketPage({super.key});

  @override
  State<MarketPage> createState() => _MarketPageState();
}

class _MarketPageState extends State<MarketPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  final _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<MarketProvider>().loadCoins();
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final theme = ShadTheme.of(context);

    return Scaffold(
      backgroundColor: theme.colorScheme.background,
      body: Consumer<MarketProvider>(
        builder: (context, provider, _) {
          return Column(
            children: [
              _buildSearchBar(provider),
              _buildTabs(provider),
              Expanded(
                child: _buildCoinList(provider),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildSearchBar(MarketProvider provider) {
    final theme = ShadTheme.of(context);

    return Padding(
      padding: const EdgeInsets.all(16),
      child: ShadInput(
        controller: _searchController,
        placeholder: const Text('搜索币种...'),
        leading: Icon(
          LucideIcons.search,
          size: 18,
          color: theme.colorScheme.mutedForeground,
        ),
        trailing: _searchController.text.isNotEmpty
            ? GestureDetector(
                onTap: () {
                  _searchController.clear();
                  provider.clearSearch();
                },
                child: Icon(
                  LucideIcons.x,
                  size: 18,
                  color: theme.colorScheme.mutedForeground,
                ),
              )
            : null,
        onChanged: provider.search,
      ),
    );
  }

  Widget _buildTabs(MarketProvider provider) {
    final theme = ShadTheme.of(context);

    final tabs = [
      {'key': 'all', 'label': '全部'},
      {'key': 'realtime', 'label': '实时'},
      {'key': 'hot', 'label': '热门'},
    ];

    return Container(
      height: 44,
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: tabs.asMap().entries.map((entry) {
          final index = entry.key;
          final tab = entry.value;
          final isActive = provider.activeTab == tab['key'];

          return GestureDetector(
            onTap: () => provider.setTab(tab['key']!),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              margin: const EdgeInsets.only(right: 8),
              decoration: BoxDecoration(
                color: isActive
                    ? theme.colorScheme.primary
                    : theme.colorScheme.card,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Text(
                tab['label']!,
                style: TextStyle(
                  color: isActive
                      ? Colors.white
                      : theme.colorScheme.mutedForeground,
                  fontWeight: isActive ? FontWeight.w600 : FontWeight.normal,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildCoinList(MarketProvider provider) {
    final theme = ShadTheme.of(context);

    if (provider.isLoading) {
      return Center(
        child: CircularProgressIndicator(
          color: theme.colorScheme.primary,
        ),
      );
    }

    if (provider.error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              LucideIcons.circleAlert,
              size: 48,
              color: theme.colorScheme.destructive,
            ),
            const SizedBox(height: 12),
            Text(
              provider.error!,
              style: TextStyle(color: theme.colorScheme.destructive),
            ),
            const SizedBox(height: 16),
            ShadButton(
              onPressed: provider.loadCoins,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    final coins = provider.coins;
    if (coins.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              LucideIcons.coins,
              size: 48,
              color: theme.colorScheme.mutedForeground,
            ),
            const SizedBox(height: 12),
            Text(
              '暂无数据',
              style: theme.textTheme.muted,
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: provider.refresh,
      color: theme.colorScheme.primary,
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: coins.length,
        itemBuilder: (context, index) => _buildCoinItem(coins[index]),
      ),
    );
  }

  Widget _buildCoinItem(Coin coin) {
    final theme = ShadTheme.of(context);
    final upColor = const Color(0xFF00C853);
    final downColor = const Color(0xFFFF5252);

    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: ShadCard(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            // 图标
            CircleAvatar(
              radius: 22,
              backgroundColor: theme.colorScheme.primary.withValues(alpha: 0.1),
              child: Text(
                coin.displayIcon,
                style: TextStyle(
                  fontSize: 20,
                  color: theme.colorScheme.primary,
                ),
              ),
            ),
            const SizedBox(width: 12),
            // 名称
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '${coin.code}/USDT',
                    style: theme.textTheme.large.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    coin.name,
                    style: theme.textTheme.muted,
                  ),
                ],
              ),
            ),
            // 涨跌幅
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              decoration: BoxDecoration(
                color: coin.isUp ? upColor.withValues(alpha: 0.2) : downColor.withValues(alpha: 0.2),
                borderRadius: BorderRadius.circular(6),
              ),
              child: Text(
                coin.formattedChange,
                style: TextStyle(
                  color: coin.isUp ? upColor : downColor,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
