import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:nm/nm.dart';

import '../../../../common/extension/getCharCodes.dart';
import '../../../../common/widgets/scaffold_with_statusbar.dart';
import '../../business/wifi_controller.dart';
import 'widgets/ap_pw_dialog.dart';
import 'widgets/wifi_bar_icon.dart';

class AccessPointScreen extends ConsumerWidget {
  const AccessPointScreen({
    this.accessPoint,
    super.key,
  });

  final NetworkManagerAccessPoint? accessPoint;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final wifiRepository = (accessPoint != null)
        ? ref.watch(wifiControllerProvider.notifier).wifiStream()
        : const Stream.empty();

    return ScaffoldWithStatusbar(
      appBar: AppBar(
        title: Row(
          children: [
            Text(
              String.fromCharCodes(
                accessPoint?.ssid ?? 'Demo'.getCharCodes(),
              ),
            ),
            if (accessPoint?.rsnFlags.isNotEmpty ?? true)
              const Padding(
                padding: EdgeInsets.only(left: 8.0),
                child: Icon(
                  Icons.lock,
                ),
              )
          ],
        ),
      ),
      body: SingleChildScrollView(
          child: Center(
        child: Container(
          // TODO: boxconstraint constant
          constraints: const BoxConstraints(maxWidth: 500),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ListTile(
                leading: WifiBarIcon(strength: accessPoint?.strength ?? 1),
                title: const Text('Signal Strength'),
                subtitle: Text(accessPoint?.strength.toString() ?? '1'),
              ),
              const Divider(),
              ListTile(
                leading: const Icon(Icons.hardware),
                title: const Text('Hardware Address'),
                subtitle: Text(accessPoint?.hwAddress ?? '00:00:00:00:00:00'),
              ),
              const Divider(),
              ListTile(
                leading: const Icon(Icons.speed),
                title: const Text('Max Bitrate in kb/s'),
                subtitle: Text(accessPoint?.maxBitrate.toString() ?? '0'),
              ),
              const Divider(),
              ListTile(
                leading: const Icon(Icons.radio),
                title: const Text('Radio frequency in MHz'),
                subtitle: Text(accessPoint?.frequency.toString() ?? '0'),
              ),
              const Divider(),
              StreamBuilder(
                  stream: wifiRepository,
                  builder: (context, snapshot) {
                    if (!Platform.isLinux) {
                      return ElevatedButton(
                        onPressed: () {
                          if (accessPoint?.rsnFlags.isNotEmpty ?? true) {
                            showDialog(
                              context: context,
                              builder: (context) {
                                return AccessPointPasswordDialog(
                                  accessPoint: accessPoint,
                                );
                              },
                            );
                          } else {
                            if (accessPoint != null) {
                              ref
                                  .read(wifiControllerProvider.notifier)
                                  .connectToWifiNetwork(
                                    accessPoint: accessPoint!,
                                  );
                              context.pop();
                            }
                          }
                        },
                        child: const Text('Demo Connect'),
                      );
                    }
                    if (snapshot.hasData) {
                      return Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            ElevatedButton(
                              onPressed: () {
                                if (accessPoint != null) {
                                  ref
                                      .read(wifiControllerProvider.notifier)
                                      .disconnectFromWifiNetwork(
                                        accessPoint: accessPoint!,
                                      );
                                }
                              },
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.red,
                                foregroundColor: Colors.white,
                              ),
                              child: const Text('Forget Connection'),
                            ),
                            ElevatedButton(
                              onPressed: () {
                                if (accessPoint?.rsnFlags.isNotEmpty ?? true) {
                                  showDialog(
                                    context: context,
                                    builder: (context) {
                                      return AccessPointPasswordDialog(
                                        accessPoint: accessPoint,
                                      );
                                    },
                                  );
                                } else {
                                  if (accessPoint != null) {
                                    ref
                                        .read(wifiControllerProvider.notifier)
                                        .connectToWifiNetwork(
                                          accessPoint: accessPoint!,
                                        );
                                    context.pop();
                                  }
                                }
                              },
                              child: const Text('Connect'),
                            )
                          ],
                        ),
                      );
                    } else if (snapshot.hasError) {
                      return const Text('Lost connection');
                    } else {
                      return const Padding(
                        padding: EdgeInsets.only(top: 16.0),
                        child: CircularProgressIndicator(),
                      );
                    }
                  }),
            ],
          ),
        ),
      )),
    );
  }
}
