import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:initial_folder/main.dart';
import 'package:initial_folder/models/comment_qna_model.dart';
import 'package:initial_folder/models/qna_model.dart';
import 'package:initial_folder/providers/like_or_unlike_provider.dart';
import 'package:initial_folder/providers/posting_qna_provider.dart';
import 'package:initial_folder/providers/qna_provider.dart';
import 'package:initial_folder/screens/course/component/detail_quest_and_answer.dart';
import 'package:initial_folder/widgets/counter_qna_comment_page.dart';
import 'package:initial_folder/widgets/counter_qna_like_page.dart';
import 'package:initial_folder/widgets/edit_qna_user.dart';
import 'package:initial_folder/widgets/qna_user_page.dart';
import 'package:provider/provider.dart';

import '../get_it.dart';
import '../size_config.dart';
import '../theme.dart';

class QnaUser extends StatefulWidget {
  const QnaUser({
    Key? key,
    required this.id,
    this.divider,
    required this.qnaDataModel,
    required this.index,
    required this.userId,
  }) : super(key: key);

  final Widget? divider;
  final id;
  final QnaDataModel qnaDataModel;
  final int index;
  final int userId;

  @override
  State<QnaUser> createState() => _QnaUserState();
}

class _QnaUserState extends State<QnaUser> {
  double value = 0;
  final provider = qnaGetIt<QnaProvider>();
  // bool selfLike = false;
  @override
  Widget build(BuildContext context) {
    PostingQnaProvider deleteQnaProvider =
        Provider.of<PostingQnaProvider>(context);

    deleteQna() async {
      if (await deleteQnaProvider
          .deleteQna(int.parse(widget.qnaDataModel.idQna.toString()))) {
        ScaffoldMessenger.of(globalScaffoldKey.currentContext!).showSnackBar(
          SnackBar(
            duration: Duration(seconds: 2),
            backgroundColor: primaryColor,
            content: Text(
              'Pertanyaan berhasil dihapus',
              style: primaryTextStyle.copyWith(
                color: backgroundColor,
              ),
            ),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5),
            ),
            action: SnackBarAction(
              label: 'Lihat',
              onPressed: () {
                ScaffoldMessenger.of(globalScaffoldKey.currentContext!)
                    .hideCurrentSnackBar();
              },
            ),
          ),
        );
      } else {
        ScaffoldMessenger.of(globalScaffoldKey.currentContext!).showSnackBar(
          SnackBar(
            duration: Duration(seconds: 2),
            backgroundColor: primaryColor,
            content: Text(
              'Terjadi kesalahan',
              style: primaryTextStyle.copyWith(
                color: backgroundColor,
              ),
            ),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        );
      }
    }

    LikeOrUnlikeProvider _likeOrUnlikeProvider =
        Provider.of<LikeOrUnlikeProvider>(context);

    likeOrUnlikes(int idQna) async {
      final provider = qnaGetIt<QnaProvider>();
      if (await _likeOrUnlikeProvider.likeOrUnlike(idQna)) {
        provider.getQna(widget.id);
        print("Respon Baik");
      }
    }

