import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/models/offers_and_discounts/get_offers_list.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share/share.dart';
import 'package:url_launcher/url_launcher.dart';

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

  @override
  State<OffersAndDiscountsDetails> createState() => _OffersAndDiscountsDetailsState();
}

class _OffersAndDiscountsDetailsState extends State<OffersAndDiscountsDetails> {
  // late OffersListModel getOffersList;
  late List<OffersListModel> getOffersList;
  late ScrollController _scrollController;

  GlobalKey _globalKey = GlobalKey();

  @override
  void initState() {
    _scrollController = ScrollController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    getOffersList = ModalRoute.of(context)?.settings.arguments as List<OffersListModel>;
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        // title: LocaleKeys.mowadhafhiRequest.tr(),
        title: "Offers & Discounts",
        showHomeButton: true,
      ),
      body: ListView(
        controller: _scrollController,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Hero(
                tag: "ItemImage" + getOffersList[0].rowID!,
                // transitionOnUserGestures: true,
                child: RepaintBoundary(
                  key: _globalKey,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(6),
                    child: Image.network(
                      getOffersList[0].bannerImage!,
                      fit: BoxFit.contain,
                    ),
                  ).paddingAll(12),
                ),
              ),
              8.height,
              AppState().isArabic(context)
                  ? getOffersList[0].titleAR!.toText22(isBold: true, color: const Color(0xff2B353E)).center
                  : getOffersList[0].title!.toText22(isBold: true, color: const Color(0xff2B353E)).center,
              Html(
                data: AppState().isArabic(context) ? getOffersList[0].descriptionAR! : getOffersList[0].description ?? "",
                onLinkTap: (String? url, RenderContext context, Map<String, String> attributes, _) {
                  launchUrl(Uri.parse(url!));
                },
              ),
              checkDate(getOffersList[0].endDate!).paddingOnly(left: 8),
              10.height,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  getOffersList[0].discount!.toText16(isBold: true),
                  InkWell(
                      onTap: () {
                        _shareOfferAsImage();
                      },
                      child: const Icon(Icons.share, color: MyColors.darkIconColor).paddingOnly(bottom: 4))
                ],
              ).paddingOnly(left: 8, right: 8),
              getOffersList[0].isHasLocation == "true"
                  ? InkWell(
                      onTap: () {},
                      child: Row(
                        children: [const Icon(Icons.map_sharp, color: MyColors.darkIconColor).paddingOnly(bottom: 4), "Offer Location".toText16(isUnderLine: true).paddingOnly(left: 8)],
                      ).paddingOnly(left: 8, right: 8, top: 8),
                    )
                  : 12.height,
            ],
          ).objectContainerView().paddingOnly(left: 21, right: 21, top: 21),
          "Related Offers".toText22(isBold: true, color: const Color(0xff2B353E)).paddingOnly(left: 21, right: 21, top: 21),
          GridView(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 162 / 266, crossAxisSpacing: 12, mainAxisSpacing: 12),
            padding: const EdgeInsets.all(21),
            shrinkWrap: true,
            primary: false,
            physics: const ScrollPhysics(),
            children: getItemsForSaleWidgets(),
          ),
        ],
      ),
    );
  }

  void _shareOfferAsImage() async {
    try {
      RenderRepaintBoundary? boundary = _globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
      ui.Image? image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();

      Directory tempDir = await getTemporaryDirectory();
      File file = await File('${tempDir.path}/${DateTime.now().toString()}.png').create();
      await file.writeAsBytes(pngBytes);
      await Share.shareFiles([(file.path)], text: AppState().isArabic(context) ? getOffersList[0].titleAR : getOffersList[0].title);
    } catch (ex) {
      debugPrint(ex.toString());
    }
  }

  void _scrollToTop() {
    _scrollController.animateTo(
      0,
      duration: const Duration(milliseconds: 500),
      curve: Curves.linear,
    );
  }

  List<Widget> getItemsForSaleWidgets() {
    List<Widget> itemsList = [];
    for (int i = 1; i < 5; i++) {
      itemsList.add(getItemCard(getOffersList[i]));
    }
    return itemsList;
  }

  Widget getItemCard(OffersListModel getOffersList) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Hero(
          tag: "ItemImage" + getOffersList.rowID!,
          transitionOnUserGestures: true,
          child: AspectRatio(
            aspectRatio: 148 / 127,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: Image.network(
                getOffersList.bannerImage!,
                fit: BoxFit.contain,
              ),
            ),
          ),
        ),
        5.height,
        getOffersList.title!.toText16(isBold: true, color: const Color(0xff2B353E), maxlines: 1),
        // Html(
        //     data: AppState().isArabic(context) ? getOffersList.descriptionAR! : getOffersList.description ?? "",
        //     // onLinkTap: (String? url, RenderContext context, Map<String, String> attributes, _) {
        //   //   launchUrl(Uri.parse(url!));
        //   // }
        // ),
        getOffersList.description!.toText12(maxLine: 2, color: const Color(0xff535353)),
        16.height,
        getOffersList.discount!.toText14(isBold: true, maxlines: 1),
        8.height,
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [checkDate(getOffersList.endDate!), SvgPicture.asset("assets/images/arrow_next.svg").paddingOnly(bottom: 4)],
        ),
      ],
    ).objectContainerView().onPress(() {
      this.getOffersList[0] = getOffersList;
      _scrollToTop();
      setState(() {});
    });
  }

  void getOfferLocation() {}

  Widget checkDate(String endDate) {
    DateTime endDateObj = DateFormat("yyyy-MM-dd").parse(endDate);
    if (endDateObj.isAfter(DateTime.now())) {
      return "Offer Valid".toText16(isBold: true, color: MyColors.greenColor);
    } else {
      return "Offer Expired".toText16(isBold: true, color: MyColors.redColor);
    }
  }
}
