import 'dart:io';
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;

  // Start recording
  Future<void> startRecording({String? rideId}) async {
    final bool isPermissionGranted = await recorder.hasPermission();
    if (!isPermissionGranted) {
      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
    String fileName = (rideId != null && rideId.isNotEmpty && rideId != 'yet' && rideId != 'null')
        ? '${dateStr}_$rideId.m4a'
        : '$dateStr.m4a';
    filePath = '${directory.path}/$fileName';

    const config = RecordConfig(
      encoder: AudioEncoder.aacLc,
      sampleRate: 44100,
      bitRate: 128000,
    );

    await recorder.start(config, path: filePath);

    isRecording = true;
    update();
  }

  // Stop recording
  Future<void> stopRecording() async {
    await recorder.stop();
    isRecording = false;
    isPaused = false;
    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();
    }
  }

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