import 'dart:convert';

import 'package:boilerplate/core/di/injection_init.dart';
import 'package:boilerplate/core/extensions/date_time_extension.dart';
import 'package:boilerplate/core/i18n/translations.g.dart';
import 'package:boilerplate/core/styles/my_dimensions.dart';
import 'package:boilerplate/core/styles/my_font.dart';
import 'package:boilerplate/core/utils/navigator_util.dart';
import 'package:boilerplate/data/models/product/DipRegisInfoModel.dart';
import 'package:boilerplate/domain/entities/flavor/flavor_data.dart';
import 'package:boilerplate/presentation/bloc/product_detail/product_detail_bloc.dart';
import 'package:boilerplate/presentation/screen/products/detail/widgets/product_images.dart';
import 'package:boilerplate/presentation/screen/products/detail/widgets/product_may_be_interest.dart';
import 'package:boilerplate/presentation/screen/web_view/web_view_screen.dart';
import 'package:boilerplate/presentation/widgets/base_container.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../data/models/fail/fail_model.dart';
import '../../../widgets/ipm_back_button.dart';
import 'widgets/product_address.dart';
import 'widgets/product_contract_form.dart';
import 'widgets/product_detail.dart';
import 'widgets/product_header.dart';
import 'widgets/product_highlight.dart';
import 'widgets/product_industry_group.dart';
import 'widgets/product_registration_info.dart';
import 'widgets/product_tag.dart';
import 'package:http/http.dart' as http;

class ProductDetailScreen extends StatefulWidget {
  static final String tag = 'ProductDetailScreen';

  final int prodictId;
  // late String? type="";

  ProductDetailScreen({
    Key? key,
    required this.prodictId,
    // required this.type,
  }) : super(key: key);

  @override
  State<ProductDetailScreen> createState() => _ProductDetailScreenState();
}

class checkType {
  final String request_number;
  final String request_name;
  final String request_date;
  final String expire_date;
  final String name;
  final String address_of_request_name;
  final String certificate_number;
  final String certificate_date;
  // final int index;

  checkType({
    required this.request_number,
    required this.request_name,
    required this.request_date,
    required this.expire_date,
    required this.name,
    required this.address_of_request_name,
    required this.certificate_number,
    required this.certificate_date,
  });
}

class _ProductDetailScreenState extends State<ProductDetailScreen> {
  final GlobalKey<RefreshIndicatorState> refreshKey = GlobalKey();
  late final ProductDetailBloc bloc;
  DipRegisInfoModel? dipRegisInfoModel;
  late String lang = '';

