import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:window_manager/window_manager.dart';
import '../providers/price_provider.dart';
import '../providers/update_provider.dart';
import '../services/window_service.dart';
import '../widgets/price_chart.dart';
import '../widgets/alerts_panel.dart';
import '../widgets/vendor_table.dart';
import '../widgets/update_notification.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
    // Initialize providers and window service
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // Initialize window service with context
      await WindowService().initialize(context: context);
      
      context.read<UpdateProvider>().initialize();
      context.read<UpdateProvider>().startPeriodicChecks();
      
      // Listen to provider changes to update system tray
      _setupProviderListeners();
    });
  }

  void _setupProviderListeners() {
    // Listen to price provider for connection status
    context.read<PriceProvider>().addListener(_updateTrayStatus);

    // Listen to update provider for update notifications
    context.read<UpdateProvider>().addListener(_updateTrayMenu);
  }

  void _updateTrayStatus() {
    final priceProvider = context.read<PriceProvider>();
    WindowService().updateTrayTooltip(
      'AUEC Tracker - ${priceProvider.connectionStatus}'
    );
  }

  void _updateTrayMenu() {
    final updateProvider = context.read<UpdateProvider>();
    WindowService().updateTrayMenu(hasUpdate: updateProvider.hasUpdate);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0A0E27),
      body: Column(
        children: [
          // Custom title bar (desktop only)
          if (!kIsWeb && (Theme.of(context).platform == TargetPlatform.windows ||
              Theme.of(context).platform == TargetPlatform.macOS ||
              Theme.of(context).platform == TargetPlatform.linux))
            GestureDetector(
              onPanStart: (details) => windowManager.startDragging(),
              onDoubleTap: () => WindowService().maximizeWindow(),
              child: Container(
                height: 40,
                color: const Color(0xFF1A1F3A),
                child: Row(
                  children: [
                    const SizedBox(width: 16),
                    const Text(
                      'rmtPocketWatcher',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const Spacer(),
                    const Text(
                      'Lambda Banking Conglomerate',
                      style: TextStyle(
                        color: Color(0xFF888888),
                        fontSize: 12,
                      ),
                    ),
                    const SizedBox(width: 16),
                  // Update check button
                  Consumer<UpdateProvider>(
                    builder: (context, updateProvider, child) {
                      return IconButton(
                        icon: updateProvider.isChecking
                            ? const SizedBox(
                                width: 12,
                                height: 12,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  color: Color(0xFF50E3C2),
                                ),
                              )
                            : Icon(
                                updateProvider.hasUpdate ? Icons.system_update : Icons.refresh,
                                color: updateProvider.hasUpdate ? const Color(0xFF50E3C2) : Colors.white,
                                size: 16,
                              ),
                        onPressed: updateProvider.isChecking
                            ? null
                            : () => updateProvider.checkForUpdates(force: true),
                        tooltip: updateProvider.hasUpdate
                            ? 'Update available'
                            : 'Check for updates',
                      );
                    },
                  ),
                  // Minimize button (minimize to tray)
                  IconButton(
                    icon: const Icon(Icons.minimize, color: Colors.white, size: 16),
                    onPressed: () => WindowService().minimizeToTray(),
                    tooltip: 'Minimize to system tray',
                  ),
                  // Maximize/Restore button
                  FutureBuilder<bool>(
                    future: windowManager.isMaximized(),
                    builder: (context, snapshot) {
                      bool isMaximized = snapshot.data ?? false;
                      return IconButton(
                        icon: Icon(
                          isMaximized ? Icons.fullscreen_exit : Icons.fullscreen,
                          color: Colors.white,
                          size: 16,
                        ),
                        onPressed: () => WindowService().maximizeWindow(),
                        tooltip: isMaximized ? 'Restore window' : 'Maximize window',
                      );
                    },
                  ),
                  // Close button (exit app)
                  IconButton(
                    icon: const Icon(Icons.close, color: Colors.white, size: 16),
                    onPressed: () => WindowService().closeWindow(),
                    tooltip: 'Exit application',
                  ),
                ],
              ),
            ),
          ),
          // Main content
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // Update notification banner
                  const UpdateNotificationBanner(),
                  // Top stats row - Bloomberg style
                  Consumer<PriceProvider>(
                    builder: (context, provider, child) {
                      return Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: const Color(0xFF1A1F3A),
                          borderRadius: BorderRadius.circular(4),
                          border: Border.all(color: const Color(0xFF50E3C2), width: 1),
                        ),
                        child: MediaQuery.of(context).size.width > 600
                          ? Row(
                              children: [
                                // Connection status
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const Text(
                                        'CONNECTION',
                                        style: TextStyle(
                                          color: Color(0xFF888888),
                                          fontSize: 11,
                                          fontWeight: FontWeight.bold,
                                          letterSpacing: 1.2,
                                        ),
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        provider.connectionStatus == 'Connected' ? 'CONNECTED' : provider.connectionStatus.toUpperCase(),
                                        style: TextStyle(
                                          color: provider.connectionStatus == 'Connected'
                                              ? const Color(0xFF50E3C2)
                                              : const Color(0xFFFF6B9D),
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                          fontFamily: 'monospace',
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                if (provider.latestPrice != null) ...[
                                  // Lowest price
                                  Expanded(
                                    flex: 2,
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        const Text(
                                          'LOWEST PRICE',
                                          style: TextStyle(
                                            color: Color(0xFF888888),
                                            fontSize: 11,
                                            fontWeight: FontWeight.bold,
                                            letterSpacing: 1.2,
                                          ),
                                        ),
                                        const SizedBox(height: 4),
                                        Text(
                                          provider.latestPrice!.lowestPrice >= 1 
                                            ? '\$${provider.latestPrice!.lowestPrice.toStringAsFixed(2)}'
                                            : provider.latestPrice!.lowestPrice >= 0.01
                                            ? '\$${provider.latestPrice!.lowestPrice.toStringAsFixed(4)}'
                                            : provider.latestPrice!.lowestPrice >= 0.0001
                                            ? '\$${provider.latestPrice!.lowestPrice.toStringAsFixed(6)}'
                                            : '\$${provider.latestPrice!.lowestPrice.toStringAsFixed(8)}', // Use more decimal places instead of scientific notation
                                          style: const TextStyle(
                                            color: Color(0xFF50E3C2),
                                            fontSize: 18, // Reduced from 20
                                            fontWeight: FontWeight.bold,
                                            fontFamily: 'monospace',
                                          ),
                                        ),
                                        const Text(
                                          'per 1M AUEC',
                                          style: TextStyle(
                                            color: Color(0xFF888888),
                                            fontSize: 10,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  // Seller info
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        const Text(
                                          'SELLER',
                                          style: TextStyle(
                                            color: Color(0xFF888888),
                                            fontSize: 11,
                                            fontWeight: FontWeight.bold,
                                            letterSpacing: 1.2,
                                          ),
                                        ),
                                        const SizedBox(height: 4),
                                        Text(
                                          provider.latestPrice!.sellerName,
                                          style: const TextStyle(
                                            color: Colors.white,
                                            fontSize: 16,
                                            fontWeight: FontWeight.bold,
                                            fontFamily: 'monospace',
                                          ),
                                        ),
                                        Text(
                                          provider.latestPrice!.platform,
                                          style: const TextStyle(
                                            color: Color(0xFF888888),
                                            fontSize: 10,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ],
                            )
                          : Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: [
                                // Connection status (mobile)
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const Text(
                                      'CONNECTION',
                                      style: TextStyle(
                                        color: Color(0xFF888888),
                                        fontSize: 11,
                                        fontWeight: FontWeight.bold,
                                        letterSpacing: 1.2,
                                      ),
                                    ),
                                    const SizedBox(height: 4),
                                    Text(
                                      provider.connectionStatus == 'Connected' ? 'CONNECTED' : provider.connectionStatus.toUpperCase(),
                                      style: TextStyle(
                                        color: provider.connectionStatus == 'Connected'
                                            ? const Color(0xFF50E3C2)
                                            : const Color(0xFFFF6B9D),
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                        fontFamily: 'monospace',
                                      ),
                                    ),
                                  ],
                                ),
                                if (provider.latestPrice != null) ...[
                                  const SizedBox(height: 16),
                                  // Lowest price (mobile)
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const Text(
                                        'LOWEST PRICE',
                                        style: TextStyle(
                                          color: Color(0xFF888888),
                                          fontSize: 11,
                                          fontWeight: FontWeight.bold,
                                          letterSpacing: 1.2,
                                        ),
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        provider.latestPrice!.lowestPrice >= 1 
                                          ? '\$${provider.latestPrice!.lowestPrice.toStringAsFixed(2)}'
                                          : provider.latestPrice!.lowestPrice >= 0.01
                                          ? '\$${provider.latestPrice!.lowestPrice.toStringAsFixed(4)}'
                                          : provider.latestPrice!.lowestPrice >= 0.0001
                                          ? '\$${provider.latestPrice!.lowestPrice.toStringAsFixed(6)}'
                                          : '\$${provider.latestPrice!.lowestPrice.toStringAsFixed(8)}',
                                        style: const TextStyle(
                                          color: Color(0xFF50E3C2),
                                          fontSize: 18,
                                          fontWeight: FontWeight.bold,
                                          fontFamily: 'monospace',
                                        ),
                                      ),
                                      const Text(
                                        'per 1M AUEC',
                                        style: TextStyle(
                                          color: Color(0xFF888888),
                                          fontSize: 10,
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 16),
                                  // Seller info (mobile)
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const Text(
                                        'SELLER',
                                        style: TextStyle(
                                          color: Color(0xFF888888),
                                          fontSize: 11,
                                          fontWeight: FontWeight.bold,
                                          letterSpacing: 1.2,
                                        ),
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        provider.latestPrice!.sellerName,
                                        style: const TextStyle(
                                          color: Colors.white,
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                          fontFamily: 'monospace',
                                        ),
                                      ),
                                      Text(
                                        provider.latestPrice!.platform,
                                        style: const TextStyle(
                                          color: Color(0xFF888888),
                                          fontSize: 10,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ],
                            )
                      );
                    },
                  ),
                  const SizedBox(height: 16),
                  // Price Alerts section
                  const AlertsPanel(),
                  const SizedBox(height: 16),
                  // Price History Chart
                  const PriceChart(),
                  const SizedBox(height: 16),
                  // Current Listings table
                  const VendorTable(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}