import 'package:flutter/material.dart';
import 'package:initial_folder/models/announcement_model.dart';
import 'package:initial_folder/providers/announcement_provider.dart';
import 'package:initial_folder/providers/posting_announcement_reply_provider.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/announcement_user.dart';
import 'package:initial_folder/widgets/reply_announcement_user_page.dart';
import 'package:provider/provider.dart';

import '../../../get_it.dart';

final scaffoldKey = GlobalKey<ScaffoldState>();

class InsideAnnouncement extends StatefulWidget {
  const InsideAnnouncement({
    Key? key,
    required this.id,
    required this.announcementDataModel,
    required this.index,
    required this.userId,
  }) : super(key: key);
  final AnnouncementDataModel announcementDataModel;
  final id;

  final int index;
  final int userId;
  @override
  State<InsideAnnouncement> createState() => _InsideAnnouncementState();
}

class _InsideAnnouncementState extends State<InsideAnnouncement> {
  final _controller = TextEditingController();
  final provider = announcementGetIt<AnnouncementProvider>();
  late Widget announcement;

  @override
  Widget build(BuildContext context) {
    PostingAnnouncementReplyProvider postingAnnouncementReplyProvider =
        Provider.of<PostingAnnouncementReplyProvider>(context);

    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
        title: Text(
          'Pengumuman',
          style: primaryTextStyle.copyWith(
            fontWeight: semiBold,
            fontSize: getProportionateScreenWidth(16),
            letterSpacing: 0.2,
          ),
        ),
      ),
      body: GestureDetector(
        // onTap: () => FocusScope.of(context).unfocus(),
        child: Stack(
          children: [
            ListView(
              children: [
                // QnaUser(
                //   qnaDataModel: widget.qnaDataModel,
                //   id: widget.id,
                //   index: widget.index,
                //   userId: widget.userId,
                // ),
                StreamBuilder<AnnouncementModel>(
                    stream: provider.announcementStream,
                    builder:
                        (context, AsyncSnapshot<AnnouncementModel> snapshot) {
                      if (snapshot.hasError) {
                        return Center(
                          child: Text(
                            'Terjadi Kesalahan',
                            style: thirdTextStyle,
                          ),
                        );
                      } else {
                        switch (snapshot.connectionState) {
                          case ConnectionState.waiting:
                            announcement = Center(
                              child: CircularProgressIndicator(
                                color: primaryColor,
                                strokeWidth: 2,
                              ),
                            );
                            break;
                          case ConnectionState.none:
                            announcement = Center(
                              child: Text(
                                'Tidak ada koneksi',
                                style: thirdTextStyle,
                              ),
                            );
                            break;
                          case ConnectionState.active:
                            print('masuk siniiiiiiiiiii active' +
                                snapshot.data!.error.toString());
                            announcement = snapshot.data!.data[0].length > 0
                                ? Container(
                                    padding: EdgeInsets.only(top: 12),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.only(
                                            bottomRight: Radius.circular(10),
                                            bottomLeft: Radius.circular(10)),
                                        color: Theme.of(context)
                                            .colorScheme
                                            .primaryContainer,
                                        boxShadow: [
                                          BoxShadow(
                                              color: Theme.of(context)
                                                          .brightness ==
                                                      Brightness.dark
                                                  ? Color(0xff212643)
                                                  : Colors.grey,
                                              blurRadius: 0.5,
                                              offset: Offset(0, 2),
                                              spreadRadius: 0.001)
                                        ]),
                                    child: AnnouncementUser(
                                      announcementDataModel:
                                          snapshot.data!.data[0][widget.index],
                                      id: widget.id,
                                      index: widget.index,
                                      userId: widget.userId,
                                    ))
                                : Center(
                                    child: Text(
                                      'Belum ada pengumuman',
                                      style: thirdTextStyle,
                                    ),
                                  );
                            break;
                          case ConnectionState.done:
                            announcement = snapshot.data!.data[0].length > 0
                                ? AnnouncementUser(
                                    announcementDataModel:
                                        snapshot.data!.data[0][widget.index],
                                    id: widget.id,
                                    index: widget.index,
                                    userId: widget.userId,
                                  )
                                : Center(
                                    child: Text(
                                      'Belum ada pertanyaan',
                                      style: thirdTextStyle,
                                    ),
                                  );
                            break;
                        }
                      }
                      return announcement;
                    }),

                Padding(
                  padding: EdgeInsets.symmetric(
                      horizontal: getProportionateScreenWidth(16),
                      vertical: getProportionateScreenWidth(8)),
                  child: InkWell(
                    onTap: () {},
                    child: Text(
                      'Balasan',
                      style: thirdTextStyle.copyWith(
                          color: Theme.of(context).colorScheme.onBackground,
                          fontWeight: semiBold,
                          fontSize: getProportionateScreenWidth(16),
                          letterSpacing: 1),
                    ),
                  ),
                ),
                SizedBox(height: getProportionateScreenHeight(13)),
                ReplyAnnouncementUserPage(
                  idCourse: widget.id,
                  index: widget.index,
                  userId: widget.userId,
                ),
                SizedBox(height: 50)
              ],
            ),
            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(
                          controller: _controller,
                          scrollPadding: EdgeInsets.zero,
                          cursorColor: secondaryColor,
                          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",
                          ),
                        ),
                      ),
                      ElevatedButton(
                        onPressed: () async {
                          if (await postingAnnouncementReplyProvider
                              .postAnnouncementReply(
                            _controller.text,
                            widget.announcementDataModel.idAnnouncement
                                .toString(),
                            widget.announcementDataModel.tokenAnnouncement
                                .toString(),
                            widget.announcementDataModel.idAnnouncement
                                .toString(),
                          )) {
                            provider.getAnnouncement(widget.id);
                            _controller.clear();
                            ScaffoldMessenger.of(scaffoldKey.currentContext!)
                                .showSnackBar(
                              SnackBar(
                                duration: Duration(seconds: 2),
                                backgroundColor: primaryColor,
                                content: Text(
                                  'Balasan Terkirim',
                                  style: primaryTextStyle.copyWith(
                                      color: backgroundColor),
                                ),
                                behavior: SnackBarBehavior.floating,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(5),
                                ),
                                action: SnackBarAction(
                                  label: 'Lihat',
                                  onPressed: () {
                                    ScaffoldMessenger.of(
                                            scaffoldKey.currentContext!)
                                        .hideCurrentSnackBar();
                                  },
                                ),
                              ),
                            );
                          } else {
                            ScaffoldMessenger.of(scaffoldKey.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),
                                ),
                              ),
                            );
                          }
                        },
                        child: Text(
                          'Kirim',
                          style: thirdTextStyle.copyWith(
                            color: Colors.white,
                            letterSpacing: 0.3,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: primaryColor,
                          minimumSize: Size(
                            getProportionateScreenWidth(35),
                            getProportionateScreenWidth(35),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
