import 'dart:convert';

import 'package:siro_driver/constant/links.dart';
import 'package:siro_driver/main.dart';
import 'package:siro_driver/controller/functions/crud.dart';
import 'package:siro_driver/print.dart';
import 'package:siro_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

class VideoController extends GetxController {
  var videos = [];
  var isLoading = true.obs;
  final String apiUrl =
      '${AppLink.seferCairoServer}/ride/videos_driver/get.php';

  @override
  void onInit() {
    fetchVideos();
    super.onInit();
  }

  late VideoPlayerController videoPlayerController;

  // Initialize the video player with the provided URL
  Future<void> initializeVideo(String videoUrl) async {
    videoPlayerController =
        VideoPlayerController.networkUrl(Uri.parse(videoUrl));
    await videoPlayerController.initialize();
    videoPlayerController
        .setLooping(true); // Set to true if you want the video to loop
    update(); // Update the UI after the video has been initialized
  }

  // Play the video
  void play() {
    videoPlayerController.play();
    update();
  }

  // Pause the video
  void pause() {
    videoPlayerController.pause();
    update();
  }

  @override
  void onClose() {
    videoPlayerController
        .dispose(); // Dispose of the video player controller when not in use
    super.onClose();
  }

  void fetchVideos({bool force = false}) async {
    final String cacheKey = 'video_list_cache';
    final String lastFetchKey = 'video_last_fetch';

    if (!force) {
      String? cachedVideos = box.read(cacheKey);
      String? lastFetchStr = box.read(lastFetchKey);

      if (cachedVideos != null && lastFetchStr != null) {
        try {
          DateTime lastFetch = DateTime.parse(lastFetchStr);
          if (DateTime.now().difference(lastFetch).inHours < 3) {
            videos = jsonDecode(cachedVideos);
            isLoading(false);
            update();
            return;
          }
        } catch (e) {
          Log.print('⚠️ [VideoController] Failed to parse cache: $e');
        }
      }
    }

    try {
      var res = await CRUD().get(link: apiUrl, payload: {});
      if (res != 'failure') {
        videos = jsonDecode(res)['message'];
        box.write(cacheKey, jsonEncode(videos));
        box.write(lastFetchKey, DateTime.now().toIso8601String());
        update();
      } else {
        mySnackeBarError('');
      }
    } catch (e) {
      mySnackeBarError(e.toString());
    } finally {
      isLoading(false);
    }
  }
}
