import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import 'models/store.dart';
import 'models/channel.dart';

// Legacy compatibility
class SiteConfig {
  final String id;
  final String name;
  final String url;
  final String consumerKey;
  final String consumerSecret;

  SiteConfig({required this.id, required this.name, required this.url, required this.consumerKey, required this.consumerSecret});
  
  factory SiteConfig.fromJson(Map<String, dynamic> json) => SiteConfig(
        id: json['id'],
        name: json['name'],
        url: json['url'],
        consumerKey: json['consumerKey'],
        consumerSecret: json['consumerSecret'],
      );
}

class ProfileManager with ChangeNotifier {
  bool _isAuthenticated = false;
  bool _hasPin = false;
  List<Store> _stores = [];

  bool get isAuthenticated => _isAuthenticated;
  bool get hasPin => _hasPin;
  List<Store> get stores => _stores;

  ProfileManager() {
    _init();
  }

  Future<void> _init() async {
    final prefs = await SharedPreferences.getInstance();
    _hasPin = prefs.containsKey('app_pin');
    
    // Migration: Check for legacy sites
    if (prefs.containsKey('saved_sites')) {
        final sitesJson = prefs.getStringList('saved_sites') ?? [];
        for (var s in sitesJson) {
            try {
                final site = SiteConfig.fromJson(jsonDecode(s));
                // Convert to Store
                final newStore = Store(
                    id: const Uuid().v4(),
                    name: site.name,
                    channels: [
                        WooCommerceChannel(
                            id: const Uuid().v4(), 
                            name: 'WooCommerce', 
                            url: site.url, 
                            consumerKey: site.consumerKey, 
                            consumerSecret: site.consumerSecret
                        )
                    ]
                );
                _stores.add(newStore);
            } catch (e) {
                print('Error migrating site: $e');
            }
        }
        // Save new format
        await _saveStores();
        // Remove old format (or keep as backup? Remove to avoid re-migration)
        await prefs.remove('saved_sites');
    } else {
        // Load Stores
        final storesJson = prefs.getStringList('saved_stores') ?? [];
        _stores = storesJson.map((s) => Store.fromJson(jsonDecode(s))).toList();
    }
    
    notifyListeners();
  }

  Future<void> setPin(String pin) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('app_pin', pin);
    _hasPin = true;
    _isAuthenticated = true; 
    notifyListeners();
  }

  Future<bool> unlock(String pin) async {
    final prefs = await SharedPreferences.getInstance();
    final storedPin = prefs.getString('app_pin');
    if (storedPin == pin) {
      _isAuthenticated = true;
      notifyListeners();
      return true;
    }
    return false;
  }

  Future<void> addStore(String name, WooCommerceChannel channel) async {
      final store = Store(
          id: const Uuid().v4(),
          name: name,
          channels: [channel]
      );
      _stores.add(store);
      await _saveStores();
      notifyListeners();
  }

  Future<void> removeStore(String id) async {
    _stores.removeWhere((s) => s.id == id);
    await _saveStores();
    notifyListeners();
  }

  Future<void> _saveStores() async {
    final prefs = await SharedPreferences.getInstance();
    final storesJson = _stores.map((s) => jsonEncode(s.toJson())).toList();
    await prefs.setStringList('saved_stores', storesJson);
  }

  Future<void> updateStore(String id, String name, WooCommerceChannel channel) async {
      final index = _stores.indexWhere((s) => s.id == id);
      if (index != -1) {
          _stores[index] = Store(
              id: id,
              name: name,
              channels: [channel] // Replace channel list for now (assuming 1 channel)
          );
          await _saveStores();
          notifyListeners();
      }
  }

  void logout() {
    _isAuthenticated = false;
    notifyListeners();
  }
}
