import 'package:flutter/material.dart';
import 'package:initial_folder/main.dart';
import 'package:initial_folder/providers/posting_qna_provider.dart';
import 'package:initial_folder/providers/qna_provider.dart';
import 'package:provider/provider.dart';
import 'package:quill_html_editor/quill_html_editor.dart';

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

class EditQna extends StatefulWidget {
  const EditQna(
      {Key? key,
      required this.quest,
      required this.title,
      required this.id_lesson,
      required this.id_qna,
      required this.id_course,})
      : super(key: key);

  final quest;
  final id_lesson;
  final title;
  final id_qna;
  final id_course;

  @override
  State<EditQna> createState() => _EditQnaState();
}

class _EditQnaState extends State<EditQna> {
  final TextEditingController _controllerTitle = TextEditingController();
  final QuillEditorController _controllerQuest = QuillEditorController();
  
  final customToolbar = [
    ToolBarStyle.headerOne,
    ToolBarStyle.headerTwo,
    ToolBarStyle.bold,
    ToolBarStyle.italic,
    ToolBarStyle.underline,
    ToolBarStyle.color,
    ToolBarStyle.listBullet,
    ToolBarStyle.listOrdered,
  ];

  late String initialTitle;
  late String initialQuest;

  double value = 0;

  @override
  void initState() {
    initialTitle = widget.title;
    initialQuest = widget.quest;

    _controllerTitle.text = widget.title;
    super.initState();
  }

  @override
  void dispose() {
    _controllerTitle.dispose();
    _controllerQuest.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    PostingQnaProvider editQnaProvider =
        Provider.of<PostingQnaProvider>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Edit Pertanyaan',
          style: primaryTextStyle.copyWith(
            fontWeight: semiBold,
            fontSize: getProportionateScreenWidth(16),
            letterSpacing: 0.2,
          ),
        ),
      ),
      body: Stack(
        children: [
          Container(
            margin: EdgeInsets.symmetric(
              horizontal: getProportionateScreenWidth(16),
            ),
            child: Column(
              children: [
                SizedBox(
                  height: 15,
                ),
               TextField(
                  controller: _controllerTitle,
                  cursorColor: secondaryColor,
                  scrollPadding: EdgeInsets.zero,
                  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: "Masukkan Judul Pertanyaan",
                  ),
                ),
                SizedBox(height: getProportionateScreenWidth(18)),
                
                ToolBar(
                  toolBarColor: Theme.of(context).brightness == Brightness.dark
                      ? seventeenColor
                      : Colors.grey[200]!,
                  activeIconColor: primaryColor,
                  iconColor: secondaryColor,
                  padding: const EdgeInsets.all(8),
                  iconSize: 20,
                  controller: _controllerQuest,
                  toolBarConfig: customToolbar,
                ),
                
                Container(
                  height: 180,
                  width: double.infinity,
                  padding: EdgeInsets.all(15),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(10),
                      bottomRight: Radius.circular(10),
                    ),
                    color: Theme.of(context).colorScheme.primaryContainer,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey,
                        blurRadius: 0.5,
                        offset: Offset(0, 2),
                        spreadRadius: 0.001,
                      ),
                    ],
                  ),
                  child: QuillHtmlEditor(
                    hintText: 'Edit pertanyaan Anda',
                    controller: _controllerQuest,
                    isEnabled: true,
                    minHeight: 100,
                    backgroundColor:
                        Theme.of(context).brightness == Brightness.dark
                            ? seventeenColor
                            : Colors.grey[200]!,
                    textStyle: secondaryTextStyle.copyWith(
                      // color: secondaryColor,
                      fontSize: getProportionateScreenWidth(16),
                    ),
                    hintTextStyle: secondaryTextStyle.copyWith(
                      // color: secondaryColor,
                      fontSize: getProportionateScreenWidth(16),
                    ),
                    hintTextAlign: TextAlign.start,
                    padding: const EdgeInsets.all(3),
                    hintTextPadding: const EdgeInsets.all(0),
                    loadingBuilder: (context) {
                      return const Center(
                        child: CircularProgressIndicator(
                          strokeWidth: 0.4,
                        ),
                      );
                    },
                    onEditorCreated: () {
                    if (widget.quest.isNotEmpty) {
                      _controllerQuest.setText(widget.quest);
                    }
                  },
                  ),
                ),
                SizedBox(height: getProportionateScreenHeight(4)),
                
                 Align(
                  alignment: Alignment.topRight,
                  child: ElevatedButton(
                     onPressed: () async {
                    String currentTitle = _controllerTitle.text;
                    String currentQuest = await _controllerQuest.getText();

                    String currentQuestTrimmed = currentQuest.trim();
                    String initialQuestTrimmed = initialQuest.trim();

                    // Cek apakah ada perubahan
                    if (currentTitle == initialTitle &&
                        currentQuestTrimmed == initialQuestTrimmed) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          duration: Duration(seconds: 2),
                          backgroundColor: primaryColor,
                          content: Text(
                            'Tidak ada perubahan',
                            style: primaryTextStyle.copyWith(
                              color: Colors.white,
                            ),
                          ),
                          behavior: SnackBarBehavior.floating,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(5),
                          ),
                        ),
                      );
                    } else {
                     bool success = await editQnaProvider.editQna(
                       widget.id_course,
                       currentQuest,
                        int.parse(widget.id_qna.toString()),
                      currentTitle,
                        widget.id_lesson,
                      );
                      if (success) {
                        ScaffoldMessenger.of(globalScaffoldKey.currentContext!)
                            .showSnackBar(
                          SnackBar(
                            duration: Duration(seconds: 2),
                            backgroundColor: primaryColor,
                            content: Text(
                              'Pertanyaan berhasil diedit',
                              style: primaryTextStyle.copyWith(
                                color:Colors.white,
                              ),
                            ),
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(5),
                            ),
                          ),
                        );
                        _controllerQuest.clear();
                        _controllerTitle.clear();
                        Navigator.pop(context);
                      } else {
                        ScaffoldMessenger.of(globalScaffoldKey.currentContext!)
                            .showSnackBar(
                          SnackBar(
                            duration: Duration(seconds: 2),
                            backgroundColor: primaryColor,
                            content: Text(
                              'Terjadi kesalahan',
                              style: primaryTextStyle.copyWith(
                                color: Colors.white,
                              ),
                            ),
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(5),
                            ),
                          ),
                        );
                      }
                      }
                    },
                    child: Text(
                      'Edit Pertanyaan',
                      style: thirdTextStyle.copyWith(
                        color: Colors.white,
                        fontSize: SizeConfig.blockHorizontal! * 4,
                      ),
                      
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: primaryColor,
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
