// lib/widgets/dialogs/cast_dialog.dart

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

import 'package:aves/widgets/cast/dlna.dart';
import 'package:aves/widgets/dialogs/aves_dialog.dart';
import 'package:aves/widgets/common/extensions/build_context.dart';

/// Target astratto (rimane per compatibilità)
abstract class CastTarget {
  const CastTarget();
}

/// DLNA target
class DlnaTarget extends CastTarget {
  final DLNADevice device;
  const DlnaTarget(this.device);
}

/// Dialog dedicata SOLO al DLNA.
/// Google Cast Standard e Custom Receiver NON passano da qui.
class CastDialog extends StatefulWidget {
  static const routeName = '/dialog/cast';

  const CastDialog({super.key});

  @override
  State<CastDialog> createState() => _CastDialogState();
}

class _CastDialogState extends State<CastDialog> {
  // Ora i renderer DLNA devono essere passati dall’esterno
  // oppure gestiti da un discovery che aggiungeremo dopo.
  final Map<String, DLNADevice> _seenRenderers = {};

  @override
  void initState() {
    super.initState();
    // Nessuna discovery automatica: il controller o il chiamante
    // deve popolare _seenRenderers.
  }

  @override
  Widget build(BuildContext context) {
    return AvesDialog(
      title: context.l10n.castDialogTitle,
      scrollableContent: [
        const SizedBox(height: 12),
        _buildDlnaList(context),
      ],
      actions: const [
        CancelButton(),
      ],
    );
  }

  // -------------------------------------------
  // DLNA LIST
  // -------------------------------------------
  Widget _buildDlnaList(BuildContext context) {
    if (_seenRenderers.isEmpty) {
      return const Padding(
        padding: EdgeInsets.all(16),
        child: Center(child: Text("Nessun dispositivo DLNA trovato")),
      );
    }

    return ListView(
      shrinkWrap: true,
      children: _seenRenderers.values
          .map(
            (dev) => ListTile(
              leading: const Icon(Icons.tv),
              title: Text(dev.info.friendlyName),
              onTap: () =>
                  Navigator.of(context).pop<CastTarget>(DlnaTarget(dev)),
            ),
          )
          .toList(),
    );
  }
}
