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

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:aves/model/entry/entry.dart';
import 'package:aves/model/selection.dart';
import 'package:aves/model/source/collection_lens.dart';

import 'package:aves/services/cast/cast_server.dart';
import 'package:aves/widgets/cast/cast_controller.dart';

import 'package:aves/widgets/viewer/fullscreen_cast_viewer.dart';
import 'package:aves/widgets/viewer/fullscreen_cast_viewer_dlna.dart';

import 'cast_controls_sheet.dart';

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

  // ------------------------------------------------------------
  // RISOLVE LE ENTRY DA CASTARE
  // ------------------------------------------------------------
  List<AvesEntry> _resolveEntries(BuildContext context) {
    List<AvesEntry> entries = [];

    try {
      final selection = context.read<Selection<AvesEntry>>();
      entries = selection.selectedItems.toList();
    } catch (_) {}

    if (entries.isEmpty) {
      try {
        final lens = context.read<CollectionLens>();
        final lensEntries = lens.sortedEntries;
        if (lensEntries != null && lensEntries.isNotEmpty) {
          entries = List<AvesEntry>.from(lensEntries);
        }
      } catch (_) {}
    }

    if (entries.isEmpty) {
      try {
        final single = Provider.of<AvesEntry>(context, listen: false);
        entries = [single];
      } catch (_) {}
    }

    return entries;
  }

  // ------------------------------------------------------------
  // MOSTRA CONTROLLI CAST
  // ------------------------------------------------------------
  void _showCastControlsSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.black87,
      builder: (_) => const CastControlsSheet(),
    );
  }

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

    return Container(
      height: 48,
      padding: const EdgeInsets.symmetric(horizontal: 8),
      color: Theme.of(context).colorScheme.surfaceVariant,
      child: Row(
        children: [
          // ------------------------------------------------------------
          // 1) CAST + VIEWER FULLSCREEN
          // ------------------------------------------------------------
          IconButton(
            icon: const Icon(Icons.aspect_ratio),
            tooltip: 'Cast + viewer fullscreen',
            onPressed: () async {
              final entries = _resolveEntries(context);
              if (entries.isEmpty) return;

              await castServer.start();

              await controller.startFullscreen(entries, 0);

              if (!context.mounted) return;

              await Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (_) => controller.backendNotifier.value == CastBackend.dlna
                      ? FullscreenCastViewerDlna(
                          entries: entries,
                          startIndex: 0,
                        )
                      : FullscreenCastViewer(
                          entries: entries,
                          startIndex: 0,
                        ),
                  fullscreenDialog: true,
                ),
              );
            },
          ),

          // ------------------------------------------------------------
          // 2) CAST NORMALE (manuale)
          // ------------------------------------------------------------
          IconButton(
            icon: const Icon(Icons.screen_share),
            tooltip: 'Cast normale',
            onPressed: () async {
              final entries = _resolveEntries(context);
              if (entries.isEmpty) return;

              await castServer.start();
              await controller.startManualQueue(entries, 0);
            },
          ),

          // ------------------------------------------------------------
          // 3) SLIDESHOW
          // ------------------------------------------------------------
          IconButton(
            icon: const Icon(Icons.play_arrow),
            tooltip: 'Avvia slideshow',
            onPressed: () async {
              final entries = _resolveEntries(context);
              if (entries.isEmpty) return;

              await controller.startSlideshow(entries, 0);
            },
          ),

          // ------------------------------------------------------------
          // 4) CONTROLLI CAST
          // ------------------------------------------------------------
          IconButton(
            icon: const Icon(Icons.cast_connected),
            tooltip: 'Controlli Cast',
            onPressed: () => _showCastControlsSheet(context),
          ),

          // ------------------------------------------------------------
          // 5) STOP CAST
          // ------------------------------------------------------------
          IconButton(
            icon: const Icon(Icons.stop),
            tooltip: 'Stop cast',
            onPressed: () => controller.stopCast(),
          ),

          // ------------------------------------------------------------
          // 6) PREV
          // ------------------------------------------------------------
          ValueListenableBuilder<int>(
            valueListenable: controller.currentIndexNotifier,
            builder: (context, index, _) {
              return IconButton(
                icon: const Icon(Icons.skip_previous),
                tooltip: 'Precedente',
                onPressed: () async {
                  await controller.prevManual();
                },
              );
            },
          ),

          // ------------------------------------------------------------
          // 7) NEXT
          // ------------------------------------------------------------
          IconButton(
            icon: const Icon(Icons.skip_next),
            tooltip: 'Successivo',
            onPressed: () async {
              await controller.nextManual();
            },
          ),
        ],
      ),
    );
  }
}
