// lib/widgets/collection/app_bar/cast/cast_controls_sheet.dart

import 'package:flutter/material.dart';
import 'package:aves/widgets/cast/cast_controller.dart';

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

  String _formatDuration(Duration d) {
    final totalSeconds = d.inSeconds;
    final hours = totalSeconds ~/ 3600;
    final minutes = (totalSeconds % 3600) ~/ 60;
    final seconds = totalSeconds % 60;

    if (hours > 0) {
      return '${hours.toString().padLeft(2, '0')}:'
          '${minutes.toString().padLeft(2, '0')}:'
          '${seconds.toString().padLeft(2, '0')}';
    }

    return '${minutes.toString().padLeft(2, '0')}:'
        '${seconds.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    final controller = CastController.instance;

    return SafeArea(
      child: Container(
        color: Colors.black87,
        padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              'Controlli Cast',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),

            const SizedBox(height: 16),

            // ------------------------------------------------------------
            // SEEK SOLO PER GOOGLE
            // ------------------------------------------------------------
            ValueListenableBuilder<CastBackend>(
              valueListenable: controller.backendNotifier,
              builder: (context, backend, _) {
                if (backend != CastBackend.google) {
                  return const SizedBox.shrink();
                }

                return ValueListenableBuilder<Duration>(
                  valueListenable: controller.durationNotifier,
                  builder: (context, duration, _) {
                    return ValueListenableBuilder<Duration>(
                      valueListenable: controller.positionNotifier,
                      builder: (context, position, __) {
                        final maxMs = duration.inMilliseconds <= 0
                            ? 1
                            : duration.inMilliseconds;
                        final valueMs =
                            position.inMilliseconds.clamp(0, maxMs);

                        return Column(
                          children: [
                            Slider(
                              value: valueMs.toDouble(),
                              min: 0,
                              max: maxMs.toDouble(),

                              // aggiorna UI locale mentre trascini
                              onChanged: (v) {
                                controller.positionNotifier.value =
                                    Duration(milliseconds: v.toInt());
                              },

                              // invia seek al Chromecast
                              onChangeEnd: (v) {
                                controller.google.seekCast(
                                  Duration(milliseconds: v.toInt()),
                                );
                              },
                            ),
                            Row(
                              children: [
                                Text(
                                  _formatDuration(position),
                                  style: const TextStyle(color: Colors.white70),
                                ),
                                const Spacer(),
                                Text(
                                  _formatDuration(duration),
                                  style: const TextStyle(color: Colors.white70),
                                ),
                              ],
                            ),
                          ],
                        );
                      },
                    );
                  },
                );
              },
            ),

            const SizedBox(height: 16),

            // ------------------------------------------------------------
            // CONTROLLI PLAYBACK
            // ------------------------------------------------------------
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                IconButton(
                  iconSize: 32,
                  color: Colors.white,
                  icon: const Icon(Icons.skip_previous),
                  onPressed: () async {
                    await controller.google.prevManual();
                  },
                ),

                const SizedBox(width: 8),

                ValueListenableBuilder<CastBackend>(
                  valueListenable: controller.backendNotifier,
                  builder: (context, backend, _) {
                    if (backend != CastBackend.google) {
                      return const SizedBox.shrink();
                    }

                    return ValueListenableBuilder<bool>(
                      valueListenable: controller.isPlayingNotifier,
                      builder: (context, isPlaying, _) {
                        return IconButton(
                          iconSize: 40,
                          color: Colors.white,
                          icon: Icon(
                            isPlaying
                                ? Icons.pause_circle
                                : Icons.play_circle,
                          ),
                          onPressed: () {
                            if (isPlaying) {
                              controller.google.pauseCast();
                            } else {
                              controller.google.playCast();
                            }
                          },
                        );
                      },
                    );
                  },
                ),

                const SizedBox(width: 8),

                IconButton(
                  iconSize: 32,
                  color: Colors.white,
                  icon: const Icon(Icons.skip_next),
                  onPressed: () async {
                    await controller.google.nextManual();
                  },
                ),
              ],
            ),

            const SizedBox(height: 16),

            // ------------------------------------------------------------
            // VOLUME SOLO PER GOOGLE
            // ------------------------------------------------------------
            ValueListenableBuilder<CastBackend>(
              valueListenable: controller.backendNotifier,
              builder: (context, backend, _) {
                if (backend != CastBackend.google) {
                  return const SizedBox.shrink();
                }

                return Column(
                  children: [
                    ValueListenableBuilder<double>(
                      valueListenable: controller.volumeNotifier,
                      builder: (context, volume, _) {
                        return Row(
                          children: [
                            IconButton(
                              color: Colors.white,
                              icon: const Icon(Icons.volume_up),
                              onPressed: () {
                                controller.google.toggleMuteCast();
                              },
                            ),
                            Expanded(
                              child: Slider(
                                value: volume.clamp(0.0, 1.0),
                                min: 0,
                                max: 1,

                                // aggiorna UI locale
                                onChanged: (v) {
                                  controller.volumeNotifier.value = v;
                                },

                                // invia volume al Chromecast
                                onChangeEnd: (v) {
                                  controller.google.setCastVolume(v);
                                },
                              ),
                            ),
                          ],
                        );
                      },
                    ),
                    const SizedBox(height: 16),
                  ],
                );
              },
            ),

            Wrap(
              spacing: 8,
              runSpacing: 8,
              alignment: WrapAlignment.center,
              children: [
                ElevatedButton.icon(
                  onPressed: () async {
                    await controller.google.stopGoogleCast();
                    if (context.mounted) Navigator.of(context).pop();
                  },
                  icon: const Icon(Icons.stop_circle_outlined),
                  label: const Text('Stop Cast'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
