import 'dart:io';

import 'package:flutter/material.dart';
import 'package:sense_the_rhythm/utils/esense_input.dart';
import 'package:sense_the_rhythm/utils/simfile.dart';
import 'package:sense_the_rhythm/screens/level.dart';
import 'package:sense_the_rhythm/widgets/esense_connect_dialog.dart';
import 'package:sense_the_rhythm/widgets/esense_not_connected_dialog.dart';

class LevelListEntry extends StatelessWidget {
  const LevelListEntry({
    super.key,
    required this.simfile,
  });

  final Simfile simfile;

  void navigateToLevel(BuildContext context) {
    Navigator.push(context,
        MaterialPageRoute(builder: (BuildContext context) => Level(simfile)));
  }

  void openESenseConnectDialog(context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return ESenseConnectDialog(
          deviceStatus: ESenseInput.instance.deviceStatus,
          connect: (String name) {
            ESenseInput.instance.connectToESense(name);
          },
          disconnect: () {
            ESenseInput.instance.eSenseManager.disconnect();
          },
        );
      },
    );
  }

  void tapHandler(BuildContext context) {
    if (ESenseInput.instance.connected) {
      navigateToLevel(context);
    } else {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return ESenseNotConnectedDialog(
            onCancel: () {
              openESenseConnectDialog(context);
            },
            onContinue: () {
              navigateToLevel(context);
            },
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Image.file(File(simfile.bannerPath!)),
      trailing: Icon(Icons.play_arrow),
      title: Text(simfile.tags["TITLE"]!),
      subtitle: Text('3:45'),
      onTap: () {
        tapHandler(context);
      },
    );
  }
}
