import 'package:get/get.dart';
import 'package:gifunavi/model/entry.dart';
import 'package:gifunavi/pages/index/index_controller.dart';
import 'package:gifunavi/pages/destination/destination_controller.dart';
import 'package:gifunavi/services/api_service.dart';
import 'package:flutter/material.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;

class EventEntriesController extends GetxController {
  final ApiService _apiService = Get.find<ApiService>();
  final IndexController _indexController = Get.find<IndexController>();
  late final DestinationController _destinationController;

  final entries = <Entry>[].obs;
  final filteredEntries = <Entry>[].obs;
  final showTodayEntries = true.obs;

  static bool _timezoneInitialized = false;

  @override
  void onInit() {
    super.onInit();
    _initializeTimezone();
    // DestinationControllerが登録されていない場合に備えて、lazyPutを使用
    Get.lazyPut<DestinationController>(() => DestinationController(), fenix: true);
    _destinationController = Get.find<DestinationController>();

    fetchEntries();
  }

  void _initializeTimezone() {
    if (!_timezoneInitialized) {
      tz.initializeTimeZones();
      _timezoneInitialized = true;
    }
  }

  Future<void> fetchEntries() async {
    try {
      final fetchedEntries = await _apiService.getEntries();
      entries.assignAll(fetchedEntries);
      filterEntries();
    } catch (e) {
      print('Error fetching entries: $e');
      // エラー処理を追加
    }
  }

  void filterEntries() {
    if (showTodayEntries.value) {
      filterEntriesForToday();
    } else {
      filteredEntries.assignAll(entries);
    }
  }

  void filterEntriesForToday() {
    final now = tz.TZDateTime.now(tz.getLocation('Asia/Tokyo'));
    filteredEntries.assignAll(entries.where((entry) {
      final entryDate = tz.TZDateTime.from(entry.date!, tz.getLocation('Asia/Tokyo'));
      return entryDate.year == now.year &&
          entryDate.month == now.month &&
          entryDate.day == now.day;
    }));
  }

  void filterEntriesForToday_old() {
    final now = DateTime.now();
    filteredEntries.assignAll(entries.where((entry) =>
    entry.date?.year == now.year &&
        entry.date?.month == now.month &&
        entry.date?.day == now.day
    ));
  }

  void toggleShowTodayEntries() {
    showTodayEntries.toggle();
    filterEntries();
  }

  void refreshMap() {
    final tk = _indexController.currentUser[0]["token"];
    if (tk != null) {

      _destinationController.fixMapBound(tk);
    }
  }

  Future<void> joinEvent(Entry entry) async {
      //final now = DateTime.now();
      final now = tz.TZDateTime.now(tz.getLocation('Asia/Tokyo'));
      final entryDate = tz.TZDateTime.from(entry.date!, tz.getLocation('Asia/Tokyo'));
      bool isToday = entryDate.year == now.year &&
          entryDate.month == now.month &&
          entryDate.day == now.day;

      _indexController.setReferenceMode(!isToday);
      _indexController.setSelectedEventName(entry.event.eventName);

      final userid = _indexController.currentUser[0]["user"]["id"];

      await _apiService.updateUserInfo(userid,entry);

      _indexController.currentUser[0]["user"]["event_date"] = entryDate;  // 追加2024-8-9
      _indexController.currentUser[0]["user"]["event_code"] = entry.event.eventName;
      _indexController.currentUser[0]["user"]["team_name"] = entry.team.teamName;
      _indexController.currentUser[0]["user"]["group"] = entry.team.category.categoryName;
      _indexController.currentUser[0]["user"]["zekken_number"] = entry.zekkenNumber;

      Get.back(); // エントリー一覧ページを閉じる
      //_indexController.isLoading.value = true;
      _indexController.reloadMap(entry.event.eventName);

      refreshMap();

      if (isToday) {
        Get.snackbar('成功', 'イベントに参加しました。',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.green,
            colorText: Colors.white);
      } else {
        Get.snackbar('参照モード', '過去または未来のイベントを参照しています。ロゲの開始やチェックインはできません。',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.orange,
            colorText: Colors.white);
      }
  }
}