
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_wisetronic/events/eventbus.dart';
import 'package:flutter_wisetronic/events/events.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';

import '../../constants.dart';
import '../../generated/l10n.dart';
import '../../models/user.dart';
import '../../routes.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/utils.dart';
import '../../widgets/general/breadcrumbs.dart';
import '../../utils/util_web.dart' if (dart.library.io) '../../utils/util_io.dart';

class DesktopNewTicket extends StatefulWidget {
  final Key? key;
  final int businessId;

  const DesktopNewTicket({this.key, int businessId}) :
        businessId = businessId ?? Constants.BUSINESS_ID;

  @override
  State<StatefulWidget> createState() {
    return DesktopNewTicketState();
  }
}

class DesktopNewTicketState extends State<DesktopNewTicket> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final issueMsgController = TextEditingController();

  bool onSubmitting = false;
  double submitProgress = 0.0;

  final List<Map<String, dynamic>> galleryImagesFlag = [
    {'show': false, 'progress': 0.0, 'path': ''},
    {'show': false, 'progress': 0.0, 'path': ''},
    {'show': false, 'progress': 0.0, 'path': ''},
  ];

  double sideSpace = 0;
  double mainSpace = 1200;

  @override
  void initState() {
    super.initState();
    onSubmitting = false;
  }

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    BuildContext mainContext = context;

    if (MediaQuery.of(context).size.width <= 1200) {
      mainSpace = MediaQuery.of(context).size.width;
      sideSpace = 0;
    } else {
      mainSpace = 1200;
      sideSpace = (MediaQuery.of(context).size.width - 1200) / 2;
    }

    Row row = Row(
      children: [
        Container(
          width: sideSpace,
        ),
        Container(
          width: mainSpace,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: mainSpace / 2,
                margin: EdgeInsets.only(top: 16.0, bottom: 16.0),
                padding: EdgeInsets.all(10.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(left: 16.0, top: 16.0, right: 16.0),
                      child: Text(
                        S.of(context).add_new_ticket,
                        style: TextStyle(
                            fontSize: 24.0,
                            color: Colors.black
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 12.0, left: 16.0, right: 16.0, bottom: 12.0),
                      child: Text(
                        S.of(context).add_new_ticket_desc,
                        style: TextStyle(
                          color: Colors.black54,
                          fontSize: 14.0,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                width: mainSpace / 2,
                margin: EdgeInsets.only(top: 16.0, bottom: 16.0),
                padding: EdgeInsets.all(10.0),
                decoration: BoxDecoration(
                  border: Border(
                    left: BorderSide(
                      width: 1.0,
                      color: Colors.black12,
                    ),
                  ),
                ),
                child: Column(
                  children: <Widget>[
                    Form(
                      key: _formKey,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0, bottom: 16.0),
                            child: TextFormField(
                              controller: issueMsgController,
                              keyboardType: TextInputType.multiline,
                              textCapitalization: TextCapitalization.sentences,
                              decoration: new InputDecoration(
                                enabledBorder: OutlineInputBorder(
                                  borderSide: BorderSide(
                                    width: 0.5,
                                    color: Colors.black12,
                                  ),
                                ),
                                focusedBorder: OutlineInputBorder(
                                  borderSide: BorderSide(
                                    width: 1.0,
                                    color: Colors.blue,
                                  ),
                                ),
                                labelText: S.of(context).your_question_issue,
                              ),
                              style: TextStyle(
                                  fontSize: 18.0
                              ),
                              autofocus: true,
                              validator: (String? value) {
                                if (value.trim().isEmpty) {
                                  return S.of(context).this_field_is_required;
                                }
                                return null;
                              },
                              maxLines: 5,
                              maxLength: 1000,
                            ),
                            decoration: BoxDecoration(
                              border: Border(
                                bottom: BorderSide(
                                  width: 1.0,
                                  color: Colors.black12,
                                ),
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0, bottom: 4.0),
                            child: Text(
                              S.of(context).attach_pictures,
                              style: TextStyle(
                                fontSize: 17.0,
                                color: Colors.black87,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(top: 4.0, left: 16.0, right: 16.0, bottom: 8.0),
                            child: Text(
                              S.of(context).attach_pictures_desc,
                              style: TextStyle(
                                fontSize: 14.0,
                                color: Colors.black38,
                              ),
                            ),
                          ),
                          Container(
                            height: 120.0,
                            padding: EdgeInsets.only(top: 8.0, left: 16.0, right: 16.0, bottom: 16.0),
                            child: SingleChildScrollView(
                              scrollDirection: Axis.horizontal,
                              child: galleryImages(mainContext),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: Container(
                        padding: EdgeInsets.only(top: 20.0, left: 16.0, right: 16.0, bottom: 20.0),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Theme.of(context).primaryColor,
                          ),
                          child: Text(
                            S.of(context).login,
                            style: TextStyle(
                              color: Colors.white,
                            ),
                          ),
                          onPressed: () {
                            _submit();
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Container(
          width: sideSpace,
        ),
      ],
    );

    Widget view = SingleChildScrollView(
      child: Stack(
        children: [
          Visibility(
            visible: onSubmitting,
            child: Container(
              height: MediaQuery.of(context).size.height - 100.0,
              color: Colors.grey.withOpacity(0.6),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(
                      strokeWidth: 10,
                      backgroundColor: Colors.green,
                      valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),
                      value: submitProgress,
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 16.0),
                      child: Text(
                        S.of(context).submitting_please_wait,
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Visibility(
            visible: !onSubmitting,
            child: row,
          ),
        ],
      ),
    );
    return view;
  }

  Widget galleryImages(BuildContext mainContext) {
    Row row = Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[],
    );
    for (int i = 0; i < 3; i++) {
      Map<String, dynamic> image = galleryImagesFlag[i];
      Widget imageWidget;

      imageWidget = GestureDetector(
        child: Stack(
          alignment: Alignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(right: 20.0),
              child: Util.showImage(
                  '${image['path']}',
                  width: 80.0,
                  height: 80.0,
                  fit: BoxFit.fill
              ),
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(
                    width: 0.5,
                    color: Colors.black12,
                  ),
                  bottom: BorderSide(
                    width: 0.5,
                    color: Colors.black12,
                  ),
                  left: BorderSide(
                    width: 0.5,
                    color: Colors.black12,
                  ),
                  right: BorderSide(
                    width: 0.5,
                    color: Colors.black12,
                  ),
                ),
              ),
            ),
            Visibility(
              visible: galleryImagesFlag[i]['show'],
              child: Container(
                padding: EdgeInsets.only(right: 20.0),
                child: CircularPercentIndicator(
                  radius: 60.0,
                  lineWidth: 10.0,
                  percent: galleryImagesFlag[i]['progress'],
                  center: new Text(
                    '${(galleryImagesFlag[i]['progress'] * 100.0).toStringAsFixed(1)}%',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 15.0,
                      color: Colors.white,
                    ),
                  ),
                  circularStrokeCap: CircularStrokeCap.round,
                  progressColor: Colors.orange,
                ),
              ),
            ),
          ],
        ),
        onTap: () {
          showDialog(
              context: mainContext,
              builder: (BuildContext context) {
                FocusScopeNode currentFocus = FocusScope.of(context);
                if (!currentFocus.hasPrimaryFocus) {
                  currentFocus.unfocus();
                }
                return Util().getPicture2(mainContext, i, (int imageId, String path){
                  setState(() {
                    galleryImagesFlag[imageId]['path'] = path;
                  });
                });
                return null;
              }
          );
        },
      );

      row.children.add(Badge(
        position: BadgePosition.topEnd(top: -10.0, end: 10.0),
        badgeContent: Container(
          child: GestureDetector(
            child: Icon(
              Icons.clear,
              color: Colors.white,
              size: 14.0,
            ),
            onTap: () {
              _deleteImage(mainContext, i);
            },
          ),
        ),
        showBadge: image['path'].isNotEmpty ? true : false,
        child: imageWidget,
      ));
    }
    return row;
  }

  void _deleteImage(BuildContext mainContext, int imageId) {
    showDialog(context: mainContext,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(S.of(context).warning),
          content: Text(S.of(context).are_you_sure_to_remove_the_picture),
          actions: [
            TextButton(
              child: Text(S.of(context).cancel),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            ElevatedButton(
              child: Text(S.of(context).yes_i_am_sure),
              style: ElevatedButton.styleFrom(
                backgroundColor: Theme.of(context).primaryColor,
              ),
              onPressed: () {
                Navigator.of(context).pop();
                setState(() {
                  galleryImagesFlag[imageId]['path'] = '';
                });
              },
            ),
          ],
        );
      },
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    eventBus.on<OnSubmitProgressEvent>().listen((event) {
      if (mounted) {
        setState(() {
          onSubmitting = event.showProgress;
          submitProgress = event.progress;
        });
      }
    });
  }

  void _submit() {
    final FormState form = _formKey.currentState;
    if (form.validate()) {
      setState(() {
        onSubmitting = true;
      });
      Util().createTicket(context, issueMsgController.text.trim(),
          galleryImagesFlag, (response){
            showDialog(context: context,
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text(S.of(context).success),
                    content: Text(S.of(context).ticket_created_success),
                    actions: <Widget>[
                      TextButton(
                        child: Text(S.of(context).ok),
                        onPressed: () {
                          Routes.router.navigateTo(context, '/my-support/${widget.businessId}', replace: true);
                        },
                      ),
                    ],
                  );
                });
          }, (error) {
            Utils.showMessageDialog(context, error, onOk: () {
              Routes.router.pop(context);
              Routes.router.pop(context);
            });
          });
    }
  }
}