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/models/qna_model.dart';
import 'package:initial_folder/providers/like_or_unlike_provider.dart';
import 'package:initial_folder/providers/posting_qna_reply_provider.dart';
import 'package:initial_folder/providers/qna_provider.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/reply_qna_user_page.dart';
import 'package:provider/provider.dart';

import '../../../get_it.dart';
import '../../../models/comment_qna_model.dart';
// import '../../../widgets/qna_user.dart';

final scaffoldKey = GlobalKey<ScaffoldState>();

class DetailQuestAndAnswer extends StatefulWidget {
  const DetailQuestAndAnswer({
    Key? key,
    required this.id,
    required this.qnaDataModel,
    required this.index,
    required this.userId,
  }) : super(key: key);
  
  final QnaDataModel qnaDataModel;
  final id;
  final int index;
  final int userId;

  @override
  State<DetailQuestAndAnswer> createState() => _DetailQuestAndAnswerState();
}

class _DetailQuestAndAnswerState extends State<DetailQuestAndAnswer> {
  final _controller = TextEditingController();
  final provider = qnaGetIt<QnaProvider>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    
    
  void onReplyDeleted(String idRep) {
    setState(() {
    // Temukan indeks balasan yang akan dihapus
    final int indexToRemove = widget.qnaDataModel.comment.indexWhere((comment) => comment.idRep == idRep);

    // Jika balasan ditemukan, hapus dan perbarui jumlah komentar
    if (indexToRemove != -1) {
      widget.qnaDataModel.comment.removeAt(indexToRemove);
      widget.qnaDataModel.countComment = (widget.qnaDataModel.countComment ?? 1) - 1;
    }
  });
  }

