import 'dart:convert';

import 'package:auto_route/annotations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:mnemo_cards_common/mnemo_cards_common.dart';
import '../../features/analytics/analytics.dart';

import '../../di/locator.dart';
import 'available_pack.dart';
import 'buy_pack_page.dart';
import 'card_pack_header.dart';
import 'loading_pack.dart';

@RoutePage()
class CardPackPage extends StatefulWidget {
  final CardPackPreviewDto previewDto;

  const CardPackPage(this.previewDto, {super.key});

  @override
  State<StatefulWidget> createState() => _CardPackPage();
}

class _CardPackPage extends State<CardPackPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: StreamBuilder<GetCardPackResponse>(
            stream: locator.packManager.getCardPackStream(
              widget.previewDto.id,
              widget.previewDto.isAvailable,
            ),
            initialData: null,
            builder: (context, snapshot) {
              if (!snapshot.hasData) return Loading(widget.previewDto);
              if (snapshot.requireData.responseType ==
                  GetCardPackResponseType.loading)
                return Loading(widget.previewDto);
              final response = snapshot.requireData;
              if (response is CardPackBuyDto) {
                return BuyPack(response);
              } else if (response is CardPackDto) {
                return AvailablePack(response);
              }
              Analytics.crashlyticsError(
                data: {'response': jsonEncode(snapshot.data?.toJson() ?? '{}')},
                message: 'cant load pack ${widget.previewDto.id}',
              );

              return Column(
                children: [
                  CardPackHeader.fromDto(null),
                  Expanded(
                    child: Center(
                      child: Text(
                        'Ошибка, попробуйте еще раз или попробуйте обновить приложение',
                      ),
                    ),
                  ),
                ],
              );
            }),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }
}
