

import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/blog.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';
import '../../widgets/mobile/MobileBottomNav.dart';

class MobileBlog extends StatefulWidget {
  final int businessId;
  const MobileBlog({Key? key, this.businessId}) : super(key: key);

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

}

class MobileBlogState extends State<MobileBlog> {
  List<Blog> blogs;

  int _page = 1;
  int _pageCount = 1;

  bool _isLoading = false;
  bool _loadingFinish = false;

  RefreshController _refreshController = RefreshController(initialRefresh: true);

  void _onRefresh() {
    _page = 1;
    if (blogs != null) {
      blogs.clear();
    } else {
      blogs = [];
    }
    _refreshController.resetNoData();
    loadBlogs(true);
  }

  void _onLoadMore() {
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if (_pageCount > _page) {
      _page += 1;
      loadBlogs(false);
    } else {
      _refreshController.loadNoData();
    }
  }

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

    BuildContext mainContext = context;

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        title: Text(S.of(context).blog),
        backgroundColor: Theme.of(context).primaryColor,
        actions: [],
      ),
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode){
            Widget footer;
            if(mode == LoadStatus.idle) {
              footer = Text(S.of(context).pull_up_to_load_more);
            } else if (mode == LoadStatus.loading) {
              footer = CircularProgressIndicator();
            } else if (mode == LoadStatus.failed) {
              footer = Text(S.of(context).load_failed_retry);
            } else if (mode == LoadStatus.canLoading) {
              footer = Text(S.of(context).release_to_load_more);
            } else if (mode == LoadStatus.noMore) {
              footer = Text(S.of(context).no_more_record);
            } else {
              footer = Text('...');
            }
            return Container(
              height: 55.0,
              child: Center(child: footer,),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoadMore,
        child: _buildBody(),
      ),
      bottomNavigationBar: MobileBottomNav(currentIndex: 3,),
    );
  }

  @override
  void dispose() {
    _refreshController?.dispose();
    super.dispose();
  }

  Widget _buildBody() {
    if (blogs == null) {
      return SizedBox.shrink();
    }
    return ListView.builder(
        itemCount: blogs.length <= 1 ? 1 : blogs.length,
        itemBuilder: (BuildContext context, int i) {
          if (blogs.length <= 0) {
            return Container(
              padding: EdgeInsets.all(16.0),
              child: Center(
                child: Text(S.of(context).no_blog_yet),
              ),
            );
          } else {
            Blog blog = blogs[i];

            Widget w = Container(
              padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 16.0),
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                        color: Colors.black12,
                        width: 0.6,
                      )
                  )
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  (blog.thumbUrl != null) ?
                  Container(
                    padding: EdgeInsets.only(right: 10.0),
                    child: Util.showImage(
                      'https:${blog.thumbUrl}',
                      width: 80.0,
                      height: 80.0,
                    ),
                  ) : SizedBox.shrink(),
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          child: Text(
                            blog.title,
                            style: TextStyle(
                              fontSize: 19.0,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Container(
                          child: Text(
                            Utils.utcDatetimeStringToLocalDatetimeString(context, blog.createdAt),
                            style: TextStyle(
                              fontSize: 13.0,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );

            return GestureDetector(
              child: w,
              onTap: () {
                Routes.router.navigateTo(context, '/view-blog/${blog.id}');
              },
            );
          }
        }
    );
  }

  @override
  void initState() {
    super.initState();

    eventBus.on<OnTicketsUpdated>().listen((event) {
      if (mounted) {
        setState(() {
          blogs = null;
        });
      }
      _refreshController.requestRefresh();
    });
  }

  void loadBlogs(bool isRefresh) {
    _loadingFinish = false;
    HttpUtil.httpGet(
      'v1/blogs',
      businessId: widget.businessId,
      queryParameters: {
        'page': _page.toString(),
        'size': Constants.BLOG_PER_PAGE_MOBILE.toString()
      }
    ).then((value) {
      if (mounted) {
        if (isRefresh) {
          _refreshController.refreshCompleted();
        } else {
          _refreshController.loadComplete();
        }

        if (int.parse(value['currentPage'].toString()) >= int.parse(value['pageCount'].toString())) {
          _loadingFinish = true;
        }
        if (_loadingFinish) {
          _refreshController.loadNoData();
        }
        _page = int.parse(value['currentPage'].toString());
        _pageCount = int.parse(value['pageCount'].toString());

        setState(() {
          if (blogs == null) {
            blogs = [];
          }
          blogs.addAll((value['blogs'] as List).map((e) => Blog.fromJson(e)).toList());
        });
      }
    }).catchError((error) {
      if (mounted) {
        if (isRefresh) {
          _refreshController.refreshFailed();
        } else {
          _refreshController.loadFailed();
        }
        _isLoading = false;
        Utils.showMessageDialog(context, error, onOk: () {
          Navigator.of(context).pop();
          Navigator.of(context).pop();
        });
      }
    });
  }

}