import 'package:fcs/domain/entities/pickup.dart';
import 'package:fcs/helpers/theme.dart';

import 'package:fcs/pages/pickup/model/pickup_model.dart';
import 'package:fcs/pages/pickup/pickup_list_row.dart';
import 'package:fcs/pages/widgets/barcode_scanner.dart';
import 'package:flutter/material.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';
import 'package:provider/provider.dart';

Future<Pickup?> searchPickup(BuildContext context,
        {CallbackPickupSelect? callbackPickupSelect}) async =>
    await showSearch<Pickup>(
      context: context,
      delegate:
          PackageSearchDelegate(callbackPickupSelect: callbackPickupSelect),
    );

class PackageSearchDelegate extends SearchDelegate<Pickup> {
  final CallbackPickupSelect? callbackPickupSelect;

  PackageSearchDelegate({this.callbackPickupSelect});

  @override
  String get searchFieldLabel => 'Search by Pickup Number';

  @override
  ThemeData appBarTheme(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return theme.copyWith(
      appBarTheme: AppBarTheme(color: primaryColor),
      inputDecorationTheme: InputDecorationTheme(
          border: InputBorder.none,
          hintStyle: TextStyle(
              color: theme.primaryTextTheme.caption?.color, fontSize: 14)),
      textTheme: TextTheme(
          headline1: TextStyle(
              color: theme.primaryTextTheme.headline1?.color,
              fontSize: 16,
              backgroundColor: primaryColor)),
      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, new Pickup()),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    final pickupModel = Provider.of<PickupModel>(context);
    return FutureBuilder(
        future: pickupModel.searchPickup(query),
        builder: (context, AsyncSnapshot<List<Pickup>> 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((e) {
                  return PickupListRow(
                    pickup: e,
                    callbackPickupSelect: callbackPickupSelect,
                  );
                }).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(SimpleLineIcons.direction, 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');
    }
  }
}
