import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path/path.dart' as path;
import 'package:share_plus/share_plus.dart';

import '../../../controller/functions/audio_record1.dart';

class TripsRecordedPage extends StatelessWidget {
  const TripsRecordedPage({super.key});

  @override
  Widget build(BuildContext context) {
    // Ensure the controller is available.
    // If it's not initialized elsewhere, you can use Get.put() or Get.lazyPut() here.
    // Get.lazyPut(() => AudioRecorderController());

    return Scaffold(
      appBar: AppBar(
        title: Text('Trips recorded'.tr),
        backgroundColor: Colors.white,
        elevation: 1,
        actions: [
          GetBuilder<AudioRecorderController>(
            builder: (controller) => IconButton(
              tooltip: 'Delete All'.tr,
              icon: const Icon(Icons.delete_sweep_outlined),
              onPressed: () {
                _showDeleteConfirmation(context, controller, isDeleteAll: true);
              },
            ),
          )
        ],
      ),
      body: GetBuilder<AudioRecorderController>(
        builder: (controller) {
          return Column(
            children: [
              Expanded(
                child: _buildRecordingsList(controller),
              ),
              // Show player controls only when a file is selected
              if (controller.selectedFilePath != null)
                _buildPlayerControls(context, controller),
            ],
          );
        },
      ),
    );
  }

  /// Builds the list of recorded audio files.
  Widget _buildRecordingsList(AudioRecorderController controller) {
    return FutureBuilder<List<String>>(
      future: controller.getRecordedFiles(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'.tr));
        }
        if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.mic_off_outlined, size: 80, color: Colors.grey[400]),
                const SizedBox(height: 16),
                Text(
                  'No Recordings Found'.tr,
                  style: TextStyle(fontSize: 18, color: Colors.grey[600]),
                ),
                const SizedBox(height: 8),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 40.0),
                  child: Text(
                    'Record your trips to see them here.'.tr,
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.grey[500]),
                  ),
                ),
              ],
            ),
          );
        }

        final recordedFiles = snapshot.data!;
        return ListView.builder(
          padding: const EdgeInsets.only(top: 8, bottom: 8),
          itemCount: recordedFiles.length,
          itemBuilder: (context, index) {
            final file = recordedFiles[index];
            final fileName = path.basename(file);
            final isSelected = controller.selectedFilePath == file;

            return Card(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
              elevation: isSelected ? 4 : 1,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12)),
              child: ListTile(
                leading: Icon(
                  isSelected && controller.isPlaying
                      ? Icons.pause_circle_filled
                      : Icons.play_circle_fill,
                  color:
                      isSelected ? Theme.of(context).primaryColor : Colors.grey,
                  size: 40,
                ),
                title: Text(fileName,
                    style: const TextStyle(fontWeight: FontWeight.w500)),
                subtitle: Text("Audio Recording".tr),
                onTap: () {
                  if (isSelected) {
                    controller.isPlaying
                        ? controller.pausePlayback()
                        : controller.resumePlayback();
                  } else {
                    controller.playRecordedFile(file);
                  }
                },
                selected: isSelected,
                selectedTileColor:
                    Theme.of(context).primaryColor.withOpacity(0.1),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12)),
              ),
            );
          },
        );
      },
    );
  }

  /// Builds the player UI at the bottom of the screen.
  Widget _buildPlayerControls(
      BuildContext context, AudioRecorderController controller) {
    final fileName = path.basename(controller.selectedFilePath!);
    final positionText = Duration(seconds: controller.currentPosition.toInt())
        .toString()
        .split('.')
        .first
        .padLeft(8, '0')
        .substring(3);
    final durationText = Duration(seconds: controller.totalDuration.toInt())
        .toString()
        .split('.')
        .first
        .padLeft(8, '0')
        .substring(3);

    return Material(
      elevation: 10,
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(fileName,
                style:
                    const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                textAlign: TextAlign.center),
            const SizedBox(height: 8),
            Row(
              children: [
                Text(positionText),
                Expanded(
                  child: Slider(
                    value: (controller.totalDuration > 0)
                        ? controller.currentPosition / controller.totalDuration
                        : 0.0,
                    onChanged: (value) {
                      final newPosition = value * controller.totalDuration;
                      controller.audioPlayer
                          .seek(Duration(seconds: newPosition.toInt()));
                    },
                  ),
                ),
                Text(durationText),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                IconButton(
                  icon: const Icon(Icons.share_outlined),
                  tooltip: 'Share'.tr,
                  onPressed: () {
                    Share.shareXFiles([XFile(controller.selectedFilePath!)]);
                  },
                  iconSize: 28,
                ),
                IconButton(
                  icon: Icon(controller.isPlaying
                      ? Icons.pause_circle_filled
                      : Icons.play_circle_filled),
                  onPressed: () {
                    controller.isPlaying
                        ? controller.pausePlayback()
                        : controller.resumePlayback();
                  },
                  iconSize: 56,
                  color: Theme.of(context).primaryColor,
                ),
                IconButton(
                  icon:
                      const Icon(Icons.delete_outline, color: Colors.redAccent),
                  tooltip: 'Delete'.tr,
                  onPressed: () {
                    _showDeleteConfirmation(context, controller,
                        isDeleteAll: false);
                  },
                  iconSize: 28,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  /// Shows a confirmation dialog for deleting one or all files.
  void _showDeleteConfirmation(
    BuildContext context,
    AudioRecorderController controller, {
    required bool isDeleteAll,
  }) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(isDeleteAll
              ? 'Delete All Recordings?'.tr
              : 'Delete Recording?'.tr),
          content: Text(isDeleteAll
              ? 'This action cannot be undone.'.tr
              : 'Are you sure you want to delete this file?'.tr),
          actions: [
            TextButton(
              child: Text('Cancel'.tr),
              onPressed: () => Navigator.of(context).pop(),
            ),
            TextButton(
              child:
                  Text('Delete'.tr, style: const TextStyle(color: Colors.red)),
              onPressed: () async {
                if (isDeleteAll) {
                  await controller.deleteAllRecordedFiles();
                } else {
                  // NOTE: You may need to add this method to your controller
                  // if it doesn't exist.
                  // await controller.deleteFile(controller.selectedFilePath!);
                }
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}
