import 'package:fcs/domain/entities/carton.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/carton/model/carton_model.dart';
import 'package:fcs/pages/widgets/barcode_scanner.dart';
import 'package:fcs/pages/widgets/local_popup_menu_button.dart';
import 'package:fcs/pages/widgets/local_popupmenu.dart';
import 'package:fcs/pagination/paginator_listview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';
import 'package:provider/provider.dart';

import 'carton_list_row.dart';

typedef CallbackCartonSelect(Carton carton);

Future<Carton?> searchCarton(BuildContext context,
        {CallbackCartonSelect? callbackCartonSelect}) async =>
    await showSearch<Carton>(
      context: context,
      delegate: PartSearchDelegate(callbackCartonSelect: callbackCartonSelect),
    );

class PartSearchDelegate extends SearchDelegate<Carton> {
  final CallbackCartonSelect? callbackCartonSelect;
  PartSearchDelegate({this.callbackCartonSelect});

  @override
  String get searchFieldLabel => 'Search by Carton 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) {
    var boxModel = Provider.of<CartonModel>(context);
    final popupMenu =
        StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
      return LocalPopupMenuButton(
          popmenus: [
            LocalPopupMenu(
                id: 1,
                textKey: "box.weight",
                selected: boxModel.selectedIndexFilter == 1),
            LocalPopupMenu(
                id: 2,
                textKey: "box.name",
                selected: boxModel.selectedIndexFilter == 2)
          ],
          popupMenuCallback: (p) => setState(() {
                boxModel.selectedIndexFilter = p.id;
              }));
    });

    return [
      IconButton(
        icon: Icon(MaterialCommunityIcons.barcode_scan,
            size: 30, color: Colors.white),
        onPressed: () => _scan(context),
      ),
      popupMenu,
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () => query = '',
      ),
    ];
  }

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

  @override
  Widget buildResults(BuildContext context) {
    final cartonModel = Provider.of<CartonModel>(context);
    return FutureBuilder(
        future: cartonModel.searchCarton(query),
        builder: (context, AsyncSnapshot<List<Carton>> 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) => CartonListRow(
                          key: ValueKey(u.id),
                          carton: u,
                          callbackCartonSelect: callbackCartonSelect,
                        ))
                    .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) {
    final cartonModel = Provider.of<CartonModel>(context);

    return Container(
      padding: EdgeInsets.only(top: 5),
      child: PaginatorListView<Carton>(
        paginatorListener: cartonModel.cartonsByFilter!,
        rowBuilder: (c) => CartonListRow(
          key: ValueKey(c.id),
          carton: c,
          callbackCartonSelect: callbackCartonSelect,
        ),
        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 {
      String? barcode = await scanBarcode();
      if (barcode != null) {
        query = barcode;
        showResults(context);
      }
    } catch (e) {
      print('error: $e');
    }
  }
}
