import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import '../theme/dynamic_color_scheme.dart';

class DynamicThemeProvider extends ChangeNotifier {
  ColorScheme? _dynamicColorScheme;
  List<Color> _logoColors = [];
  bool _isUsingDynamicTheme = false;
  bool _isLoading = false;

  // Manual override
  bool _useManualOverride = false;
  Color? _manualPrimary;
  Color? _manualSecondary;
  Color? _manualTertiary;

  // Getters
  ColorScheme? get dynamicColorScheme => _dynamicColorScheme;
  List<Color> get logoColors => _logoColors;
  bool get isUsingDynamicTheme => _isUsingDynamicTheme;
  bool get isLoading => _isLoading;
  bool get useManualOverride => _useManualOverride;
  Color? get manualPrimary => _manualPrimary;
  Color? get manualSecondary => _manualSecondary;
  Color? get manualTertiary => _manualTertiary;

  // Set loading state
  set isLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  // Generate dynamic theme from logo
  Future<void> generateThemeFromLogo(Uint8List logoBytes) async {
    try {
      print("DynamicThemeProvider.generateThemeFromLogo called");
      print("Logo bytes length: ${logoBytes.length}");

      isLoading = true;

      // Extract colors with lightweight, downscaled palette to avoid jank
      print("Extracting colors from logo (lite in main isolate)...");
      final colors =
          await DynamicColorScheme.extractColorsFromBytesLite(logoBytes);

      print("Colors extracted: ${colors.length}");
      _logoColors = colors;

      // Generate light theme
      print("Generating light theme...");
      final lightTheme =
          DynamicColorScheme.generateDynamicColorScheme(colors, isDark: false);

      // Generate dark theme
      print("Generating dark theme...");
      final darkTheme =
          DynamicColorScheme.generateDynamicColorScheme(colors, isDark: true);

      // Store the dynamic color scheme
      _dynamicColorScheme = lightTheme;
      _isUsingDynamicTheme = true;

      print('Dynamic theme generated with ${colors.length} colors');
      print('Primary: ${colors.isNotEmpty ? colors[0] : 'N/A'}');
      print('Secondary: ${colors.length > 1 ? colors[1] : 'N/A'}');
      print('Tertiary: ${colors.length > 2 ? colors[2] : 'N/A'}');
      print('_isUsingDynamicTheme set to: $_isUsingDynamicTheme');

      isLoading = false;
      print("Notifying listeners...");
      notifyListeners();
      print("Listeners notified!");
    } catch (e) {
      print('Error generating dynamic theme: $e');
      isLoading = false;
      // Fallback to default theme
      _isUsingDynamicTheme = false;
      _dynamicColorScheme = null;
      notifyListeners();
    }
  }

  // Get current color scheme (dynamic or default)
  ColorScheme getCurrentColorScheme(bool isDark) {
    // Manual overrides take highest precedence
    if (_useManualOverride && (_manualPrimary != null)) {
      final base = [
        _manualPrimary!,
        _manualSecondary ?? _manualPrimary!,
        _manualTertiary ?? (_manualSecondary ?? _manualPrimary!)
      ];
      return DynamicColorScheme.generateDynamicColorScheme(base,
          isDark: isDark);
    }

    if (_isUsingDynamicTheme && _dynamicColorScheme != null) {
      // Return dynamic theme with appropriate brightness
      if (isDark) {
        return DynamicColorScheme.generateDynamicColorScheme(_logoColors,
            isDark: true);
      } else {
        return _dynamicColorScheme!;
      }
    } else {
      // Return default theme
      return DynamicColorScheme.generateDynamicColorScheme([], isDark: isDark);
    }
  }

  // Get gradient colors for UI elements
  List<Color> getGradientColors() {
    if (_useManualOverride && _manualPrimary != null) {
      return DynamicColorScheme.generateGradientColors([
        _manualPrimary!,
        _manualSecondary ?? _manualPrimary!,
        _manualTertiary ?? (_manualSecondary ?? _manualPrimary!)
      ]);
    }
    if (_isUsingDynamicTheme && _logoColors.isNotEmpty) {
      return DynamicColorScheme.generateGradientColors(_logoColors);
    } else {
      return DynamicColorScheme.generateGradientColors([]);
    }
  }

