import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:simplecloudnotifier/components/layout/scaffold.dart';
import 'package:simplecloudnotifier/models/scan_result.dart';
import 'package:simplecloudnotifier/pages/channel_scanner/channel_scanner_result_channelsubscribe.dart';
import 'package:simplecloudnotifier/pages/channel_scanner/channel_scanner_result_channelview.dart';
import 'package:simplecloudnotifier/pages/channel_scanner/channel_scanner_result_messagesend.dart';
import 'package:simplecloudnotifier/utils/ui.dart';

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

  @override
  State<ChannelScannerPage> createState() => _ChannelScannerPageState();
}

class _ChannelScannerPageState extends State<ChannelScannerPage> {
  final MobileScannerController _controller = MobileScannerController(
    formats: const [BarcodeFormat.qrCode],
  );

  ScanResult? scanResult = null;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SCNScaffold(
      title: "Scanner",
      showSearch: false,
      showShare: false,
      child: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(24, 16, 24, 16),
          child: Column(
            children: [
              SizedBox(height: 16),
              if (scanResult == null) ...[
                Center(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(UI.DefaultBorderRadius),
                    ),
                    clipBehavior: Clip.hardEdge,
                    child: SizedBox(
                      height: 300,
                      width: 300,
                      child: MobileScanner(
                        fit: BoxFit.cover,
                        controller: _controller,
                        onDetect: _handleBarcode,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 16),
              ],
              Center(
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxWidth: 300, minWidth: 300, minHeight: 200),
                  child: _buildScanResult(context),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _handleBarcode(BarcodeCapture barcodes) {
    setState(() {
      if (barcodes.barcodes.isEmpty) {
        scanResult = null;
      } else {
        scanResult = ScanResult.parse(barcodes.barcodes[0].rawValue ?? '');
        print('parsed: ${jsonEncode(barcodes.barcodes[0].rawValue)} as ${scanResult.runtimeType.toString()}');
      }
    });
  }

  Widget _buildScanResult(BuildContext context) {
    if (scanResult == null) {
      return UI.box(
        padding: EdgeInsets.fromLTRB(16, 32, 16, 8),
        context: context,
        child: Center(
          child: Column(
            spacing: 32,
            children: [
              Icon(FontAwesomeIcons.solidEmptySet, size: 64, color: Theme.of(context).colorScheme.onPrimaryContainer.withAlpha(48)),
              Text("Please scan a Channel QR Code to subscribe to it", style: TextStyle(fontStyle: FontStyle.italic), textAlign: TextAlign.center),
            ],
          ),
        ),
      );
    }

    if (scanResult! is ScanResultMessageSend) {
      return UI.box(
        padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
        context: context,
        child: ChannelScannerResultMessageSend(value: scanResult! as ScanResultMessageSend),
      );
    }

    if (scanResult! is ScanResultChannel) {
      return UI.box(
        padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
        context: context,
        child: ChannelScannerResultChannelView(value: scanResult! as ScanResultChannel),
      );
    }

    if (scanResult! is ScanResultChannelSubscribe) {
      return UI.box(
        padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
        context: context,
        child: ChannelScannerResultChannelSubscribe(value: scanResult! as ScanResultChannelSubscribe),
      );
    }

    if (scanResult! is ScanResultError) {
      return UI.box(
        padding: EdgeInsets.fromLTRB(16, 32, 16, 8),
        context: context,
        child: Center(
          child: Column(
            spacing: 32,
            children: [
              Icon(FontAwesomeIcons.solidTriangleExclamation, size: 64, color: Colors.red[900]),
              Text((scanResult! as ScanResultError).message, textAlign: TextAlign.center),
            ],
          ),
        ),
      );
    }

    return UI.box(
      padding: EdgeInsets.fromLTRB(16, 32, 16, 8),
      context: context,
      child: Center(
        child: Column(
          spacing: 32,
          children: [
            Icon(FontAwesomeIcons.solidTriangleExclamation, size: 64, color: Colors.red[900]),
            Text("Please scan a Channel QR Code to subscribe to it", style: TextStyle(fontStyle: FontStyle.italic), textAlign: TextAlign.center),
          ],
        ),
      ),
    );
  }
}