import 'dart:io';
import 'dart:typed_data';

import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/cx_module/chat/api_client.dart';
import 'package:test_sa/modules/cx_module/chat/chat_api_client.dart';
import 'package:test_sa/modules/cx_module/chat/model/get_single_user_chat_list_model.dart';

import '../../../../new_views/app_style/app_color.dart';

class ChatAudioPlayer extends StatefulWidget {
  String downloadURl;
  FileTypeResponse file;
  bool isLocalFile;

  ChatAudioPlayer(this.file, this.downloadURl, {Key? key, this.isLocalFile = false}) : super(key: key);

  @override
  _ChatAudioPlayerState createState() {
    return _ChatAudioPlayerState();
  }
}

class _ChatAudioPlayerState extends State<ChatAudioPlayer> {
  bool downloading = false;

  PlayerController playerController = PlayerController();

  @override
  void initState() {
    super.initState();
    checkFileInLocalStorage();
  }

  File? audioFile;
  List<double> waveformData = [];

  void checkFileInLocalStorage() async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = '${tempDir.path}/${widget.file.fileName}';
    File tempFile = File(tempPath);
    bool exists = await tempFile.exists();
    if (exists) {
      audioFile = tempFile;
      playerController = PlayerController();
      await playerController.preparePlayer(path: tempPath);
      waveformData = await playerController.extractWaveformData(path: tempPath);
    } else {
      downloadFile();
    }
  }

  void downloadFile() async {
    downloading = true;
    setState(() {});
    try {
      // Uint8List list = await ChatApiClient().downloadFileWithHttp(widget.downloadURl, fileName: widget.file.fileName, fileTypeDescription: widget.file.fileTypeDescription, fileSource: widget.file.fileTypeId!);
      // audioFile = File.fromRawPath(list);

      audioFile =
          await ChatApiClient().downloadFileWithHttp(widget.downloadURl, fileName: widget.file.fileName, fileTypeDescription: widget.file.fileTypeDescription, fileSource: widget.file.fileTypeId!);

      playerController = PlayerController();
      await playerController.preparePlayer(path: audioFile!.path);
      waveformData = await playerController.extractWaveformData(path: audioFile!.path);
    } catch (ex) {
      print(ex);
      audioFile = null;
    }
    downloading = false;
    setState(() {});
  }

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

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 56,
      child: Row(
        children: [
          if (downloading)
            const SizedBox(
              height: 24,
              width: 24,
              child: CircularProgressIndicator(color: AppColor.primary10, strokeWidth: 2),
            )
          else if (playerController.playerState == PlayerState.playing)
            IconButton(
              onPressed: () async {
                await playerController.pausePlayer();
                await playerController.stopPlayer();
                setState(() {});
              },
              style: const ButtonStyle(
                tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded
              ),
              icon: const Icon(Icons.stop_circle_outlined, size: 20),
              constraints: const BoxConstraints(),
            )
          else
            IconButton(
              onPressed: () async {
                await playerController.startPlayer();
                setState(() {});
              },
              style: const ButtonStyle(
                tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded
              ),
              icon: const Icon(Icons.play_circle_fill_rounded, size: 20),
              constraints: const BoxConstraints(),
            ),
          AudioFileWaveforms(
            playerController: playerController,
            waveformData: waveformData,
            enableSeekGesture: false,
            continuousWaveform: false,
            waveformType: WaveformType.long,
            playerWaveStyle: const PlayerWaveStyle(
              fixedWaveColor: AppColor.neutral50,
              liveWaveColor: AppColor.primary10,
              showSeekLine: true,
            ),
            size: Size(MediaQuery.of(context).size.width, 56.0),
          ).expanded,
        ],
      ),
    );
  }
}
