import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:provider/provider.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../../core/theme/app_color_scheme.dart';
import '../../../core/theme/app_spacing.dart';
import '../../../data/models/coin.dart';
import '../../../providers/market_provider.dart';
import '../../components/glass_panel.dart';

/// 行情页面 - Material Design 3 风格
class MarketPage extends StatefulWidget {
  const MarketPage({super.key});

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

class _MarketPageState extends State<MarketPage> with AutomaticKeepAliveClientMixin {
  final _searchController = TextEditingController();

  @override
  bool get wantKeepAlive => true;

  @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 colorScheme = Theme.of(context).colorScheme;
    final isDark = Theme.of(context).brightness == Brightness.dark;

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

  Widget _buildSearchBar(MarketProvider provider, ColorScheme colorScheme) {
    return Padding(
      padding: EdgeInsets.fromLTRB(AppSpacing.md, AppSpacing.md, AppSpacing.md, 0),
      child: Container(
        decoration: BoxDecoration(
          color: colorScheme.surfaceContainerLowest,
          borderRadius: BorderRadius.circular(AppRadius.xl),
          border: Border.all(
            color: colorScheme.outlineVariant.withOpacity(0.15),
          ),
        ),
        child: TextField(
          controller: _searchController,
          onChanged: provider.search,
          style: TextStyle(color: colorScheme.onSurface),
          decoration: InputDecoration(
            hintText: '搜索市场...',
            hintStyle: TextStyle(color: colorScheme.onSurfaceVariant),
            prefixIcon: Icon(
              LucideIcons.search,
              size: 18,
              color: colorScheme.onSurfaceVariant,
            ),
            suffixIcon: _searchController.text.isNotEmpty
                ? GestureDetector(
                    onTap: () {
                      _searchController.clear();
                      provider.clearSearch();
                    },
                    child: Icon(
                      LucideIcons.x,
                      size: 18,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  )
                : null,
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(
              horizontal: AppSpacing.md,
              vertical: AppSpacing.md + AppSpacing.xs,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTabs(MarketProvider provider, ColorScheme colorScheme, bool isDark) {
    final tabs = [
      {'key': 'all', 'label': '全部'},
      {'key': 'realtime', 'label': '实时'},
      {'key': 'hot', 'label': '热门'},
    ];

    return Container(
      height: 48,
      margin: EdgeInsets.fromLTRB(AppSpacing.md, AppSpacing.md, AppSpacing.md, 0),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: tabs.map((tab) {
            final isActive = provider.activeTab == tab['key'];

            return GestureDetector(
              onTap: () => provider.setTab(tab['key']!),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                margin: EdgeInsets.only(right: AppSpacing.sm),
                padding: EdgeInsets.symmetric(
                  horizontal: AppSpacing.lg,
                  vertical: AppSpacing.sm + AppSpacing.xs,
                ),
                decoration: BoxDecoration(
                  color: isActive
                      ? colorScheme.primary.withOpacity(0.1)
                      : colorScheme.surfaceContainerHigh,
                  borderRadius: BorderRadius.circular(AppRadius.full),
                  border: isActive
                      ? Border.all(
                          color: colorScheme.primary.withOpacity(0.2),
                        )
                      : null,
                  boxShadow: isActive
                      ? [
                          BoxShadow(
                            color: colorScheme.primary.withOpacity(isDark ? 0.15 : 0.08),
                            blurRadius: 15,
                          ),
                        ]
                      : null,
                ),
                child: Text(
                  tab['label']!,
                  style: TextStyle(
                    color: isActive
                        ? colorScheme.primary
                        : colorScheme.onSurfaceVariant,
                    fontWeight: isActive ? FontWeight.w700 : FontWeight.normal,
                    fontSize: 12,
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }

  Widget _buildCoinList(MarketProvider provider, ColorScheme colorScheme, bool isDark) {
    if (provider.isLoading) {
      return Center(
        child: CircularProgressIndicator(
          color: colorScheme.primary,
        ),
      );
    }

    if (provider.error != null) {
      return _buildErrorState(provider, colorScheme);
    }

    final coins = provider.coins;
    if (coins.isEmpty) {
      return _buildEmptyState(colorScheme);
    }

    return RefreshIndicator(
      onRefresh: provider.refresh,
      color: colorScheme.primary,
      backgroundColor: colorScheme.surfaceContainer,
      child: ListView.builder(
        padding: EdgeInsets.all(AppSpacing.md),
        itemCount: coins.length,
        itemBuilder: (context, index) => _buildCoinItem(coins[index], colorScheme),
      ),
    );
  }

  Widget _buildErrorState(MarketProvider provider, ColorScheme colorScheme) {
    return Center(
      child: Padding(
        padding: AppSpacing.pagePadding,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              LucideIcons.circleAlert,
              size: 48,
              color: colorScheme.error,
            ),
            SizedBox(height: AppSpacing.md),
            Text(
              provider.error!,
              style: TextStyle(color: colorScheme.error),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: AppSpacing.lg),
            ShadButton(
              onPressed: provider.loadCoins,
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState(ColorScheme colorScheme) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            LucideIcons.coins,
            size: 48,
            color: colorScheme.onSurfaceVariant,
          ),
          SizedBox(height: AppSpacing.md),
          Text(
            '暂无数据',
            style: TextStyle(color: colorScheme.onSurfaceVariant),
          ),
        ],
      ),
    );
  }

  Widget _buildCoinItem(Coin coin, ColorScheme colorScheme) {
    final changeColor = coin.isUp ? AppColorScheme.up : AppColorScheme.down;
    final changeBgColor = coin.isUp
        ? AppColorScheme.up.withOpacity(0.1)
        : colorScheme.error.withOpacity(0.1);

    return GlassCard(
      margin: EdgeInsets.only(bottom: AppSpacing.sm),
      child: Row(
        children: [
          // 图标容器
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: colorScheme.surfaceContainerHighest,
              borderRadius: BorderRadius.circular(AppRadius.xl),
              border: Border.all(
                color: colorScheme.outlineVariant.withOpacity(0.2),
              ),
            ),
            child: Center(
              child: Text(
                coin.displayIcon,
                style: TextStyle(
                  fontSize: 20,
                  color: coin.isUp ? colorScheme.primary : colorScheme.secondary,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          SizedBox(width: AppSpacing.sm + AppSpacing.xs),
          // 币种信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      coin.code,
                      style: GoogleFonts.spaceGrotesk(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: colorScheme.onSurface,
                      ),
                    ),
                    SizedBox(width: AppSpacing.xs),
                    Text(
                      '/USDT',
                      style: TextStyle(
                        fontSize: 12,
                        color: colorScheme.onSurfaceVariant,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: AppSpacing.xs / 2),
                Text(
                  coin.name,
                  style: TextStyle(
                    fontSize: 12,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          ),
          // 价格和涨跌幅
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                '\$${coin.formattedPrice}',
                style: GoogleFonts.spaceGrotesk(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  color: colorScheme.onSurface,
                ),
              ),
              SizedBox(height: AppSpacing.xs),
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: AppSpacing.sm,
                  vertical: AppSpacing.xs,
                ),
                decoration: BoxDecoration(
                  color: changeBgColor,
                  borderRadius: BorderRadius.circular(AppRadius.sm),
                  border: Border.all(
                    color: changeColor.withOpacity(0.2),
                  ),
                ),
                child: Text(
                  coin.formattedChange,
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w700,
                    color: changeColor,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
