import 'dart:async';
import 'dart:convert';

import 'package:boilerplate/core/di/injection_init.dart';
import 'package:boilerplate/core/styles/my_colors.dart';
import 'package:boilerplate/core/styles/my_dimensions.dart';
import 'package:boilerplate/presentation/bloc/home/home_bloc.dart';
import 'package:boilerplate/presentation/bloc/notification/notification_count/notification_count_cubit.dart';
import 'package:boilerplate/presentation/widgets/base_container.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:http/http.dart' as http;

import 'package:flutter/material.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../core/i18n/translations.g.dart';
import '../../../core/styles/my_font.dart';
import '../../../core/utils/authentication_util.dart';
import '../../../core/utils/navigator_util.dart';
import '../../../core/utils/shared_preferences_util.dart';
import '../../../data/models/userex/userexmodel.dart';
import '../../../domain/entities/flavor/flavor_data.dart';
import '../../bloc/notification/notification_count/notification_count_state.dart';
import '../../widgets/ipm_image.dart';
import '../../widgets/ipm_search_field.dart';
import '../../widgets/ipm_title_text.dart';
import '../../widgets/notification_count.dart';
import '../contact_us/contact_us_page.dart';
import '../landing/landing_screen.dart';
import '../notification/notifications_screen.dart';
import '../products/favorite/favorite_list_screen.dart';
import '../products/list/product_list_screen.dart';
import '../user_experience/user_ex_list_page.dart';
import '../user_experience/user_experience_screen.dart';
import '../web_view/web_view_screen.dart';
import 'widgets/home_all_idea.dart';
import 'widgets/home_banner.dart';
import 'widgets/home_business_matching.dart';
import 'widgets/home_categories.dart';
import 'widgets/home_new_idea.dart';
import 'widgets/home_product_type.dart';
import 'widgets/home_serch.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with AutomaticKeepAliveClientMixin {
  final GlobalKey<RefreshIndicatorState> _refreshKey =
      GlobalKey<RefreshIndicatorState>();
  final TextEditingController searchCtrl = TextEditingController();
  UserExModel? userExModel;
  late final HomeBloc _bloc;
  late final TextEditingController controller;
  late String lang = '';
  final pref = getIt.get<SharedPreferencesUtil>();
  late Timer _timer;
  int _start = 1;
  bool loading = true;
  @override
  void initState() {
    super.initState();

    _bloc = getIt.get<HomeBloc>();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _bloc.add(GetHomeDataEvent());
      BlocProvider.of<NotificationCountCubit>(context).getNotificationCount();
    });
    startTimer();
    getLang();
    getUserEx();
  }

  void startTimer() {
    const oneSec = const Duration(seconds: 1);
    _timer = new Timer.periodic(
      oneSec,
      (Timer timer) => setState(
        () {
          if (_start < 1) {
            setState(() {
              loading = false;
            });
            timer.cancel();
          } else {
            _start = _start - 1;
          }
        },
      ),
    );
  }

  Future<bool> _onRefresh() async {
    _bloc.add(GetHomeDataEvent());
    var state =
        await _bloc.stream.firstWhere((state) => state is GetDataSuccessState);
    return state is GetDataSuccessState;
  }

  @override
  void dispose() {
    searchCtrl.dispose();
    _bloc.close();

    super.dispose();
  }

  getLang() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      lang = prefs.getString('lang').toString();
    });
    await FirebaseAnalytics.instance.logScreenView(screenName: 'HomePage');
    await getUserEx();
  }

  @override
  Widget build(BuildContext context) {
    // getLang();
    super.build(context);
    return BlocProvider.value(
      value: _bloc,
      child: BaseContainer(
        child: loading == true
            ? Center(
                child: CircularProgressIndicator(
                  color: Colors.redAccent,
                ),
              )
            : Stack(
                children: [
                  SizedBox(
                    height: MyDimens.dimen375,
                    child: Image.asset(
                      'assets/images/img_home_header_bg.png',
                      fit: BoxFit.fitHeight,
                    ),
                  ),
                  Column(
                    children: [
                      // HomeSearch(controller: searchCtrl),
                      Container(
                        padding: EdgeInsets.only(
                          top: MediaQuery.of(context).padding.top +
                              MyDimens.dimen16,
                          left: MyDimens.dimen16,
                          right: MyDimens.dimen16,
                          bottom: MyDimens.dimen18,
                        ),
                        child: Column(
                          children: [
                            Image.asset(
                              'assets/images/img_ipm_logo.png',
                              width: MyDimens.dimen100,
                            ),
                            SizedBox(height: MyDimens.dimen16),
                            Row(
                              children: [
                                Expanded(
                                  child: IPMSearchField(
                                    controller: searchCtrl,
                                    checkHome: "YES",
                                    hintText: lang == 'th' || lang == ""
                                        ? AppLocalizations.home.search_product
                                        : AppLocalizations
                                            .home.search_product_en,
                                    onFieldSubmitted: (v) {
                                      NavigatorUtil.pushToPage(
                                          ProductListScreen(searchTxt: v));
                                    },
                                  ),
                                ),
                                Column(
                                  children: [
                                    Row(
                                      children: [
                                        GestureDetector(
                                          onTap: () {
                                            print(getIt
                                                    .get<AppFlavorData>()
                                                    .webDomain +
                                                '/me?tabs=tabs-4#tabs-4&lang=${lang}&mobile=1');
                                            NavigatorUtil.pushToPage(
                                              ContactUsPage(
                                                title: lang == "th" ||
                                                        lang == ""
                                                    ? AppLocalizations.menu.cart
                                                    : AppLocalizations
                                                        .menu.cart_en,
                                                // url: getIt
                                                //         .get<AppFlavorData>()
                                                //         .webDomain +
                                                //     '/me?tabs=tabs-4#tabs-4&lang=${lang}&mobile=1'
                                                url:
                                                    'https://ipmart.ipthailand.go.th/me?mobile=1&tabs=tabs-4#tabs-4&lang=${lang}',
                                              ),
                                            );
                                          },
                                          child: pref.getInt(
                                                      SharedPreferencesUtil
                                                          .keyUserId) ==
                                                  null
                                              ? Container()
                                              : Container(
                                                  margin: EdgeInsets.symmetric(
                                                      horizontal:
                                                          MyDimens.dimen8),
                                                  child: Icon(
                                                    Icons
                                                        .shopping_cart_outlined,
                                                    color: Colors.white,
                                                    size: 27,
                                                  ),
                                                ),
                                        ),
                                        GestureDetector(
                                          onTap: () {
                                            AuthenticationUtil.checkHasUser(() {
                                              NavigatorUtil.pushToPage(
                                                  FavoritesScreen());
                                            });
                                          },
                                          child: pref.getInt(
                                                      SharedPreferencesUtil
                                                          .keyUserId) ==
                                                  null
                                              ? Container()
                                              : Container(
                                                  margin: EdgeInsets.symmetric(
                                                      horizontal:
                                                          MyDimens.dimen8),
                                                  child: SvgPicture.asset(
                                                    'assets/icons/ic_favorite.svg',
                                                    fit: BoxFit.fitWidth,
                                                  ),
                                                ),
                                        ),
                                        GestureDetector(
                                          onTap: () {
                                            setState(() {
                                              final userId = pref.getInt(
                                                  SharedPreferencesUtil
                                                      .keyUserId);
                                              final _flavor =
                                                  getIt.get<AppFlavorData>();

                                              if (pref.getInt(
                                                      SharedPreferencesUtil
                                                          .keyUserId) ==
                                                  null) {
                                                NavigatorUtil.pushToPage(
                                                  WebViewScreen(
                                                    url: _flavor.webDomain +
                                                        '/login?mobile=1&lang=${pref.getString('lang')}',
                                                    title: 'ลงชื่อเข้าใช้',
                                                  ),
                                                );
                                              } else {
                                                pref.putInt(
                                                    SharedPreferencesUtil
                                                        .keyNotificationCount,
                                                    0);

                                                FlutterAppBadger.removeBadge();
                                                FlutterAppBadger
                                                    .updateBadgeCount(0);
                                                pref.putInt(
                                                    SharedPreferencesUtil
                                                        .keyNotificationCount,
                                                    0);
                                                NavigatorUtil.pushToPage(
                                                    NotificationsScreen());
                                              }
                                              // AuthenticationUtil.checkHasUser(() {
                                              //   NavigatorUtil.pushToPage(
                                              //       NotificationsScreen());
                                              // });
                                            });
                                          },
                                          child: pref.getInt(
                                                      SharedPreferencesUtil
                                                          .keyUserId) ==
                                                  null
                                              ? Container()
                                              : Stack(
                                                  clipBehavior: Clip.none,
                                                  children: [
                                                    Container(
                                                      margin:
                                                          EdgeInsets.symmetric(
                                                              horizontal:
                                                                  MyDimens
                                                                      .dimen8),
                                                      child: SvgPicture.asset(
                                                        'assets/icons/ic_notification.svg',
                                                        fit: BoxFit.fitWidth,
                                                      ),
                                                    ),
                                                    BlocBuilder<
                                                        NotificationCountCubit,
                                                        NotificationCountState>(
                                                      builder:
                                                          (context, state) {
                                                        if (state
                                                            is HaveNotificaitonCountState) {
                                                          return Positioned(
                                                            top: -(MyDimens
                                                                .dimen2),
                                                            right:
                                                                MyDimens.dimen8,
                                                            child:
                                                                NotificationCount(
                                                                    count: 1),
                                                          );
                                                        } else {
                                                          return Container();
                                                        }
                                                      },
                                                    ),
                                                  ],
                                                ),
                                        ),
                                      ],
                                    ),
                                    GestureDetector(
                                      onTap: () async {
                                        SharedPreferences prefs =
                                            await SharedPreferences
                                                .getInstance();

                                        setState(() {
                                          if (lang == "" ||
                                              lang == null ||
                                              lang == "en") {
                                            prefs.setString('lang', 'th');
                                          } else {
                                            prefs.setString('lang', 'en');
                                          }

                                          NavigatorUtil.popToFirstAndReplace(
                                              LandingScreem());
                                        });
                                      },
                                      child: Container(
                                        width: 170,
                                        margin:
                                            EdgeInsets.only(left: 8, top: 8),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Spacer(),
                                            Image.asset(
                                              'assets/images/icons8-globe-48.png',
                                              width: 30,
                                              height: 30,
                                            ),
                                            SizedBox(
                                              width: 8,
                                            ),
                                            Text(
                                              'ไทย',
                                              style: MyFont.medium14.copyWith(
                                                  color: lang == 'th'
                                                      ? Colors.white
                                                      : Colors.white60),
                                            ),
                                            SizedBox(
                                              width: 8,
                                            ),
                                            Text(
                                              '|',
                                              style: MyFont.medium14.copyWith(
                                                  color: Colors.white),
                                            ),
                                            SizedBox(
                                              width: 8,
                                            ),
                                            Text(
                                              'EN',
                                              style: MyFont.medium14.copyWith(
                                                  color: lang == 'en'
                                                      ? Colors.white
                                                      : Colors.white60),
                                            ),
                                            SizedBox(
                                              width: 8,
                                            ),
                                            Spacer(),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: RefreshIndicator(
                          key: _refreshKey,
                          onRefresh: _onRefresh,
                          color: MyColor.orange,
                          child: SingleChildScrollView(
                            child: Column(
                              children: [
                                HomeBanner(),
                                Container(
                                  color: Colors.white,
                                  child: Column(
                                    children: [
                                      Container(
                                        child: lang == "th" || lang == null
                                            ? IPMTitleText(
                                                title1: AppLocalizations
                                                    .products
                                                    .explore_idea_th_title1,
                                                title2: AppLocalizations
                                                    .products
                                                    .explore_idea_th_title2,
                                              )
                                            : IPMTitleText(
                                                title1: AppLocalizations
                                                    .products
                                                    .explore_idea_en_title1,
                                                title2: AppLocalizations
                                                    .products
                                                    .explore_idea_en_title2,
                                              ),
                                        alignment: Alignment.centerLeft,
                                        margin:
                                            EdgeInsets.only(left: 16, top: 16),
                                      ),
                                      HomeProductType(),
                                      HomeNewIdea(),
                                      HomeBusinessMatching(myLang: lang),
                                      HomeCategories(),
                                      Row(
                                        children: [
                                          Container(
                                            child: lang == "th" || lang == null
                                                ? IPMTitleText(
                                                    title1: AppLocalizations
                                                        .home.user_ex_th_title1,
                                                    title2: AppLocalizations
                                                        .home.user_ex_th_title2,
                                                  )
                                                : IPMTitleText(
                                                    title1: AppLocalizations
                                                        .home.user_ex_en_title1,
                                                    title2: AppLocalizations
                                                        .home.user_ex_en_title2,
                                                  ),
                                            alignment: Alignment.centerLeft,
                                            margin: EdgeInsets.only(
                                                left: 16, top: 16),
                                          ),
                                          Spacer(),
                                          GestureDetector(
                                            onTap: () async {
                                              NavigatorUtil.pushToPage(
                                                  UserExperienceListScreen());
                                              if (await canLaunchUrl(Uri.parse(
                                                  "https://eservice.ipthailand.go.th/login"))) {
                                                await launchUrl(Uri.parse(
                                                    "https://eservice.ipthailand.go.th/login"));
                                              }
                                              // final _url = Uri.parse(
                                              //     "https://eservice.ipthailand.go.th/login");
                                              // if (!await launchUrl(_url,
                                              //     mode: LaunchMode
                                              //         .externalApplication)) {
                                              //   // <--
                                              //   throw Exception(
                                              //       'Could not launch $_url');
                                              // }
                                            },
                                            child: Container(
                                              height: MyDimens.dimen36,
                                              width: MyDimens.dimen80,
                                              child: Text(
                                                'ดูทั้งหมด' ?? '',
                                                style:
                                                    MyFont.regular16.copyWith(
                                                  color: Colors.white,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                                maxLines: 2,
                                              ),
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(6),
                                                color: MyColor.orange,
                                                boxShadow: [],
                                              ),
                                              alignment: Alignment.center,
                                              margin: EdgeInsets.only(
                                                  left: 16, top: 16, right: 16),
                                            ),
                                          ),
                                        ],
                                      ),
                                      userExModel == null
                                          ? CircularProgressIndicator()
                                          : Container(
                                              height: MyDimens.dimen360,
                                              margin: EdgeInsets.only(
                                                  left: 0,
                                                  right: 16,
                                                  top: 8,
                                                  bottom: 35),
                                              child: ListView.builder(
                                                shrinkWrap: true,
                                                scrollDirection:
                                                    Axis.horizontal,
                                                itemCount: userExModel!
                                                    .result!.data!.length,
                                                itemBuilder:
                                                    (BuildContext context,
                                                            int index) =>
                                                        GestureDetector(
                                                  onTap: () {
                                                    NavigatorUtil.pushToPage(
                                                        UserExperienceScreen(
                                                            id: userExModel!
                                                                .result!
                                                                .data![index]
                                                                .id
                                                                .toString()));
                                                  },
                                                  child: Container(
                                                    margin: EdgeInsets.only(
                                                        left: 16, right: 16),
                                                    child: Card(
                                                      shadowColor:
                                                          Colors.black87,
                                                      elevation: 8.0,
                                                      shape:
                                                          RoundedRectangleBorder(
                                                        borderRadius:
                                                            BorderRadius
                                                                .circular(15.0),
                                                      ),
                                                      child: Column(
                                                        children: [
                                                          Container(
                                                            margin:
                                                                EdgeInsets.only(
                                                                    left: 8,
                                                                    right: 8,
                                                                    top: MyDimens
                                                                        .dimen12,
                                                                    bottom: 16),
                                                            width: MyDimens
                                                                .dimen200,
                                                            height: MyDimens
                                                                .dimen120,
                                                            decoration:
                                                                BoxDecoration(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          8),
                                                            ),
                                                            child: ClipRRect(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          8),
                                                              child: IPMImage(
                                                                url: userExModel!
                                                                        .result!
                                                                        .data![
                                                                            index]
                                                                        .cover ??
                                                                    '',
                                                                fit: BoxFit
                                                                    .cover,
                                                              ),
                                                            ),
                                                          ),
                                                          Container(
                                                            margin: EdgeInsets.only(
                                                                left: MyDimens
                                                                    .dimen8,
                                                                right: MyDimens
                                                                    .dimen8,
                                                                top: 0,
                                                                bottom: 0),
                                                            width: MyDimens
                                                                .dimen200,
                                                            child: Text(
                                                              userExModel!
                                                                      .result!
                                                                      .data![
                                                                          index]
                                                                      .postTitle ??
                                                                  '',
                                                              style: MyFont
                                                                  .bold16
                                                                  .copyWith(
                                                                color: MyColor
                                                                    .headerColor,
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                              maxLines: 1,
                                                            ),
                                                          ),
                                                          Container(
                                                            margin: EdgeInsets.only(
                                                                left: MyDimens
                                                                    .dimen8,
                                                                right: MyDimens
                                                                    .dimen8,
                                                                top: MyDimens
                                                                    .dimen4,
                                                                bottom: MyDimens
                                                                    .dimen4),
                                                            width: MyDimens
                                                                .dimen200,
                                                            child: Text(
                                                              userExModel!
                                                                      .result!
                                                                      .data![
                                                                          index]
                                                                      .postName ??
                                                                  '',
                                                              style: MyFont
                                                                  .regular14
                                                                  .copyWith(
                                                                color: MyColor
                                                                    .headerColor,
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                              maxLines: 1,
                                                            ),
                                                          ),
                                                          Container(
                                                            margin: EdgeInsets.only(
                                                                left: MyDimens
                                                                    .dimen8,
                                                                right: MyDimens
                                                                    .dimen8,
                                                                top: 0,
                                                                bottom: MyDimens
                                                                    .dimen8),
                                                            width: MyDimens
                                                                .dimen200,
                                                            child: Text(
                                                              userExModel!
                                                                      .result!
                                                                      .data![
                                                                          index]
                                                                      .postExcerpt ??
                                                                  '',
                                                              style: MyFont
                                                                  .regular14
                                                                  .copyWith(
                                                                color: MyColor
                                                                    .grey,
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                              maxLines: 2,
                                                            ),
                                                          ),
                                                          Container(
                                                            margin: EdgeInsets.only(
                                                                left: MyDimens
                                                                    .dimen8,
                                                                right: MyDimens
                                                                    .dimen8,
                                                                top: 0,
                                                                bottom: MyDimens
                                                                    .dimen8),
                                                            alignment: Alignment
                                                                .centerRight,
                                                            width: MyDimens
                                                                .dimen200,
                                                            child: Text(
                                                              lang == "th"
                                                                  ? 'อ่านต่อ...'
                                                                  : 'read more...',
                                                              style: MyFont
                                                                  .regular14
                                                                  .copyWith(
                                                                color: MyColor
                                                                    .orange,
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                              maxLines: 2,
                                                            ),
                                                          ),
                                                          Row(
                                                            children: [
                                                              Container(
                                                                margin: EdgeInsets
                                                                    .only(
                                                                        left: 8,
                                                                        right:
                                                                            8,
                                                                        top: 0,
                                                                        bottom:
                                                                            16),
                                                                alignment:
                                                                    Alignment
                                                                        .topLeft,
                                                                width: MyDimens
                                                                    .dimen52,
                                                                height: MyDimens
                                                                    .dimen52,
                                                                decoration:
                                                                    BoxDecoration(
                                                                  borderRadius:
                                                                      BorderRadius
                                                                          .circular(
                                                                              8),
                                                                ),
                                                                child:
                                                                    ClipRRect(
                                                                  borderRadius:
                                                                      BorderRadius
                                                                          .circular(
                                                                              8),
                                                                  child:
                                                                      IPMImage(
                                                                    url: userExModel!
                                                                            .result!
                                                                            .data![index]
                                                                            .image ??
                                                                        '',
                                                                    fit: BoxFit
                                                                        .cover,
                                                                  ),
                                                                ),
                                                              ),
                                                              Column(
                                                                children: [
                                                                  Container(
                                                                    margin: EdgeInsets.only(
                                                                        left: 0,
                                                                        right: MyDimens
                                                                            .dimen8,
                                                                        top: 0,
                                                                        bottom:
                                                                            2),
                                                                    width: MyDimens
                                                                        .dimen145,
                                                                    child: Text(
                                                                      userExModel!
                                                                              .result!
                                                                              .data![index]
                                                                              .attributeName ??
                                                                          '',
                                                                      style: MyFont
                                                                          .regular14
                                                                          .copyWith(
                                                                        color: Colors
                                                                            .black,
                                                                        overflow:
                                                                            TextOverflow.ellipsis,
                                                                      ),
                                                                      maxLines:
                                                                          2,
                                                                    ),
                                                                  ),
                                                                  Container(
                                                                    margin: EdgeInsets.only(
                                                                        left: 0,
                                                                        right: MyDimens
                                                                            .dimen8,
                                                                        top: 0,
                                                                        bottom:
                                                                            0),
                                                                    width: MyDimens
                                                                        .dimen145,
                                                                    child: Text(
                                                                      userExModel!
                                                                              .result!
                                                                              .data![index]
                                                                              .attributePosition ??
                                                                          '',
                                                                      style: MyFont
                                                                          .regular14
                                                                          .copyWith(
                                                                        color: MyColor
                                                                            .grey,
                                                                        overflow:
                                                                            TextOverflow.ellipsis,
                                                                      ),
                                                                      maxLines:
                                                                          2,
                                                                    ),
                                                                  ),
                                                                ],
                                                              ),
                                                            ],
                                                          ),
                                                        ],
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      )
                    ],
                  )
                ],
              ),
      ),
    );
  }

  getUserEx() async {
    var _model;
    var _fail;
    var result;
    String url = "https://ipmart.ipthailand.go.th/api/user-exp";
    // Object body = {
    //   "id": "${id}",
    // };
    // print(body);
    var response = await http.get(
      Uri.parse(url),
    );
    // print(url);
    // print("encrytion body=> ${body}");
    var res = json.decode(response.body);
    print("response.body => ${res}");
    print("response.body encrytion=> ${response.body}");
    print("================================");
    // if (response.statusCode == 200) {
    _model = await UserExModel.fromJson(
        json.decode(utf8.decode(response.bodyBytes)));
    userExModel = _model;
  }

  HorizList() {
    return Column(
      children: [],
    );
  }

  @override
  bool get wantKeepAlive => true;
}
