import 'dart:convert';
import 'dart:developer';
import 'package:auto_route/auto_route.dart';
import 'package:mnemo_cards/utils/string_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mnemo_cards_common/mnemo_cards_common.dart';
import '../../di/injector.dart';
import '../../features/analytics/analytics.dart';
import '../../features/packs/pack_holder.dart';
import '../../main.dart';
import '../items/builder.dart';

import '../../di/locator.dart';
import '../../domain/router/app_router.dart';
import '../../theme/themes.dart';
import 'card_pack_header.dart';
import 'loading_pack.dart';

class BuyPack extends StatelessWidget {
  final CardPackBuyDto dto;

  const BuyPack(this.dto);

  @override
  Widget build(BuildContext context) {
    bool loading = false;
    Analytics.buyPackOpened(dto);
    return Container(
      // color: dto.color?.asColor,
      child: StatefulBuilder(builder: (context, setState) {
        if (loading) {
          return _Loading(dto);
        }
        return Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            CardPackHeader(dto.title, dto.subtitle, dto.color?.asColor),
            Expanded(
              child: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: 10.0.w, vertical: 18.h),
                    child: LayoutBuilder(builder: (context, constraints) {
                      final cardWidth = constraints.maxWidth / 3;
                      final imageWidth = cardWidth * 0.9;
                      return SizedBox(
                        height: 150.h,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: dto.cards.length,
                          itemExtent: cardWidth,
                          itemBuilder: (BuildContext context, int index) {
                            final card = dto.cards[index];
                            if (card.image != null) {
                              return Container(
                                alignment: Alignment.center,
                                width: imageWidth,
                                margin: EdgeInsets.symmetric(
                                  horizontal: cardWidth - imageWidth - 1,
                                  vertical: 1,
                                ),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(8.0),
                                  border: Border.all(
                                    color: borderGray,
                                  ),
                                ),
                                child: Image.memory(base64Decode(card.image!)),
                              );
                            }
                            return SizedBox.shrink();
                          },
                        ),
                      );
                    }),
                  ),
                  SizedBox(
                    height: 32.h,
                  ),
                  ...?dto.items?.build(),
                ],
              ),
            ),
            _BuyButton(dto, (v) {
              setState(() {
                loading = v;
              });
            }),
            SizedBox(
              height: 16.h,
            ),
          ],
        );
      }),
    );
  }
}

class _Loading extends StatelessWidget {
  final CardPackBuyDto dto;

  _Loading(this.dto);

  @override
  Widget build(BuildContext context) {
    final memoryImage = locator.imagesHolder.get('pack_${dto.id}');
    return Column(
      children: [
        CardPackHeader(dto.title, dto.subtitle, dto.color?.asColor),
        Expanded(
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (memoryImage != null)
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Image(
                      image: memoryImage,
                      width: 100,
                    ),
                  ),
                Text('Загрузка...'),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

class _BuyButton extends StatelessWidget {
  final CardPackBuyDto dto;
  final Function(bool) callback;

  _BuyButton(this.dto, this.callback);

  Future<void> _updatePack() async {
    try {
      callback(true);
      await locator.packUpdater.updatePackAndSaveImages(dto.id);
      await locator.packCacheManager.loadPackFromCache(dto.id);
    } catch (e, s) {
      log(
        'Updating from buy pack',
        error: e,
        stackTrace: s,
      );
      appRouter.maybePop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 5.0.h,
        horizontal: 10.w,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        mainAxisSize: MainAxisSize.max,
        children: [
          InkWell(
            onTap: () async {
              if (locator.userManager.hasUser) {
                Analytics.buyPackPressed(dto, PaymentSystem.google);
                final result = await locator.purchaseService.buyPack(dto);
                if (result) {
                  _updatePack();
                }
              } else {
                AppRouter.openAuth();
              }
            },
            child: Container(
              height: 120.h,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: borderGray),
                borderRadius: BorderRadius.circular(16.0),
              ),
              padding: EdgeInsets.all(10.0.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Купить',
                    style: TextStyle(
                      fontSize: 25.sp,
                      fontWeight: FontWeight.w500,
                      height: 0.85,
                    ),
                  ),
                  SizedBox(
                    height: 8.0.h,
                  ),
                  if (dto.price != null)
                    Text(
                      dto.price!,
                      style: TextStyle(
                        fontSize: 17.sp,
                        fontWeight: FontWeight.w400,
                        height: 1.0,
                      ),
                    ),
                ],
              ),
            ),
          ),
          TextButton(
            style: ButtonStyle(
              overlayColor:
                  WidgetStateColor.resolveWith((states) => Colors.white),
            ),
            onPressed: () async {
              if (locator.userManager.hasUser) {
                Analytics.buyPackPressed(dto, PaymentSystem.yookassa);
                if (await locator.purchaseService
                    .buyPackWithYooMoney(dto, context)) {
                  _updatePack();
                }
              } else {
                AppRouter.openAuth();
              }
            },
            child: Text(
              'Оплатить через YooMoney',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w400,
                decoration: TextDecoration.underline,
                color: borderGray,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
