import 'dart:convert';
import 'dart:io' as Io;
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:mohem_flutter_app/api/dashboard_api_client.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/main.dart';
import 'package:mohem_flutter_app/models/itg/advertisement.dart' as ads;
import 'package:path_provider/path_provider.dart';
import 'package:video_player/video_player.dart';

class ITGAdsScreen extends StatefulWidget {
  const ITGAdsScreen({Key? key}) : super(key: key);

  @override
  _ITGAdsScreenState createState() => _ITGAdsScreenState();
}

class _ITGAdsScreenState extends State<ITGAdsScreen> {
  late Future<VideoPlayerController> _futureController;
  late VideoPlayerController _controller;
  bool skip = false;
  bool isVideo = false;
  bool isImage = false;
  String ext = '';
  late File imageFile;
  ads.Advertisement? advertisementData;
  dynamic data;
  String? masterID;

  void checkFileType() async {
    String? rFile = advertisementData!.viewAttachFileColl!.first.base64String;
    String? rFileExt = advertisementData!.viewAttachFileColl!.first.fileName;
    ext = "." + rFileExt!.split(".").last.toLowerCase();
    if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif") {
      await processImage(rFile!);
      isImage = true;
    } else {
      isVideo = true;
      _futureController = createVideoPlayer(rFile!);
    }
    setState(() {});
    initTimer();
  }

  Future processImage(String encodedBytes) async {
    try {
      Uint8List decodedBytes = base64Decode(encodedBytes.split("base64,").last);
      Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); // 1
      imageFile = Io.File("${appDocumentsDirectory.path}/addImage$ext");
      imageFile.writeAsBytesSync(decodedBytes);
    } catch (e) {
      logger.d(e);
    }
  }

  Future<VideoPlayerController> createVideoPlayer(String encodedBytes) async {
    try {
      Uint8List decodedBytes = base64Decode(encodedBytes.split("base64,").last);
      Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); // 1
      File file = Io.File("${appDocumentsDirectory.path}/myAdsVideo.mp4");
      file.writeAsBytesSync(decodedBytes);
      VideoPlayerController controller = VideoPlayerController.file(file);
      await controller.initialize();
      await controller.play();
      await controller.setVolume(1.0);
      await controller.setLooping(false);
      return controller;
    } catch (e) {
      return VideoPlayerController.asset("dataSource");
    }
  }

  void initTimer() {
    Future.delayed(const Duration(seconds: 5), () {
      skip = true;
      setState(() {});
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    data = ModalRoute.of(context)!.settings.arguments;
    if (advertisementData == null) advertisementData = data["advertisement"] as ads.Advertisement;
    if (masterID == null) masterID = data["masterId"];
    if (advertisementData != null) {
      checkFileType();
    }
   // double height = MediaQuery.of(context).size.height * .25;
    return Scaffold(
      body: Stack(
        children: [
          if (isVideo)
            FutureBuilder(
              future: _futureController,
              builder: (BuildContext context, AsyncSnapshot<Object?> snapshot) {
                if (snapshot.connectionState == ConnectionState.done && snapshot.data != null) {
                  _controller = snapshot.data as VideoPlayerController;
                  return Positioned.fill(
                    child: AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller),
                    ),
                  );
                } else {
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                }
              },
            ),
          if (isImage) Image.file(imageFile),
          if (skip)
            ElevatedButton(
              onPressed: () async {
                // DashboardApiClient().setAdvertisementViewed(widget.addMasterId, widget.advertisement!.advertisementId!).then((value) {
                //   logger.d(value);
                // });
              },
              child: const Text("Go To Dashboard"),
            )
        ],
      ),
    );
  }
}
