import 'package:barcode_scan/barcode_scan.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/package/model/package_model.dart';
import 'package:fcs/pages/package/package_list_row.dart';
import 'package:fcs/pages/widgets/barcode_scanner.dart';
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

Future<Package> searchPackage(BuildContext context,
        {CallbackPackageSelect callbackPackageSelect}) async =>
    await showSearch<Package>(
      context: context,
      delegate:
          PackageSearchDelegate(callbackPackageSelect: callbackPackageSelect),
    );

class PackageSearchDelegate extends SearchDelegate<Package> {
  final CallbackPackageSelect callbackPackageSelect;

  PackageSearchDelegate({this.callbackPackageSelect});

  @override
  String get searchFieldLabel => 'Search by Tracking ID/Customer Name';

  @override
  ThemeData appBarTheme(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return theme.copyWith(
      inputDecorationTheme: InputDecorationTheme(
          hintStyle: TextStyle(
              color: theme.primaryTextTheme.caption.color, fontSize: 14)),
      textTheme: theme.textTheme.copyWith(
          title: theme.textTheme.title.copyWith(
              color: theme.primaryTextTheme.title.color, fontSize: 16)),
      primaryColor: primaryColor,
    );
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(MaterialCommunityIcons.barcode_scan,
            size: 30, color: Colors.white),
        onPressed: () => _scan(context),
      ),
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () => query = '',
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () => close(context, null),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    final packageModel = Provider.of<PackageModel>(context);
    return FutureBuilder(
        future: packageModel.searchPackage(query),
        builder: (context, AsyncSnapshot<List<Package>> snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data.length == 0) {
              return Container(
                child: Center(
                  child: Text(
                    "No result found",
                    textAlign: TextAlign.center,
                  ),
                ),
              );
            }
            return Container(
              padding: EdgeInsets.only(top: 15),
              child: ListView(
                children: snapshot.data
                    .map((u) => PackageListRow(
                          package: u,
                          callbackPackageSelect: callbackPackageSelect,
                        ))
                    .toList(),
              ),
            );
          } else if (snapshot.hasError) {
            return Container(
              child: Center(
                child: Text(
                  '${snapshot.error}',
                  textAlign: TextAlign.center,
                ),
              ),
            );
          } else {
            return Container(
              child: Center(
                child: CircularProgressIndicator(
                    valueColor:
                        new AlwaysStoppedAnimation<Color>(primaryColor)),
              ),
            );
          }
        });
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Container(
      child: Center(
        child: Opacity(
            opacity: 0.2,
            child: Icon(Octicons.package, size: 200, color: primaryColor)),
      ),
    );
  }

  _scan(BuildContext context) async {
    PermissionStatus permission =
        await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
    if (permission != PermissionStatus.granted) {
      Map<PermissionGroup, PermissionStatus> permissions =
          await PermissionHandler()
              .requestPermissions([PermissionGroup.camera]);
      if (permissions[PermissionGroup.camera] != PermissionStatus.granted) {
        showMsgDialog(context, "Error", "Camera permission is not granted");
        return null;
      }
    }

    try {
      // PickedFile pickedFile =
      //     await ImagePicker().getImage(source: ImageSource.camera);
      // FirebaseVisionImage visionImage =
      //     FirebaseVisionImage.fromFile(File(pickedFile.path));
      // final BarcodeDetector barcodeDetector =
      //     FirebaseVision.instance.barcodeDetector();
      // final List<Barcode> barcodes =
      //     await barcodeDetector.detectInImage(visionImage);
      // Barcode bc = barcodes.firstWhere((element) => true);
      // String barcode;
      // if (bc != null) barcode = bc.rawValue;
      String barcode = await scanBarcode();
      if (barcode != null) {
        query = barcode;
        showResults(context);
      }
    } catch (e) {
      print('error: $e');
    }
  }
}