  // Get accent colors for semantic elements
  Map<String, Color> getAccentColors() {
    if (_useManualOverride && _manualPrimary != null) {
      return DynamicColorScheme.generateAccentColors([
        _manualPrimary!,
        _manualSecondary ?? _manualPrimary!,
        _manualTertiary ?? (_manualSecondary ?? _manualPrimary!)
      ]);
    }
    if (_isUsingDynamicTheme && _logoColors.isNotEmpty) {
      return DynamicColorScheme.generateAccentColors(_logoColors);
    } else {
      return DynamicColorScheme.generateAccentColors([]);
    }
  }

  // Reset to default theme
  void resetToDefaultTheme() {
    _isUsingDynamicTheme = false;
    _dynamicColorScheme = null;
    _logoColors = [];
    _useManualOverride = false;
    _manualPrimary = null;
    _manualSecondary = null;
    _manualTertiary = null;
    notifyListeners();
  }

  // Enable manual override with provided colors (hex or Color)
  void enableManualOverride(
      {Color? primary, Color? secondary, Color? tertiary}) {
    _useManualOverride = true;
    if (primary != null) _manualPrimary = primary;
    if (secondary != null) _manualSecondary = secondary;
    if (tertiary != null) _manualTertiary = tertiary;
    notifyListeners();
  }

  // Disable manual override
  void disableManualOverride() {
    _useManualOverride = false;
    notifyListeners();
  }

  // Update manual colors
  void setManualColors({Color? primary, Color? secondary, Color? tertiary}) {
    if (primary != null) _manualPrimary = primary;
    if (secondary != null) _manualSecondary = secondary;
    if (tertiary != null) _manualTertiary = tertiary;
    // Ensure override is on when user sets colors
    _useManualOverride = true;
    notifyListeners();
  }

  // Check if logo has specific color characteristics
  bool hasWarmColors() {
    if (_logoColors.isEmpty) return false;

    for (final color in _logoColors) {
      final hsl = HSLColor.fromColor(color);
      // Warm colors: red, orange, yellow (0-60 degrees)
      if (hsl.hue >= 0 && hsl.hue <= 60) {
        return true;
      }
    }
    return false;
  }

  bool hasCoolColors() {
    if (_logoColors.isEmpty) return false;

    for (final color in _logoColors) {
      final hsl = HSLColor.fromColor(color);
      // Cool colors: blue, green, purple (120-300 degrees)
      if (hsl.hue >= 120 && hsl.hue <= 300) {
        return true;
      }
    }
    return false;
  }

  bool hasNeutralColors() {
    if (_logoColors.isEmpty) return false;

    for (final color in _logoColors) {
      final hsl = HSLColor.fromColor(color);
      // Neutral colors: low saturation
      if (hsl.saturation < 0.3) {
        return true;
      }
    }
    return false;
  }

  // Get theme description
  String getThemeDescription() {
    if (!_isUsingDynamicTheme) {
      return 'Default Theme';
    }

    List<String> characteristics = [];

    if (hasWarmColors()) characteristics.add('Warm');
    if (hasCoolColors()) characteristics.add('Cool');
    if (hasNeutralColors()) characteristics.add('Neutral');

    if (characteristics.isEmpty) {
      characteristics.add('Dynamic');
    }

    return '${characteristics.join(', ')} Theme';
  }

  // Get color palette info
  Map<String, dynamic> getColorPaletteInfo() {
    if (_logoColors.isEmpty) {
      return {
        'primary': null,
        'secondary': null,
        'tertiary': null,
        'totalColors': 0,
        'description': 'No logo colors available',
      };
    }

    return {
      'primary': _logoColors.isNotEmpty ? _logoColors[0] : null,
      'secondary': _logoColors.length > 1 ? _logoColors[1] : null,
      'tertiary': _logoColors.length > 2 ? _logoColors[2] : null,
      'totalColors': _logoColors.length,
      'description': 'Generated from uploaded logo',
      'characteristics': {
        'warm': hasWarmColors(),
        'cool': hasCoolColors(),
        'neutral': hasNeutralColors(),
      },
    };
  }
}
