import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:readmore/readmore.dart';
import 'package:remever/common/functions.dart';
import 'package:remever/common/resources.dart';
import 'package:remever/common/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/gen/assets.gen.dart';
import 'package:remever/screens/dialogs/alert_dialog.dart';
import 'package:remever/screens/dialogs/replace_diaog.dart';

enum CardType { CREATE, SHOW }

class LearningCard extends StatelessWidget {
  LearningCard({
    required this.index,
    super.key,
    this.type = CardType.SHOW,
    this.onTextTap,
  });

  final int index;
  final CardType type;
  void Function()? onTextTap;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8).r,
      child: Slidable(
        enabled: type == CardType.SHOW ? true : false,
        endActionPane: ActionPane(
          extentRatio: 0.62,
          motion: const StretchMotion(),
          children: <Widget>[
            const WSpace(8),
            _buildSlidableAction(
              context: context,
              backgroundColor: const Color(0xFFFFE4E6),
              foregroundColor: const Color(0xFFFF5C69),
              icon: CupertinoIcons.trash,
              onPressed: () {
                showCuperModalBottomSheet(
                  context: context,
                  height: 262.h,
                  builder:
                      (BuildContext context) => const AlertInfoDialog(
                        title:
                            'Вы хотите удалить карточку?\nЭто действие необратимо',
                        acceptTitle: 'Да, удалить',
                        declineTitle: 'Нет, оставить',
                      ),
                );
              },
            ),
            const WSpace(8),
            _buildSlidableAction(
              context: context,
              backgroundColor: const Color(0xFFD7E6F4),
              foregroundColor: const Color(0xFF0058AB),
              icon: CupertinoIcons.repeat,
              onPressed: () {},
            ),
            const WSpace(8),
            _buildSlidableAction(
              context: context,
              backgroundColor: AppColors.secondary,
              foregroundColor: AppColors.primary,
              icon: CupertinoIcons.move,
              onPressed: () {
                showCuperModalBottomSheet(
                  context: context,
                  height: 394.h,
                  backgroundColor: AppColors.gray_bg,
                  builder: (BuildContext context) => const ReplaceDialog(),
                );
              },
            ),
          ],
        ),
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(12)).r,
            color: Colors.white,
          ),
          constraints: BoxConstraints(minHeight: 50.h),
          child: Stack(
            children: <Widget>[
              SizedBox(
                height: 50.h,
                width: double.infinity,
                child: DecoratedBox(decoration: getDecoration()),
              ),
              Padding(
                padding: const EdgeInsets.all(12).r,
                child: Column(
                  children: <Widget>[
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        _buildImage(),
                        _buildText(context),
                        Wif(
                          condition: type == CardType.SHOW,
                          builder: (BuildContext context) => _editBtm(),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// Кнопка редактирования
  Widget _editBtm() {
    return GestureDetector(
      onTap: () {},
      child: Assets.icons.typeEdit.image(height: 24.h, width: 24.w),
    );
  }

  ///
  /// Кнопка в меню свайпа
  ///
  Widget _buildSlidableAction({
    required BuildContext context,
    required Color backgroundColor,
    required Color foregroundColor,
    required IconData icon,
    required VoidCallback onPressed,
  }) {
    return SlidableAction(
      borderRadius: BorderRadius.circular(12).r,
      onPressed: (_) => onPressed(),
      backgroundColor: backgroundColor,
      foregroundColor: foregroundColor,
      icon: icon,
    );
  }

  Widget _buildText(BuildContext context) {
    return GestureDetector(
      onTap: onTextTap,
      child: SizedBox(
        width:
            type == CardType.CREATE
                ? 250.w
                : index % 4 == 0
                ? 228.w
                : 300.w,
        child: ReadMoreText(
          isExpandable: true,
          index % 2 == 0
              ? 'Наше дело не так однозначно, как может показаться: высокотехнологичная концепция общественного уклада напрямую зависит от вывода текущих активов. Ясность нашей позиции очевидна: высокотехнологичная концепция общественного уклада влечет за собой процесс внедрения и модернизации первоочередных требований. Лишь многие известные личности будут указаны как претенденты на роль ключевых факторов.'
              : 'Аргумент или не аргумент, вот вообще хз',
          trimMode: TrimMode.Line,
          trimLines: 3,
          trimCollapsedText: '\nРазвернуть',
          trimExpandedText: '\nСвернуть',
          style: Regular16px().style,
          moreStyle: Regular12px().style.copyWith(
            color: AppColors.primary_blue,
          ),
          lessStyle: Regular12px().style.copyWith(
            color: AppColors.primary_blue,
          ),
        ),
      ),
    );
  }

  /// Картинка
  Widget _buildImage() {
    return Wif(
      condition: type == CardType.SHOW,
      builder: (BuildContext context) {
        return Wif(
          condition: index % 4 == 0,
          builder: (BuildContext context) {
            return Padding(
              padding: const EdgeInsets.only(right: 8).r,
              child: SizedBox.square(
                dimension: 64.r,
                child: DecoratedBox(
                  decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(8)).r,
                    image: DecorationImage(
                      image: Assets.images.imgCard.provider(),
                    ),
                  ),
                ),
              ),
            );
          },
        );
      },
      fallback: (BuildContext context) {
        return Padding(
          padding: const EdgeInsets.only(right: 8).r,
          child: SizedBox.square(
            dimension: 64.r,
            child: DecoratedBox(
              decoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(8)).r,
                gradient: const LinearGradient(
                  colors: <Color>[Color(0xFFDBD7F4), Color(0xFFB6AAFE)],
                  begin: Alignment.topRight,
                  end: Alignment.bottomLeft,
                ),
              ),
              child: Center(
                child: Assets.icons.typePhoto.image(
                  height: 24.h,
                  width: 24.w,
                  color: AppColors.primary,
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// Декорирование контейнера
  BoxDecoration getDecoration() {
    return BoxDecoration(
      borderRadius: const BorderRadius.all(Radius.circular(12)).r,
      gradient: LinearGradient(
        colors: <Color>[
          index % 3 == 0 ? AppColors.question : AppColors.answer,
          Colors.white,
        ],
        begin: Alignment.topLeft,
        end: const Alignment(-0.6, 1),
        stops: const <double>[0.25, 0.25],
      ),
    );
  }
}