  @override
  Widget build(BuildContext context) {
    PostingQnaReplyProvider postingQnaReplyProvider = Provider.of<PostingQnaReplyProvider>(context);
    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 Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text(
          'Pertanyaan',
          style: primaryTextStyle.copyWith(
            fontWeight: semiBold,
            fontSize: getProportionateScreenWidth(16),
            letterSpacing: 0.2,
          ),
        ),
      ),
      body: GestureDetector(
        child: Stack(
          children: [
            ListView(
              children: [
                // Tampilan pertanyaan utama
                Padding(
                  padding: EdgeInsets.all(getProportionateScreenWidth(0)),
                  child: Container(
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.primaryContainer,
                      borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(15),
                        bottomRight: Radius.circular(15),
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.5),
                          spreadRadius: 2,
                          blurRadius: 5,
                          offset: Offset(0, 3), 
                        ),
                      ],
                    ),
                    child: Padding(
                      padding: EdgeInsets.all(getProportionateScreenWidth(16)),
                      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: [
                                  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,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(10)),
                          if (widget.qnaDataModel.title != '')
                            Text(
                              widget.qnaDataModel.title!,
                              style: secondaryTextStyle.copyWith(
                                fontSize: getProportionateScreenWidth(16),
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context).colorScheme.onBackground,
                              ),
                            ),
                          SizedBox(height: getProportionateScreenHeight(10)),
                          Html(
                            data: widget.qnaDataModel.quest ?? 'Pertanyaan tidak tersedia',
                            style: {
                              "*": Style(margin: Margins.zero),
                            },
                          ),
                          SizedBox(height: getProportionateScreenHeight(16)),
                          Row(
  children: [
    kLike(
      widget.qnaDataModel.selfLiked ?? false,
      int.parse(widget.qnaDataModel.countLike ?? '0'),
      () async {
        await likeOrUnlikes(int.parse(widget.qnaDataModel.idQna.toString()));

        setState(() {
          widget.qnaDataModel.selfLiked = !(widget.qnaDataModel.selfLiked ?? false);
          widget.qnaDataModel.countLike = widget.qnaDataModel.selfLiked!
              ? (int.parse(widget.qnaDataModel.countLike ?? '0') + 1).toString()
              : (int.parse(widget.qnaDataModel.countLike ?? '0') - 1).toString();
        });
      },
    ),
    SizedBox(width: getProportionateScreenWidth(13)),
    kComment(widget.qnaDataModel.comment.length),
  ],
),
                        ],
                      ),
                    ),
                  ),
                ),
                SizedBox(height: getProportionateScreenHeight(10)),
                // Divider(),
                Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: getProportionateScreenWidth(16),
                    vertical: getProportionateScreenWidth(8),
                  ),
                  child: Text(
                    'Balasan',
                    style: thirdTextStyle.copyWith(
                      color: Theme.of(context).colorScheme.onBackground,
                      fontWeight: semiBold,
                      fontSize: getProportionateScreenWidth(16),
                      letterSpacing: 1,
                    ),
                  ),
                ),
                SizedBox(height: getProportionateScreenHeight(13)),
               ReplyQnaUserPage(
                  idCourse: widget.id,
                  idQna: widget.qnaDataModel.idQna ?? '',
                  userId: widget.userId,
                  onReplyDeleted: onReplyDeleted,
                ),
                SizedBox(height: getProportionateScreenHeight(65)),
              ],
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                decoration: BoxDecoration(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Color.fromARGB(255, 54, 61, 96)
                      : Color.fromARGB(255, 221, 221, 221),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20),
                    topRight: Radius.circular(20),
                  ),
                ),
                height: getProportionateScreenWidth(72),
                width: double.infinity,
                child: Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: getProportionateScreenWidth(16),
                    vertical: getProportionateScreenWidth(16),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        width: SizeConfig.screenWidth * 0.65,
                        child: TextFormField(
                          scrollPhysics: AlwaysScrollableScrollPhysics(),
                          textAlignVertical: TextAlignVertical.center,
                          controller: _controller,
                          scrollPadding: EdgeInsets.zero,
                          cursorColor: secondaryColor,
                          maxLines: 1,
                          minLines: 1,
                          keyboardType: TextInputType.multiline,
                          decoration: InputDecoration(
                            filled: true,
                            fillColor: Theme.of(context).brightness == Brightness.dark
                                ? seventeenColor
                                : Colors.grey[200],
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10),
                              borderSide: BorderSide.none,
                            ),
                            hintStyle: secondaryTextStyle.copyWith(
                              color: secondaryColor,
                              letterSpacing: 0.5,
                              fontSize: getProportionateScreenWidth(12),
                            ),
                            hintText: "Balas Pertanyaan",
                          ),
                        ),
                      ),
                      ElevatedButton(
                        onPressed: () async {
                          if (_controller.text.trim().isEmpty) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                duration: Duration(seconds: 2),
                                backgroundColor: Colors.orange,
                                content: Text(
                                  'Ups, balasan masih kosong. isi dulu yuk!',
                                  style: primaryTextStyle.copyWith(color: Colors.white),
                                ),
                                behavior: SnackBarBehavior.floating,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10),
                                ),
                              ),
                            );
                          } else {
                            bool isSuccessful = await postingQnaReplyProvider.postQnaReply(
                              _controller.text,
                              widget.qnaDataModel.idQna.toString(),
                            );

                            if (isSuccessful) {
                              setState(() {
                              // Tambahkan balasan baru ke dalam komentar
                              widget.qnaDataModel.comment.add(
                                Comment(
                                  textRep: _controller.text, 
                                  username: '', 
                                  createAt: DateTime.now().toString(), 
                                ),
                              );
                            });

                              provider.getQna(widget.id);
                              _controller.clear();
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                  duration: Duration(seconds: 2),
                                  backgroundColor: Colors.green,
                                  content: Text(
                                    'Balasan berhasil dikirim',
                                    style: primaryTextStyle.copyWith(color: Colors.white),
                                  ),
                                  behavior: SnackBarBehavior.floating,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                ),
                              );
                            } else {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                  duration: Duration(seconds: 2),
                                  backgroundColor: Colors.red,
                                  content: Text(
                                    'Gagal mengirim balasan, silakan coba lagi',
                                    style: primaryTextStyle.copyWith(color: Colors.white),
                                  ),
                                  behavior: SnackBarBehavior.floating,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                ),
                              );
                            }
                          }
                        },
                        child: Text(
                          'Kirim',
                          style: thirdTextStyle.copyWith(
                            color: Colors.white,
                            letterSpacing: 0.3,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: primaryColor,
                          minimumSize: Size(
                            getProportionateScreenWidth(35),
                            getProportionateScreenWidth(35),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Widget kLike(bool isLiked, int likeCount, Function onTap) {
  return GestureDetector(
    onTap: () => onTap(),
    child: Row(
      children: [
        Icon(
          isLiked ? Icons.favorite : Icons.favorite_border_rounded,
          color: isLiked ? Colors.red : secondaryColor,
          size: 25, 
        ),
        SizedBox(width: 5),
        Text(
          "$likeCount",
          style: secondaryTextStyle.copyWith(
            fontSize: getProportionateScreenWidth(12),
            letterSpacing: 0.3,
          ),
        ),
      ],
    ),
  );
}

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


