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

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

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

import 'package:aves/widgets/cast/animated_cast_icon.dart';
import 'package:aves/widgets/cast/cast_controller.dart';
import 'package:aves/widgets/cast/dlna_dialog.dart';
import 'package:aves/widgets/cast/dlna.dart';
import 'package:aves/widgets/cast/backends/dlna_cast_backend.dart';

class CastIconButton extends StatefulWidget {
  const CastIconButton({super.key});

  @override
  State<CastIconButton> createState() => _CastIconButtonState();
}

class _CastIconButtonState extends State<CastIconButton> {
  Timer? _lpTimer;
  bool _longPressFired = false;

  static const _longPressDelay = Duration(milliseconds: 600);

  @override
  void dispose() {
    _lpTimer?.cancel();
    super.dispose();
  }

  // ------------------------------------------------------------
  // Recupera entries come nel vecchio app_bar.dart
  // ------------------------------------------------------------
  List<AvesEntry> _resolveEntries() {
    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;
  }

  // ------------------------------------------------------------
  // TAP BREVE → toggle ON/OFF
  // ------------------------------------------------------------
  Future<void> _onTap() async {
    final controller = CastController.instance;
    final backend = controller.backendNotifier.value;
    final state = controller.castIconState.value;

    debugPrint('CastIconButton: TAP state=$state backend=$backend');

    // Se sto già castando → STOP
    if (state == CastIconState.connecting || state == CastIconState.connected) {
      await controller.stopCast();
      return;
    }

    // Stato = idle → avvia backend selezionato
    final entries = _resolveEntries();
    if (entries.isEmpty) return;

    switch (backend) {
      case CastBackend.google:
        // Dialog nativo Android
        await controller.google.showGoogleCastDialog();
        return;

      case CastBackend.fast:
        // FAST usa lo stesso dialog Android
        await controller.google.showGoogleCastDialog();
        return;

case CastBackend.dlna:
  // DLNA → selezione renderer via dialog
  final device = await showDialog<DLNADevice>(
    context: context,
    builder: (_) => const CastDialogDlna(),
  );

  if (device != null) {
    final dlna = controller.backend as DlnaCastBackend;

    // 1️⃣ Imposta renderer
    dlna.setRenderer(device);

    // 2️⃣ Mostra la cast bar
    controller.isCastingNotifier.value = true;

    // 3️⃣ Mostra stato “sto connettendo”
    controller.castIconState.value = CastIconState.connecting;

    // 4️⃣ Prepara il media server in anticipo (opzionale ma consigliato)
    unawaited(dlna.ensureMediaServerPrewarm());
  }
  return;

    }
  }

  // ------------------------------------------------------------
  // TAP LUNGO → selettore backend
  // ------------------------------------------------------------
  Future<void> _onLongPress() async {
    final controller = CastController.instance;

    final backend = await showModalBottomSheet<CastBackend>(
      context: context,
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.cast),
                title: const Text('Google Cast'),
                onTap: () => Navigator.pop(context, CastBackend.google),
              ),
              ListTile(
                leading: const Icon(Icons.flash_on),
                title: const Text('FAST Receiver'),
                onTap: () => Navigator.pop(context, CastBackend.fast),
              ),
              ListTile(
                leading: const Icon(Icons.wifi),
                title: const Text('DLNA'),
                onTap: () => Navigator.pop(context, CastBackend.dlna),
              ),
            ],
          ),
        );
      },
    );

    if (backend != null) {
      await controller.setBackend(backend);
    }
  }

  // ------------------------------------------------------------
  // Gestione long press manuale
  // ------------------------------------------------------------
  void _startLongPressTimer() {
    _lpTimer?.cancel();
    _longPressFired = false;

    _lpTimer = Timer(_longPressDelay, () async {
      if (!mounted) return;
      _longPressFired = true;
      await _onLongPress();
    });
  }

  void _cancelLongPressTimer() {
    _lpTimer?.cancel();
    _lpTimer = null;
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 48,
      height: 48,
      child: Listener(
        behavior: HitTestBehavior.opaque,
        onPointerDown: (_) => _startLongPressTimer(),
        onPointerUp: (_) async {
          _cancelLongPressTimer();
          if (_longPressFired) {
            _longPressFired = false;
            return;
          }
          await _onTap();
        },
        onPointerCancel: (_) => _cancelLongPressTimer(),
        child: const Center(
          child: AnimatedCastIcon(),
        ),
      ),
    );
  }
}
