import 'package:siro_rider/print.dart';
import 'dart:io';

// import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';

import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:record/record.dart';

class AudioRecorderController extends GetxController {
  AudioPlayer audioPlayer = AudioPlayer();
  AudioRecorder recorder = AudioRecorder();

  bool isRecording = false;
  bool isPlaying = false;
  bool isPaused = false;
  String filePath = '';
  String? selectedFilePath;
  double currentPosition = 0;
  double totalDuration = 0;

  Future<void> playSoundFromAssets(String sound) async {
    try {
      await audioPlayer.setAsset(sound);
      audioPlayer.play();
    } catch (e) {
      Log.print("Error playing sound: $e");
    }
  }

  // Start recording
  Future<void> startRecording({String? rideId}) async {
    final bool isPermissionGranted = await recorder.hasPermission();
    if (!isPermissionGranted) {
      // RecordingPermissionException('l');
      return;
    }

    final directory = await getApplicationDocumentsDirectory();
    final String dateStr =
        '${DateTime.now().year}-${DateTime.now().month.toString().padLeft(2, '0')}-${DateTime.now().day.toString().padLeft(2, '0')}';
    // Generate a unique file name using the current timestamp
    String fileName = (rideId != null && rideId.isNotEmpty && rideId != 'yet' && rideId != 'null')
        ? '${dateStr}_$rideId.m4a'
        : '$dateStr.m4a';
    filePath = '${directory.path}/$fileName';

    // Define the configuration for the recording
    const config = RecordConfig(
      // Specify the format, encoder, sample rate, etc., as needed
      encoder: AudioEncoder.aacLc, // For example, using AAC codec
      sampleRate: 44100, // Sample rate
      bitRate: 128000, // Bit rate
    );

    // Start recording to file with the specified configuration
    await recorder.start(config, path: filePath);

    isRecording = true;
    update();
  }

  // Pause recording
  Future<void> pauseRecording() async {
    if (isRecording && !isPaused) {
      await recorder.pause();
      isPaused = true;
      update();
    }
  }

  // Resume recording
  Future<void> resumeRecording() async {
    if (isRecording && isPaused) {
      await recorder.resume();
      isPaused = false;
      update();
    }
  }

  // Stop recording
  Future<void> stopRecording() async {
    recorder.stop();
    isRecording = false;
    isPaused = false;
    update();
  }

  // Play the selected recorded file
  Future<void> playRecordedFile(String filePath) async {
    await audioPlayer.setFilePath(filePath);
    totalDuration = audioPlayer.duration?.inSeconds.toDouble() ?? 0;
    audioPlayer.play();

    isPlaying = true;
    isPaused = false;
    audioPlayer.positionStream.listen((position) {
      currentPosition = position.inSeconds.toDouble();
      update();
    });
    selectedFilePath = filePath;
    update();
  }

  // Pause playback
  Future<void> pausePlayback() async {
    if (isPlaying && !isPaused) {
      await audioPlayer.pause();
      isPaused = true;
      update();
    }
  }

  // Resume playback
  Future<void> resumePlayback() async {
    if (isPlaying && isPaused) {
      await audioPlayer.play();
      isPaused = false;
      update();
    }
  }

  // Stop playback
  Future<void> stopPlayback() async {
    await audioPlayer.stop();
    isPlaying = false;
    isPaused = false;
    currentPosition = 0;
    update();
  }

  // Get a list of recorded files
  Future<List<String>> getRecordedFiles() async {
    final directory = await getApplicationDocumentsDirectory();
    final files = await directory.list().toList();
    return files
        .map((file) => file.path)
        .where((path) => path.endsWith('.m4a'))
        .toList();
  }

  // Delete a specific recorded file
  Future<void> deleteRecordedFile(String filePath) async {
    final file = File(filePath);
    if (await file.exists()) {
      await file.delete();
      update();
    }
  }

  // Delete all recorded files
  Future<void> deleteAllRecordedFiles() async {
    final directory = await getApplicationDocumentsDirectory();
    final files = await directory.list().toList();
    for (final file in files) {
      if (file.path.endsWith('.m4a')) {
        await deleteRecordedFile(file.path);
      }
    }
  }

  @override
  void onClose() {
    audioPlayer.dispose();
    recorder.dispose();
    super.onClose();
  }
}