import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';

import '../models/disease.dart';
import '../models/disease_description_point.dart';
import '../widgets/side_drawer.dart';
import 'disease_details_screen.dart';

class DiseaseList extends StatefulWidget {
  const DiseaseList({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<DiseaseList> createState() => _DiseaseListState();
}

class _DiseaseListState extends State<DiseaseList> {
  Client client = http.Client();
  List<String> diseases = [];
  List<Disease> allDiseaseList = [];
  List<String> diseaseDescriptions = [];
  List<DiseaseDescriptionPoint> diseaseDescriptionsList = [];

  @override
  void initState() {
    _retrieveDiseases();
    super.initState();
  }

  _retrieveDiseaseDescription(disease) async {
    diseaseDescriptions = [];
    String retrieveUri = "http://192.168.1.102:8000/disease/" + disease + "/";
    List responses = json.decode(
        utf8.decode((await client.get(Uri.parse(retrieveUri))).bodyBytes));

    for (var element in responses) {
      // String res = element.substring(element.indexOf('#'));
      // String res2 = res.replaceAll("#", "");
      var encoded = utf8.encode(element);
      var decoded = utf8.decode(encoded);
      var formatted = decoded.substring(1);
      diseaseDescriptions.add(formatted);
    }
    var newDiseases = List<String>.from(diseaseDescriptions);
    diseaseDescriptionsList = List.generate(
        diseaseDescriptions.length,
        (index) => DiseaseDescriptionPoint(
            descriptionPoint: diseaseDescriptions[index]));
    setState(() {});
  }

  _retrieveDiseases() async {
    diseases = [];
    String retrieveUri = "https://canis-care-app.herokuapp.com/diseases/";
    List responses =
        json.decode((await client.get(Uri.parse(retrieveUri))).body);

    for (var element in responses) {
      // String res = element.substring(element.indexOf('#'));
      // String res2 = res.replaceAll("#", "");
      diseases.add(element);
    }
    // var newDiseases = List<String>.from(diseases);
    allDiseaseList = List.generate(
        diseases.length, (index) => Disease(diseaseName: diseases[index]));
    diseaseList = List.from(allDiseaseList);
    setState(() {});
  }

  List<Disease> diseaseList = [];

  void updateDiseaseList(String item) {
    setState(() {
      diseaseList = allDiseaseList
          .where((element) =>
              element.diseaseName.toLowerCase().contains(item.toLowerCase()))
          .toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: SideDrawer(),
      appBar: AppBar(
        title: Text(widget.title, textAlign: TextAlign.center),
        actions: [
          Container(
            margin: const EdgeInsets.only(right: 40),
            padding: EdgeInsets.all(10.0),
            child: ClipOval(
              child: Icon(Icons.ac_unit_rounded),
            ),
          )
        ],
      ),

      body: RefreshIndicator(
        onRefresh: () async {
          _retrieveDiseases();
        },
        child: Container(
          color: Colors.blue[100],
          child: Column(children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: TextField(
                onChanged: (value) => updateDiseaseList(value),
                style: TextStyle(color: Colors.white),
                decoration: InputDecoration(
                    filled: true,
                    fillColor: Color(0xff302390),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8.0),
                        borderSide: BorderSide.none),
                    hintText: "Search diseases...",
                    hintStyle: TextStyle(color: Colors.cyan),
                    prefixIcon: Icon(
                      Icons.search,
                      color: Colors.white,
                    ),
                    prefixIconColor: Colors.purple.shade900),
              ),
            ),
            Expanded(
              child: Container(
                margin: const EdgeInsets.only(top: 0.0),
                child: RawScrollbar(
                  thumbColor: Colors.redAccent,
                  radius: Radius.circular(10),
                  thickness: 10,
                  child: ListView.builder(
                    itemCount: diseaseList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return AnimationConfiguration.staggeredGrid(
                        position: index,
                        columnCount: diseaseList.length,
                        child: SlideAnimation(
                          child: FadeInAnimation(
                            child: GestureDetector(
                              onTap: () {
                                Navigator.of(context).push(
                                  MaterialPageRoute(
                                      builder: (context) => DiseaseDetails(
                                            disease: diseaseList[index],
                                          )),
                                );
                              },
                              child: Container(
                                margin: const EdgeInsets.only(top: 10.0),
                                padding: const EdgeInsets.only(
                                    left: 5.0, right: 5.0),
                                child: Container(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 20),
                                  width: MediaQuery.of(context).size.width,
                                  margin: const EdgeInsets.only(bottom: 12),
                                  child: Container(
                                    padding: const EdgeInsets.all(16),
                                    //  width: SizeConfig.screenWidth * 0.78,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(16),
                                      color: Colors.blue,
                                    ),
                                    child: Row(children: [
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              diseaseList[index].diseaseName,
                                              style: GoogleFonts.lato(
                                                textStyle: const TextStyle(
                                                    fontSize: 18,
                                                    fontWeight: FontWeight.bold,
                                                    color: Colors.white),
                                              ),
                                            ),
                                            const SizedBox(
                                              height: 12,
                                            ),
                                            Row(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.center,
                                              children: [
                                                Icon(
                                                  Icons.remove_red_eye_outlined,
                                                  size: 22,
                                                ),
                                                const SizedBox(width: 8),
                                                // Text(
                                                //   "Get More...",
                                                //   style: GoogleFonts.lato(
                                                //     textStyle: TextStyle(
                                                //       fontSize: 15,
                                                //       fontWeight: FontWeight.w800,
                                                //     ),
                                                //   ),
                                                // ),
                                                Padding(
                                                  padding:
                                                      const EdgeInsets.all(0),
                                                  child: FlatButton(
                                                    onPressed: () {
                                                      Navigator.of(context)
                                                          .push(
                                                        MaterialPageRoute(
                                                            builder: (context) =>
                                                                DiseaseDetails(
                                                                  disease:
                                                                      diseaseList[
                                                                          index],
                                                                )),
                                                      );
                                                    },
                                                    color: Colors.cyan,
                                                    shape:
                                                        RoundedRectangleBorder(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        50)),
                                                    padding:
                                                        const EdgeInsets.all(5),
                                                    child: const Text(
                                                      "Get More",
                                                      style: TextStyle(
                                                          color: Colors.black,
                                                          fontSize: 15,
                                                          fontWeight:
                                                              FontWeight.bold),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                            const SizedBox(height: 12),
                                          ],
                                        ),
                                      ),
                                      Container(
                                        margin: const EdgeInsets.symmetric(
                                            horizontal: 10),
                                        height: 60,
                                        width: 1,
                                        color:
                                            Colors.grey[200]!.withOpacity(0.7),
                                      ),
                                      /* RotatedBox(
                    quarterTurns: 3,
                    child: Text(
                      reminder!.isCompleted == 1 ? "NOTED" : "WAITING",
                      style: GoogleFonts.lato(
                        textStyle: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                              color: Colors.white),
                      ),
                    ),
                  ),*/
                                      IconButton(
                                        onPressed: () async {
                                          await _retrieveDiseaseDescription(
                                              diseaseList[index].diseaseName);
                                          _showTestDialog(
                                              context,
                                              diseaseList[index].diseaseName,
                                              diseaseDescriptionsList,
                                              diseaseList[index]);
                                        },
                                        icon: const Icon(
                                          Icons.perm_device_info_rounded,
                                          size: 30,
                                        ),
                                      ),
                                    ]),
                                  ),
                                ),
                                // child: Container(
                                //   width: MediaQuery.of(context).size.width,
                                //   padding: const EdgeInsets.all(15.0),
                                //   child: ListTile(
                                //     title: Text(
                                //       diseaseList[index].diseaseName,
                                //       style: const TextStyle(
                                //           fontSize: 20, fontWeight: FontWeight.w600),
                                //     ),
                                //     onTap: () {
                                //       Navigator.of(context).push(
                                //         MaterialPageRoute(
                                //             builder: (context) => DiseaseDetails(
                                //                   disease: diseaseList[index],
                                //                 )),
                                //       );
                                //     },
                                //     trailing: IconButton(
                                //         icon: const Icon(Icons.view_headline_sharp),
                                //         // onPressed: () => {_deleteNote((notes[index].id).toString())},
                                //         onPressed: () => {
                                //               Navigator.of(context).push(
                                //                 MaterialPageRoute(
                                //                     builder: (context) => OnBoarding()),
                                //               )
                                //             }),
                                //   ),
                                // ),
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ),
            ),
          ]),
        ),
      ),
      // floatingActionButton: FloatingActionButton(
      //   onPressed: () => Navigator.of(context).push(MaterialPageRoute(
      //       builder: (context) => CreatePage(
      //             client: client,
      //           ))),
      //   tooltip: 'Increment',
      //   child: const Icon(Icons.add),
      // ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _showTestDialog(
      BuildContext context,
      String diseaseName,
      List<DiseaseDescriptionPoint> diseaseDescriptionsList,
      Disease diseaseList) {
    showDialog(
        context: context,
        barrierDismissible: false,
        //context: _scaffoldKey.currentContext,
        builder: (context) {
          return AlertDialog(
            backgroundColor: Colors.blue[100],
            elevation: 50.0,
            contentPadding: EdgeInsets.only(left: 25, right: 25),
            title: Center(child: Text("About " + diseaseName)),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(20.0))),
            content: Container(
              height: 440,
              width: 600,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(top: 10.0),
                      child: SizedBox(
                        height: 200,
                        child: RawScrollbar(
                          thumbColor: Colors.redAccent,
                          radius: Radius.circular(20),
                          thickness: 10,
                          child: ListView.builder(
                              itemCount: diseaseDescriptionsList.length,
                              itemBuilder: (BuildContext context, int index) {
                                return AnimationConfiguration.staggeredGrid(
                                  columnCount: diseaseDescriptionsList.length,
                                  position: index,
                                  child: SlideAnimation(
                                    child: FadeInAnimation(
                                      child: Container(
                                        decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(16),
                                          color: Colors.blue,
                                        ),
                                        margin: EdgeInsets.only(top: 5.0),
                                        child: Card(
                                          elevation: 5.0,
                                          child: ListTile(
                                            title: Text(
                                              diseaseDescriptionsList[index]
                                                  .descriptionPoint,
                                              style: GoogleFonts.lato(
                                                textStyle: const TextStyle(
                                                  fontSize: 18,
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              }),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            actions: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: MediaQuery.of(context).size.width * 0.20,
                    margin: EdgeInsets.only(
                        left: MediaQuery.of(context).size.width * 0.1),
                    child: RaisedButton(
                      child: Text(
                        'More...',
                        style: TextStyle(color: Colors.white),
                      ),
                      color: Color(0xFF32CD32),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.0),
                      ),
                      onPressed: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                              builder: (context) => DiseaseDetails(
                                    disease: diseaseList,
                                  )),
                        );
                      },
                    ),
                  ),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.1,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(right: 40.0),
                    child: Container(
                      width: MediaQuery.of(context).size.width * 0.20,
                      child: RaisedButton(
                        child: new Text(
                          'Close',
                          style: TextStyle(color: Colors.white),
                        ),
                        color: Color(0xFFFF0000),
                        shape: new RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(30.0),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.02,
                  ),
                ],
              )
            ],
          );
        });
  }
}
