import 'dart:convert';
import 'dart:math';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:remever/common/resources.dart';
import 'package:remever/common/widgets/typography.dart';
import 'package:remever/common/widgets/w_if.dart';
import 'package:remever/common/widgets/wspace.dart';
import 'package:remever/components/extensions/context.dart';
import 'package:remever/database/database.dart';
import 'package:remever/gen/assets.gen.dart';
import 'package:remever/inject.dart';
import 'package:remever/screens/collections/widgets/learning_card.dart';
import 'package:remever/screens/dialogs/info_dialog.dart';
import 'package:remever/services/tickets/tickets_interface.dart';
import 'package:remever/widgets/primary_button.dart';

@RoutePage()
class CollectionDetailScreen extends StatelessWidget {
  const CollectionDetailScreen({super.key, required this.collection});

  final Collection collection;

  void _onInfoTap(BuildContext context) {
    showCupertinoModalBottomSheet(
      topRadius: const Radius.circular(24).r,
      backgroundColor: AppColors.white,
      context: context,
      builder: (BuildContext _) => InfoDialog(collection: collection),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.gray_bg,
      appBar: _buildAppBar(context),
      body: _buildMain(context),
    );
  }

  /// Построение шапки
  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      toolbarHeight: 56.h,
      backgroundColor: AppColors.white,
      shadowColor: Colors.transparent,
      leading: IconButton(
        onPressed: () async {
          // context.read<HomeCubit>().toCollection();
          context.back();
        },
        icon: const Icon(CupertinoIcons.left_chevron, color: Colors.black),
      ),
      centerTitle: false,
      title: _buildTitle(),
      actions: <Widget>[
        GestureDetector(
          onTap: () => _onInfoTap(context),
          child: Assets.icons.typeDescription.image(height: 24.h, width: 24.w),
        ),
        const WSpace(16),
      ],
    );
  }

  Widget _buildTitle() {
    return Row(
      children: <Widget>[_buildAvatar(), const WSpace(5), _buildInfo()],
    );
  }

  ///
  /// Построение основной информации
  ///
  Widget _buildInfo() {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        // mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          _buildCollectionTitle(),
          const HSpace(4),
          _buildCards(),
        ],
      ),
    );
  }

  ///
  /// Построение кол-ва карточек и лайков
  ///
  Widget _buildCards() {
    return Row(
      children: <Widget>[
        Row(
          children: <Widget>[
            Assets.icons.typeCards.image(
              height: 18.h,
              width: 18.w,
              color: AppColors.disabled,
            ),
            const WSpace(2),
            StreamBuilder<List<Collection>>(
              stream: getIt<TicketsInterface>().watchTicketsList(),
              builder: (context, snapshot) {
                return _buildCount(snapshot.data?.length ?? 0);
              },
            ),
          ],
        ),
        const WSpace(8),
      ],
    );
  }

  Widget _buildCount(int count) {
    return AppTypography(
      '$count',
      type: Regular14px(),
      color: AppColors.disabled,
    );
  }

  ///
  /// Название коллекции
  ///
  Widget _buildCollectionTitle() {
    return AppTypography(
      collection.title,
      type: Medium16px(),
      maxLines: 1,
      softWrap: true,
      color: AppColors.primary,
    );
  }

  ///
  /// Обложка коллекции
  ///
  Widget _buildAvatar() {
    return SizedBox.square(
      dimension: 40.r,
      child: DecoratedBox(
        decoration: BoxDecoration(shape: BoxShape.circle, color: AppColors.bg),

        child: Wif(
          condition: collection.image != null,
          builder:
              (context) => ClipOval(
                child: Image.memory(collection.image!, fit: BoxFit.cover),
              ),
          fallback:
              (context) => Center(
                child: AppTypography(
                  collection.title.substring(0, 1),
                  type: Bold34px(),
                ),
              ),
        ),
      ),
    );
  }

  ///
  /// Построение основного содержимого
  ///
  Widget _buildMain(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16).r,

      child: _buildList(context),
    );
  }

  /// Состояние пустого списка
  Widget _buildEmptyList(BuildContext context) {
    return Column(
      children: <Widget>[
        const HSpace(40),
        Center(child: Assets.images.noData.image(width: 184.w, height: 101.h)),
        const Spacer(),
        _buildCreateBtn(context),
        const HSpace(40),
      ],
    );
  }

  ///Кнопка создания
  Widget _buildCreateBtn(BuildContext context) {
    return PrimaryButton(
      height: 52,
      onTap: () {
        // context.read<HomeCubit>().toCollection();
        context.back();
      },
      color: AppColors.primary,
      child: AppTypography('Создать карточку', type: Regular14px()),
    );
  }

  ///
  /// Построение списка карточек
  ///
  Widget _buildList(BuildContext context) {
    return ListView.builder(
      physics: BouncingScrollPhysics(),
      itemCount: 10,
      itemBuilder:
          (BuildContext context, int index) => LearningCard(index: index),
    );
  }
}
