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

import 'package:boilerplate/presentation/screen/user_experience/user_experience_screen.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../core/di/injection_init.dart';
import '../../../core/i18n/translations.g.dart';
import '../../../core/styles/my_colors.dart';
import '../../../core/styles/my_dimensions.dart';
import '../../../core/styles/my_font.dart';
import 'package:http/http.dart' as http;

import '../../../core/utils/navigator_util.dart';
import '../../../core/utils/shared_preferences_util.dart';
import '../../../data/models/userex/userexmodel.dart';
import '../../widgets/ipm_image.dart';
import '../../widgets/ipm_search_field.dart';
import '../../widgets/ipm_title_text.dart';

class UserExperienceListScreen extends StatefulWidget {
  const UserExperienceListScreen({super.key});

  @override
  State<UserExperienceListScreen> createState() =>
      _UserExperienceListScreenState();
}

class _UserExperienceListScreenState extends State<UserExperienceListScreen> {
  UserExModel? userExModel;
  late String lang = '';
  late Timer _timer;
  int _start = 1;
  late final ScrollController controller;
  final TextEditingController searchCtrl = TextEditingController();

  bool loading = true;
  bool loading2 = false;
  final pref = getIt.get<SharedPreferencesUtil>();
  @override
  void initState() {
    super.initState();
    startTimer();
    controller = ScrollController();

    getLang();
  }

  @override
  void dispose() {
    controller.dispose();
    searchCtrl.dispose();

    super.dispose();
  }

  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;
          }
        },
      ),
    );
  }

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: loading == true
          ? Center(
              child: CircularProgressIndicator(
                color: Colors.redAccent,
              ),
            )
          : SingleChildScrollView(
              child: Column(
                children: [
                  Row(
                    children: [
                      GestureDetector(
                        child: Container(
                          child: Icon(Icons.arrow_back_ios_new),
                          width: 40,
                          height: 40,
                          margin: EdgeInsets.only(
                            top: MyDimens.dimen80,
                            left: MyDimens.dimen16,
                          ),
                        ),
                        onTap: () {
                          Navigator.pop(context);
                        },
                      ),
                      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: MyDimens.dimen16, top: MyDimens.dimen80),
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(
                        top: MyDimens.dimen24,
                        left: MyDimens.dimen35,
                        right: MyDimens.dimen35),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(color: Colors.grey, spreadRadius: 1),
                      ],
                    ),
                    child: IPMSearchField(
                      controller: searchCtrl,
                      checkHome: "YES",
                      hintText: lang == 'th' || lang == ""
                          ? AppLocalizations.home.search_product
                          : AppLocalizations.home.search_product_en,
                      onFieldSubmitted: (v) {
                        setState(() {
                          loading2 = true;
                          startTimer2();
                          getUserEx(v);
                        });
                        // NavigatorUtil.pushToPage(
                        //     ProductListScreen(searchTxt: v));
                      },
                    ),
                  ),
                  loading2 == true
                      ? Container(
                          height: MediaQuery.of(context).size.height -
                              MyDimens.dimen300,
                          child: Center(
                            child: CircularProgressIndicator(
                              color: Colors.redAccent,
                            ),
                          ),
                        )
                      : userExModel!.result!.data!.length == 0
                          ? Container(
                              height: MediaQuery.of(context).size.height -
                                  MyDimens.dimen300,
                              child: Container(
                                margin: EdgeInsets.only(
                                    left: MyDimens.dimen8,
                                    right: MyDimens.dimen8,
                                    top: 0,
                                    bottom: 0),
                                width: MyDimens.dimen260,
                                child: Center(
                                  child: Text(
                                    lang == "th" ? "ไม่พบข้อมูล" : "No Data",
                                    style: MyFont.bold16.copyWith(
                                      color: MyColor.headerColor,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    maxLines: 1,
                                  ),
                                ),
                              ),
                            )
                          : Container(
                              // height: 500,
                              margin: EdgeInsets.only(
                                left: 0,
                                right: 0,
                                top: 0,
                                bottom: MyDimens.dimen35,
                              ),
                              child: GridView.builder(
                                  controller: controller,
                                  shrinkWrap: true,
                                  physics: ScrollPhysics(),
                                  gridDelegate:
                                      const SliverGridDelegateWithFixedCrossAxisCount(
                                          crossAxisCount: 1,
                                          childAspectRatio: 10 / 12),
                                  padding: EdgeInsets.symmetric(
                                    vertical: MyDimens.dimen14,
                                    horizontal: MyDimens.dimen16,
                                  ),
                                  scrollDirection: Axis.vertical,
                                  itemCount: userExModel!.result!.data!.length,
                                  itemBuilder: (context, index) {
                                    return GestureDetector(
                                        onTap: () {
                                          NavigatorUtil.pushToPage(
                                              UserExperienceScreen(
                                                  id: userExModel!
                                                      .result!.data![index].id
                                                      .toString()));
                                        },
                                        child: Container(
                                          margin: EdgeInsets.only(
                                              left: 16, right: 16, bottom: 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.dimen24,
                                                      bottom: 16),
                                                  width: MyDimens.dimen260,
                                                  height: MyDimens.dimen150,
                                                  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.dimen260,
                                                  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.dimen260,
                                                  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.dimen260,
                                                  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.dimen260,
                                                  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:
                                                              MyDimens.dimen24,
                                                          right:
                                                              MyDimens.dimen24,
                                                          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.dimen168,
                                                          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.dimen168,
                                                          child: Text(
                                                            userExModel!
                                                                    .result!
                                                                    .data![
                                                                        index]
                                                                    .attributePosition ??
                                                                '',
                                                            style: MyFont
                                                                .regular14
                                                                .copyWith(
                                                              color:
                                                                  MyColor.grey,
                                                              overflow:
                                                                  TextOverflow
                                                                      .ellipsis,
                                                            ),
                                                            maxLines: 2,
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            ),
                                          ),
                                        ));
                                  }),
                            ),
                ],
              ),
            ),
    );
  }

  getUserEx(String txt) async {
    var _model;
    var _fail;
    var result;
    String url = "https://ipmart.ipthailand.go.th/api/user-exp?search=${txt}";
    // 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 = UserExModel.fromJson(json.decode(utf8.decode(response.bodyBytes)));

    userExModel = _model;
  }
}
