import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xp_models/xp_models.dart';
import '../services/dashboard_provider.dart';
import '../widgets/stats_header.dart';
import '../widgets/progress_card.dart';
import '../widgets/xp_chart.dart';
import '../widgets/recent_activity_card.dart';
import '../widgets/xp_breakdown_card.dart';
import '../widgets/achievements_card.dart';
import '../widgets/config_card.dart';
import '../widgets/classification_card.dart';
import '../widgets/logs_card.dart';

class DashboardScreen extends StatefulWidget {
  const DashboardScreen({super.key});

  @override
  State<DashboardScreen> createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<DashboardProvider>().initialize();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('🎮 XP Nix Dashboard'),
        actions: [
          Consumer<DashboardProvider>(
            builder: (context, provider, child) {
              return Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // WebSocket connection indicator
                  Container(
                    width: 12,
                    height: 12,
                    margin: const EdgeInsets.only(right: 8),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: provider.isWebSocketConnected
                          ? Colors.green
                          : Colors.red,
                    ),
                  ),
                  Text(
                    provider.isWebSocketConnected ? 'Live' : 'Offline',
                    style: Theme.of(context).textTheme.bodySmall?.copyWith(
                      color: Colors.white70,
                    ),
                  ),
                  const SizedBox(width: 16),
                  // Refresh button
                  IconButton(
                    icon: provider.isLoading
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          )
                        : const Icon(Icons.refresh),
                    onPressed: provider.isLoading
                        ? null
                        : () => provider.refresh(),
                    tooltip: 'Refresh Dashboard',
                  ),
                ],
              );
            },
          ),
        ],
      ),
      body: Consumer<DashboardProvider>(
        builder: (context, provider, child) {
          if (provider.isLoading && provider.stats == null) {
            return const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text('Loading dashboard...'),
                ],
              ),
            );
          }

          if (provider.error != null && provider.stats == null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.error_outline,
                    size: 64,
                    color: Colors.red,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    'Failed to load dashboard',
                    style: Theme.of(context).textTheme.headlineSmall,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    provider.error!,
                    style: Theme.of(context).textTheme.bodyMedium,
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => provider.refresh(),
                    child: const Text('Retry'),
                  ),
                ],
              ),
            );
          }

          return RefreshIndicator(
            onRefresh: () => provider.refresh(),
            child: SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Stats Header
                  StatsHeader(stats: provider.stats),
                  const SizedBox(height: 24),
                  
                  // Dashboard Grid
                  LayoutBuilder(
                    builder: (context, constraints) {
                      final isWide = constraints.maxWidth > 1200;
                      final isMedium = constraints.maxWidth > 800;
                      
                      if (isWide) {
                        return _buildWideLayout(provider);
                      } else if (isMedium) {
                        return _buildMediumLayout(provider);
                      } else {
                        return _buildNarrowLayout(provider);
                      }
                    },
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildWideLayout(DashboardProvider provider) {
    return Column(
      children: [
        // First row: Progress, Chart, Recent Activity
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 1,
              child: ProgressCard(stats: provider.stats),
            ),
            const SizedBox(width: 16),
            Expanded(
              flex: 2,
              child: XPChart(history: provider.statsHistory),
            ),
            const SizedBox(width: 16),
            Expanded(
              flex: 1,
              child: RecentActivityCard(activities: provider.stats?.recentActivity ?? []),
            ),
          ],
        ),
        const SizedBox(height: 16),
        
        // Second row: XP Breakdown, Achievements
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 1,
              child: XPBreakdownCard(breakdown: provider.xpBreakdown),
            ),
            const SizedBox(width: 16),
            Expanded(
              flex: 1,
              child: AchievementsCard(achievements: provider.achievements),
            ),
          ],
        ),
        const SizedBox(height: 16),
        
        // Third row: Config, Classifications, Logs
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 1,
              child: ConfigCard(
                config: provider.config,
                onConfigUpdate: provider.updateConfig,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              flex: 1,
              child: ClassificationCard(
                classifications: provider.classifications,
                unclassified: provider.unclassified,
                onSaveClassification: provider.saveClassification,
                onDeleteClassification: provider.deleteClassification,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              flex: 1,
              child: LogsCard(
                logs: provider.logs,
                onRefresh: provider.loadLogs,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildMediumLayout(DashboardProvider provider) {
    return Column(
      children: [
        // First row: Progress, Chart
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 1,
              child: ProgressCard(stats: provider.stats),
            ),
            const SizedBox(width: 16),
            Expanded(
              flex: 2,
              child: XPChart(history: provider.statsHistory),
            ),
          ],
        ),
        const SizedBox(height: 16),
        
        // Second row: Recent Activity, XP Breakdown
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: RecentActivityCard(activities: provider.stats?.recentActivity ?? []),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: XPBreakdownCard(breakdown: provider.xpBreakdown),
            ),
          ],
        ),
        const SizedBox(height: 16),
        
        // Third row: Achievements, Config
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: AchievementsCard(achievements: provider.achievements),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: ConfigCard(
                config: provider.config,
                onConfigUpdate: provider.updateConfig,
              ),
            ),
          ],
        ),
        const SizedBox(height: 16),
        
        // Fourth row: Classifications, Logs
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: ClassificationCard(
                classifications: provider.classifications,
                unclassified: provider.unclassified,
                onSaveClassification: provider.saveClassification,
                onDeleteClassification: provider.deleteClassification,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: LogsCard(
                logs: provider.logs,
                onRefresh: provider.loadLogs,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildNarrowLayout(DashboardProvider provider) {
    return Column(
      children: [
        ProgressCard(stats: provider.stats),
        const SizedBox(height: 16),
        XPChart(history: provider.statsHistory),
        const SizedBox(height: 16),
        RecentActivityCard(activities: provider.stats?.recentActivity ?? []),
        const SizedBox(height: 16),
        XPBreakdownCard(breakdown: provider.xpBreakdown),
        const SizedBox(height: 16),
        AchievementsCard(achievements: provider.achievements),
        const SizedBox(height: 16),
        ConfigCard(
          config: provider.config,
          onConfigUpdate: provider.updateConfig,
        ),
        const SizedBox(height: 16),
        ClassificationCard(
          classifications: provider.classifications,
          unclassified: provider.unclassified,
          onSaveClassification: provider.saveClassification,
          onDeleteClassification: provider.deleteClassification,
        ),
        const SizedBox(height: 16),
        LogsCard(
          logs: provider.logs,
          onRefresh: provider.loadLogs,
        ),
      ],
    );
  }
}