  // final List<checkType> _items = [
  //   checkType(
  //     request_number: 'เลขที่คำขอ',
  //     request_name: AppLocalizations.landing.home_page,
  //     request_date: "",
  //     expire_date: "",
  //     name: "",
  //     address_of_request_name: "",
  //     certificate_number: "",
  //     certificate_date: "",
  //   ),
  // ];
  @override
  void initState() {
    super.initState();
    bloc = getIt.get<ProductDetailBloc>();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      refreshKey.currentState?.show();
    });
    getlang();

    encrytion(widget.prodictId.toString());
  }

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

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

  Future<bool> _onRefresh() async {
    bloc.add(GetProductDetailEvent(widget.prodictId));
    var state = await bloc.stream.firstWhere((state) =>
        state is GetProductDetailSuccessState ||
        state is GetProductDetailFailState);
    return state is GetProductDetailSuccessState ||
        state is GetProductDetailFailState;
  }

  @override
  void dispose() {
    bloc.close();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BaseContainer(
      child: Column(
        children: [
          Expanded(
            child: Container(
              color: Color(0xFFF4F1EB),
              child: RefreshIndicator(
                key: refreshKey,
                onRefresh: _onRefresh,
                child: BlocBuilder<ProductDetailBloc, ProductDetailState>(
                  bloc: bloc,
                  builder: (context, state) {
                    if (state.data.productData == null) {
                      return Container();
                    }
                    final data = state.data.productData!;
                    return SingleChildScrollView(
                      child: Stack(
                        children: [
                          Container(
                            width: MediaQuery.of(context).size.width,
                            margin: EdgeInsets.only(top: MyDimens.dimen16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  color: Colors.white,
                                  child: Column(
                                    children: [
                                      ProductImages(
                                        images: data.images ?? [],
                                      ),
                                      BlocProvider.value(
                                        value: bloc,
                                        child: ProductHeader(
                                          data,
                                          isFav: state.data.isFavorite,
                                          isInCart: state.data.isInCart,
                                          userId: state.data.userId,
                                        ),
                                      ),
                                      ProductContractForm(data),
                                      ProductDetail(data),
                                      ProductAddress(data),
                                      ProductIndustryGroup(data),
                                      dipRegisInfoModel?.result?.dipRegisInfo ==
                                              null
                                          ? Container()
                                          : ProductRegistrationInfo(
                                              data, dipRegisInfoModel!, lang),
                                      if (data.tags != null)
                                        ProductTag(
                                          tags: jsonDecode(data.tags!),
                                        ),
                                      _postOn(data.createdDate),
                                    ],
                                  ),
                                ),
                                // IPMDivider(),
                                // ProductComment(),
                                BlocProvider.value(
                                  value: bloc,
                                  child: ProductMayBeInterest(),
                                )
                              ],
                            ),
                          ),
                          Positioned(
                            top: MediaQuery.of(context).padding.top +
                                MyDimens.dimen10,
                            left: MyDimens.dimen10,
                            child: GestureDetector(
                              onTap: () {
                                Navigator.pop(context);
                              },
                              child: Container(
                                alignment: Alignment.center,
                                padding: EdgeInsets.all(MyDimens.dimen6),
                                decoration: BoxDecoration(
                                  color: Colors.black.withOpacity(0.3),
                                  borderRadius: BorderRadius.circular(100),
                                ),
                                child: IPMBackButton(),
                              ),
                            ),
                          )
                        ],
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
          _menuBotton(),
        ],
      ),
    );
  }

  encrytion(String id) async {
    var _model;
    var _fail;
    var result;
    String url = "https://ipmart.ipthailand.go.th/api/product/${id}";
    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)['result'];
    print("response.body => ${res}");
    print("response.body encrytion=> ${response.body}");
    print("================================");
    // if (response.statusCode == 200) {
    _model = DipRegisInfoModel.fromJson(
        json.decode(utf8.decode(response.bodyBytes)));
    dipRegisInfoModel = _model;
  }

  dynamic _jsonDecode(String json) {
    var resJson = jsonDecode(json);
    return resJson;
  }

  // if (response.statusCode == 200) {
  //   // decrytion(json.decode(response.body)['data']);
  //   return res.toString();
  //   print("200");
  // } else {
  //   // print(loginResult.errorMessage);
  // }

  _menuBotton() {
    return BlocBuilder<ProductDetailBloc, ProductDetailState>(
      bloc: bloc,
      builder: (context, state) {
        return Container(
          child: Row(
            children: [
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    NavigatorUtil.pushToPage(WebViewScreen(
                      title: 'รายละเอียดผู้ขาย',
                      isSellerDetail: true,
                      email: state.data.productData?.store?.email ?? '',
                      phone: state.data.productData?.store?.phone ?? '',
                      url: getIt.get<AppFlavorData>().webDomain +
                          "/saler-profile/${state.data.productData?.store?.id}?mobile=1&lang=${lang}",
                    ));
                  },
                  child: Container(
                    padding: EdgeInsets.only(
                      top: MyDimens.dimen24,
                      bottom: MediaQuery.of(context).padding.bottom +
                          MyDimens.dimen24,
                    ),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Color(0xFFD3CCC6), Color(0xFFAAAAAA)],
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                      ),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10),
                      ),
                    ),
                    child: Text(
                      AppLocalizations.products.seller_detail,
                      style: MyFont.medium16.copyWith(
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    NavigatorUtil.pushToPage(WebViewScreen(
                      title: 'นัดหมายเจรจาธุรกิจ',
                      url: getIt.get<AppFlavorData>().webDomain +
                          // "/mobile/order/booking?product=${state.data.productData?.id}&seller=${state.data.productData?.createBy}",
                          "/mobile/order/booking?product=${state.data.productData?.id}&lang=${lang}&seller=${state.data.productData?.createBy}&mobile=1",
                    ));
                  },
                  child: Container(
                    padding: EdgeInsets.only(
                      top: MyDimens.dimen24,
                      bottom: MediaQuery.of(context).padding.bottom +
                          MyDimens.dimen24,
                    ),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Color(0xFFF15B44), Color(0xFFB21F29)],
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                      ),
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(10),
                      ),
                    ),
                    child: Text(
                      AppLocalizations.products.business_meeting,
                      style: MyFont.medium16.copyWith(
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _postOn(String? createdDate) {
    if (createdDate == null) {
      return Container();
    }
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: MyDimens.dimen20,
        horizontal: MyDimens.dimen16,
      ),
      child: Text(
        'Posted On ${DateTime.parse(createdDate).toAppDateFormat()}',
        style: MyFont.regular16,
      ),
    );
  }
}

class Response<T> {
  T success;
  String fail;

  Response(this.success, this.fail);
}
