import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import '../models/category_model.dart';
import 'package:uuid/uuid.dart';
import '../l10n/app_localizations.dart';

class CategoryProvider extends ChangeNotifier {
  List<CategoryModel> _categories = [];
  late Box<CategoryModel> _categoryBox;

  // 카테고리 표시 순서 정의
  static const List<String> _categoryOrder = [
    'music',
    'ottVideo',
    'storageCloud',
    'telecomInternetTv',
    'lifestyle',
    'shoppingEcommerce',
    'programming',
    'collaborationOffice',
    'aiService',
    'other',
  ];

  List<CategoryModel> get categories {
    // 정의된 순서로 카테고리 정렬
    final sortedCategories = List<CategoryModel>.from(_categories);
    sortedCategories.sort((a, b) {
      final aIndex = _categoryOrder.indexOf(a.name);
      final bIndex = _categoryOrder.indexOf(b.name);

      // 순서 목록에 없는 카테고리는 맨 뒤로
      if (aIndex == -1) return 1;
      if (bIndex == -1) return -1;

      return aIndex.compareTo(bIndex);
    });

    return sortedCategories;
  }

  Future<void> init() async {
    _categoryBox = await Hive.openBox<CategoryModel>('categories');
    _categories = _categoryBox.values.toList();

    // 카테고리가 비어있으면 기본 카테고리 추가
    if (_categories.isEmpty) {
      await _initDefaultCategories();
    }

    notifyListeners();
  }

  // 기본 카테고리 초기화
  Future<void> _initDefaultCategories() async {
    final defaultCategories = [
      {'name': 'music', 'color': '#E91E63', 'icon': 'music_note'},
      {'name': 'ottVideo', 'color': '#9C27B0', 'icon': 'movie_filter'},
      {'name': 'storageCloud', 'color': '#2196F3', 'icon': 'cloud'},
      {'name': 'telecomInternetTv', 'color': '#00BCD4', 'icon': 'wifi'},
      {'name': 'lifestyle', 'color': '#4CAF50', 'icon': 'home'},
      {
        'name': 'shoppingEcommerce',
        'color': '#FF9800',
        'icon': 'shopping_cart'
      },
      {'name': 'programming', 'color': '#795548', 'icon': 'code'},
      {
        'name': 'collaborationOffice',
        'color': '#607D8B',
        'icon': 'business_center'
      },
      {'name': 'aiService', 'color': '#673AB7', 'icon': 'smart_toy'},
      {'name': 'other', 'color': '#9E9E9E', 'icon': 'category'},
    ];

    for (final category in defaultCategories) {
      final newCategory = CategoryModel(
        id: const Uuid().v4(),
        name: category['name']!,
        color: category['color']!,
        icon: category['icon']!,
      );

      await _categoryBox.put(newCategory.id, newCategory);
      _categories.add(newCategory);
    }
  }

  Future<void> addCategory({
    required String name,
    required String color,
    required String icon,
  }) async {
    final newCategory = CategoryModel(
      id: const Uuid().v4(),
      name: name,
      color: color,
      icon: icon,
    );
    await _categoryBox.put(newCategory.id, newCategory);
    _categories.add(newCategory);
    notifyListeners();
  }

  Future<void> updateCategory(CategoryModel updated) async {
    await _categoryBox.put(updated.id, updated);
    int index = _categories.indexWhere((cat) => cat.id == updated.id);
    if (index != -1) {
      _categories[index] = updated;
      notifyListeners();
    }
  }

  Future<void> deleteCategory(String id) async {
    await _categoryBox.delete(id);
    _categories.removeWhere((cat) => cat.id == id);
    notifyListeners();
  }

  CategoryModel? getCategoryById(String id) {
    try {
      return _categories.firstWhere((cat) => cat.id == id);
    } catch (_) {
      return null;
    }
  }

  // 카테고리 이름을 현재 언어에 맞게 반환
  String getLocalizedCategoryName(BuildContext context, String categoryKey) {
    final localizations = AppLocalizations.of(context);
    switch (categoryKey) {
      case 'music':
        return localizations.categoryMusic;
      case 'ottVideo':
        return localizations.categoryOttVideo;
      case 'storageCloud':
        return localizations.categoryStorageCloud;
      case 'telecomInternetTv':
        return localizations.categoryTelecomInternetTv;
      case 'lifestyle':
        return localizations.categoryLifestyle;
      case 'shoppingEcommerce':
        return localizations.categoryShoppingEcommerce;
      case 'programming':
        return localizations.categoryProgramming;
      case 'collaborationOffice':
        return localizations.categoryCollaborationOffice;
      case 'aiService':
        return localizations.categoryAiService;
      case 'other':
        return localizations.categoryOther;
      default:
        // 이전 버전과의 호환성을 위해 한국어 카테고리 이름도 처리
        switch (categoryKey) {
          case '음악':
            return localizations.categoryMusic;
          case 'OTT(동영상)':
            return localizations.categoryOttVideo;
          case '저장/클라우드':
            return localizations.categoryStorageCloud;
          case '통신 · 인터넷 · TV':
            return localizations.categoryTelecomInternetTv;
          case '생활/라이프스타일':
            return localizations.categoryLifestyle;
          case '쇼핑/이커머스':
            return localizations.categoryShoppingEcommerce;
          case '프로그래밍':
            return localizations.categoryProgramming;
          case '협업/오피스':
            return localizations.categoryCollaborationOffice;
          case 'AI 서비스':
            return localizations.categoryAiService;
          case '기타':
            return localizations.categoryOther;
          default:
            return categoryKey;
        }
    }
  }
}