    return Container(
      margin: EdgeInsets.symmetric(
        horizontal: getProportionateScreenWidth(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailQuestAndAnswer(
                    qnaDataModel: widget.qnaDataModel,
                    id: widget.id,
                    index: widget.index,
                    userId: widget.userId,
                  ),
                ),
              ).then((value) => provider.getQna(widget.id));
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    CircleAvatar(
                      backgroundColor: primaryColor,
                      backgroundImage: widget.qnaDataModel.fotoProfile == null
                          ? AssetImage("assets/images/Profile Image.png")
                          : NetworkImage(widget.qnaDataModel.fotoProfile ?? '')
                              as ImageProvider,
                    ),
                    SizedBox(
                      width: getProportionateScreenWidth(8),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Text(
                              widget.qnaDataModel.username ?? '',
                              style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(13),
                                  color: Theme.of(context)
                                      .colorScheme
                                      .onBackground),
                            ),
                          ],
                        ),
                        Text(
                          widget.qnaDataModel.date ?? '',
                          style: primaryTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(12),
                              color:
                                  Theme.of(context).colorScheme.onBackground),
                        ),
                      ],
                    ),
                    int.parse(widget.qnaDataModel.sender.toString()) ==
                            widget.userId
                        ? Expanded(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                PopupMenuButton(
                                  child: Padding(
                                    padding: EdgeInsets.only(right: 10),
                                    child: Icon(
                                      Icons.more_vert,
                                      color: Theme.of(context)
                                          .colorScheme
                                          .onBackground,
                                    ),
                                  ),
                                  itemBuilder: (context) => [
                                    PopupMenuItem(
                                      child: Container(
                                        child: Text('Edit'),
                                      ),
                                      value: 'edit',
                                    ),
                                    PopupMenuItem(
                                      child: Text('Hapus'),
                                      value: 'hapus',
                                    ),
                                  ],
                                  onSelected: (value) {
                                    switch (value) {
                                      case 'edit':
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) => EditQna(
                                              quest: widget.qnaDataModel.quest,
                                              title: widget.qnaDataModel.title,
                                              id_qna: widget.qnaDataModel.idQna,
                                              id_course: widget.id,
                                              id_lesson:widget.qnaDataModel.idLesson, 
                                            ),
                                          ),
                                        );
                                        break;
                                      case 'hapus':
                                        deleteQna();
                                        break;
                                    }
                                  },
                                ),
                              ],
                            ),
                          )
                        : SizedBox(
                            height: 12,
                          ),
                  ],
                ),
                SizedBox(height: getProportionateScreenHeight(6)),
                widget.qnaDataModel.title != ''
                    ? Text(
                        widget.qnaDataModel.title!,
                        style: secondaryTextStyle.copyWith(
                          color: Theme.of(context).colorScheme.onBackground,
                          fontSize: SizeConfig.blockHorizontal! * 4.2,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                    : const SizedBox(),

                Html(
                  data: widget.qnaDataModel.quest ?? '',
                  style: {
                    "*": Style(margin: Margins.zero),
                  },
                ),

                // Text(
                //   widget.qnaDataModel.quest ?? '',
                //   style: secondaryTextStyle.copyWith(
                //       color: Theme.of(context).colorScheme.onBackground,
                //       letterSpacing: 1,
                //       fontSize: SizeConfig.blockHorizontal! * 3.4),
                // ),
                SizedBox(height: getProportionateScreenHeight(16)),
              ],
            ),
          ),
          Row(
            children: [
              kLike(
                  widget.qnaDataModel.selfLiked == true
                      ? Icons.favorite
                      : Icons.favorite_border_rounded,
                  widget.qnaDataModel.selfLiked == true
                      ? Colors.red
                      : secondaryColor, () {
                likeOrUnlikes(int.parse(widget.qnaDataModel.idQna.toString()));
              }),
              SizedBox(
                width: getProportionateScreenWidth(3),
              ),
              Text(
                "${widget.qnaDataModel.countLike ?? 0}",
                style: secondaryTextStyle.copyWith(
                    fontSize: getProportionateScreenWidth(10),
                    letterSpacing: 0.3),
              ),
              SizedBox(
                width: getProportionateScreenWidth(13),
              ),
              kComment(
                widget.qnaDataModel.comment.length,
              ),
            ],
          ),
          SizedBox(
            height: getProportionateScreenWidth(5),
          ),
          Divider(
            thickness: 0.3,
          )
          // SizedBox(
          //   child: widget.divider,
          // )
        ],
      ),
    );
  }
}

Widget kLike(IconData icon, Color color, Function onTap) {
  return GestureDetector(
    onTap: () => onTap(),
    child: Row(
      children: [
        Icon(
          icon,
          color: color,
          size: 12,
        ),
      ],
    ),
  );
}

Widget kComment(int value) {
  return Row(
    children: [
      Icon(
        FontAwesomeIcons.comment,
        color: secondaryColor,
        size: 12,
      ),
      SizedBox(
        width: getProportionateScreenWidth(3),
      ),
      Text(
        "$value",
        style: secondaryTextStyle.copyWith(
            fontSize: getProportionateScreenWidth(10), letterSpacing: 0.3),
      )
    ],
  );
}
