

import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import '../general/smooth_star_rating.dart';

import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/comment.dart';
import '../../models/product_image.dart';
import '../../routes.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/util_web.dart' if (dart.library.io) '../../utils/util_io.dart';
import '../../utils/utils.dart';


class MobileNewComment extends StatefulWidget {
  final Key? key;
  final int orderId;
  const MobileNewComment(this.orderId, {this.key});

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

}

class MobileNewCommentState extends State<MobileNewComment> {
  Comment comment;

  bool _showProgress;

  double _progress;

  double rating;

  bool isSubmitting = false;

  final TextEditingController commentController = new TextEditingController();

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

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: (){
            Navigator.of(context).pop();
          },
        ),
        title: Text(S.of(context).comment),
        backgroundColor: Theme.of(context).primaryColor,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.check),
            onPressed: () {
              _submit();
            },
          ),
        ],
      ),
      body: _buildBody(context),
    );
  }

  @override
  void initState() {
    super.initState();
    _showProgress = false;
    _progress = 0.0;
    setState(() {
      rating = 5.0;
    });
    eventBus.on<OnUploadCommentImageProgressEvent>().listen((event) {
      if (mounted) {
        setState(() {
          _showProgress = event.showProgress;
          _progress = event.progress;
        });
      }
    });
    eventBus.on<OnCommentUpdatedEvent>().listen((event) {
      if (mounted) {
        setState(() {
          comment = event.comment;
        });
      }
    });
  }

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

  Widget _buildBody(BuildContext context) {

    return ListView.builder(
      itemCount: 3,
      itemBuilder: (BuildContext context, int position) {

        switch(position) {
          case 0:
            return Container(
              padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 16.0, bottom: 16.0),
              child: SmoothStarRating(
                allowHalfRating: false,
                onRated: (v) {
                  setState(() {
                    rating = v;
                  });
                },
                starCount: 5,
                rating: rating,
                size: 40.0,
                filledIconData: Icons.star,
                color: Colors.green,
                borderColor: Colors.green,
                spacing: 0.0,
              ),
            );
            break;
          case 1:
            return Container(
              padding: EdgeInsets.only(top: 0.0, bottom: 10.0, left: 16.0, right: 16.0),
              child: TextField(
                controller: commentController,
                keyboardType: TextInputType.multiline,
                maxLines: 10,
                maxLength: 500,
                decoration: new InputDecoration(
                  border: new OutlineInputBorder(
                    borderRadius: const BorderRadius.all(
                      const Radius.circular(12.0),
                    ),
                  ),
                  filled: true,
                  hintStyle: new TextStyle(color: Colors.grey[800]),
                  hintText: S.of(context).input_your_comment,
                  fillColor: Colors.white70,
                ),
              ),
            );
            break;
          case 2:
            return Container(
              padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
              child: commentImages(context),
            );
            break;
        }
        return null;
      }
    );
  }

  Widget commentImages(BuildContext mainContext) {
    Row row = Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[],
    );

    if (comment != null && comment.images.length > 0) {
      for (ProductImage image in comment.images) {
        row.children.add(
          Container(
            padding: EdgeInsets.only(left: 10.0),
            child: Badge(
              position: BadgePosition.topEnd(top: -10.0, end: -6.0),
              badgeContent: Container(
                child: Text(
                  '-',
                  style: TextStyle(
                    fontSize: 14.0,
                    color: Colors.white,
                  ),
                ),
              ),
              child: GestureDetector(
                child: Container(
                  child: Util.showImage('https:${image.image}',
                    width: 60.0,
                    height: 60.0,
                    fit: BoxFit.fill,
                    errorWidget: (mainContext, url, error) => Icon(
                      Icons.image,
                      size: 60.0,
                      color: Colors.grey,
                    ),
                  ),
                ),
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text(S.of(context).warning),
                        content: Text(S.of(context).are_you_sure_to_remove_the_picture),
                        actions: <Widget>[
                          TextButton(
                            child: Text(S.of(context).cancel),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            style: TextButton.styleFrom(
                              backgroundColor: Theme.of(context).primaryColor,
                            ),
                          ),
                          TextButton(
                            child: Text(S.of(context).yes_i_am_sure),
                            onPressed: () {
                              Navigator.of(context).pop();
                              _deleteImage(image.id);
                            },
                          ),
                        ],
                      );
                    }
                  );
                },
              ),
            ),
          ),
        );
      }
    }

    row.children.add(
      GestureDetector(
        child: Container(
          margin: EdgeInsets.only(left: 10,),
          child: Icon(
            Icons.add,
            size: 60.0,
            color: comment == null || comment.images.length < 3 ? Colors.lightBlue : Colors.black12,
          ),
          decoration: BoxDecoration(
            color: Colors.white70,
            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,
              ),
            ),
          ),
        ),
        onTap: () {
          if (comment == null || comment.images.length < 3) {
            showDialog(
                context: mainContext,
                barrierDismissible: true,
                builder: (BuildContext context) {
                  return Util().getPicture(mainContext, store.state.user,
                      commentId: comment != null ? comment.id : 0,
                      orderId: widget.orderId);
                }
            );
          }
        },
      ),
    );

    return Stack(
      children: <Widget>[
        Positioned(
          top: 0.0,
          left: 0.0,
          right: 0.0,
          bottom: -100.0,
          child: Visibility(
            visible: _showProgress,
            child: LinearPercentIndicator(
              lineHeight: 10.0,
              percent: _progress,
              backgroundColor: Colors.transparent,
              progressColor: Colors.blue,
              linearStrokeCap: LinearStrokeCap.butt,
            ),
          ),
        ),
        Positioned(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(bottom: 16.0),
                child: Text(
                  S.of(context).add_pictures,
                  style: TextStyle(
                    fontSize: 17.0,
                    color: Colors.black38,
                  ),
                ),
              ),
              row,
            ],
          ),
        ),
      ],
    );
  }
  
  void _deleteImage(int imageId) {
    HttpUtil.httpDelete('v1/comment-image/${imageId}', (response) {
      if (mounted) {
        setState(() {
          comment = Comment.fromJson(response.data);
        });
      }
    },
      queryParameters: {
        'comment_id': comment != null ? comment.id : 0,
      },
    ).catchError((error) {
      Utils.showMessageDialog(context, error);
    });
  }

  void _submit() {
    if (commentController.text.isEmpty) {
      Utils.showMessageDialog(context, Exception(S.of(context).comment_empty));
    } else {
      HttpUtil.httpPost('v1/add-comment', (response) {
        if (isSubmitting) {
          isSubmitting = false;
          Navigator.of(context).pop();
        }
        Utils.showMessageDialog(context,
          Exception(S.of(context).thank_you_for_your_comment),
          title: S.of(context).success,
          onOk: () {
            Routes.router.navigateTo(context, '/orders', replace: true, clearStack: true);
          }
        );
      },
        isFormData: true,
        body: {
          'order_id': widget.orderId,
          'comment_id': comment != null ? comment.id : 0,
          'content': commentController.text,
          'rating': rating.round(),
        },
      ).catchError((error) {
        if (isSubmitting) {
          isSubmitting = false;
          Navigator.of(context).pop();
        }
        Utils.showMessageDialog(context, error);
      });
      isSubmitting = true;
      Utils.showSubmitDialog(context);
    }
  }
}