import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/models/patient/progress_note_request.dart';
import 'package:doctor_app_flutter/widgets/shared/errors/dr_app_embedded_error.dart';
import 'package:doctor_app_flutter/widgets/shared/rounded_container_widget.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';

import '../../../config/shared_pref_kay.dart';
import '../../../config/size_config.dart';
import '../../../models/patient/patiant_info_model.dart';
import '../../../providers/patients_provider.dart';
import '../../../util/dr_app_shared_pref.dart';
import '../../../widgets/shared/app_scaffold_widget.dart';
import '../../../widgets/shared/app_texts_widget.dart';
import '../../../widgets/shared/dr_app_circular_progress_Indeicator.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();

/* 
 *@author: ibrahim albitar 
 *@Date:15/5/2020  
 *@param: '
 *@return:
 *@desc:
 */

class ProgressNoteScreen extends StatefulWidget {
  @override
  _ProgressNoteState createState() => _ProgressNoteState();
}

class _ProgressNoteState extends State<ProgressNoteScreen> {
  PatientsProvider patientsProv;
  var notesList;
  var filteredNotesList;
  final _controller = TextEditingController();
  var _isInit = true;

  /* 
 *@author: ibrahim al bitar 
 *@Date:16/5/2020  
 *@param: 
 *@return:
 *@desc:
 */
  getProgressNoteList(context) async {
    final routeArgs = ModalRoute.of(context).settings.arguments as Map;
    PatiantInformtion patient = routeArgs['patient'];
    String token = await sharedPref.getString(TOKEN);
    String type = await sharedPref.getString(SLECTED_PATIENT_TYPE);

    print(type);
    ProgressNoteRequest progressNoteRequest = ProgressNoteRequest(
        visitType: 5, // if equal 5 then this will return progress note
        admissionNo: int.parse(patient.admissionNo),
        projectID: patient.projectId,
        tokenID: token,
        patientTypeID: patient.patientType,
        languageID: 2);
    patientsProv.getPatientProgressNote(progressNoteRequest.toJson()).then((c){
      notesList = patientsProv.patientProgressNoteList;
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_isInit) {
      patientsProv = Provider.of<PatientsProvider>(context);
      getProgressNoteList(context);
      notesList = patientsProv.patientProgressNoteList;
    }
    _isInit = false;
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).progressNote,
      body: patientsProv.isLoading
          ? DrAppCircularProgressIndeicator()
          : patientsProv.isError
              ? DrAppEmbeddedError(error: patientsProv.error)
              : notesList == null
                  ? DrAppEmbeddedError(
                      error: TranslationBase.of(context).errorNoProgressNote)
                  : Column(
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.all(10),
                          width: SizeConfig.screenWidth * 0.80,
                          child: TextField(
                            controller: _controller,
                            onChanged: (String str) {
                              this.searchData(str);
                            },
                            textInputAction: TextInputAction.done,
                            decoration: buildInputDecoration(context,
                                TranslationBase.of(context).searchNote),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.fromLTRB(
                                SizeConfig.realScreenWidth * 0.05,
                                0,
                                SizeConfig.realScreenWidth * 0.05,
                                0),
                            child: ListView.builder(
                                itemCount: notesList.length,
                                itemBuilder: (BuildContext ctxt, int index) {
                                  return RoundedContainer(
                                      backgroundColor: Colors.white,
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          ExpansionTile(
                                            title: Container(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: <Widget>[
                                                  AppText(
                                                    notesList[index]
                                                        ["DoctorName"],
                                                    marginTop: 10,
                                                    marginLeft: 10,
                                                    marginBottom: 5,
                                                    fontWeight: FontWeight.bold,
                                                  ),
                                                  AppText(
                                                    convertDateFormat(
                                                        notesList[index]
                                                            ["AssessmentDate"]),
                                                    marginLeft: 10,
                                                    color: Colors.grey[600],
                                                  ),
                                                ],
                                              ),
                                            ),
                                            children: <Widget>[
                                              Divider(
                                                color: Colors.black,
                                                height: 20,
                                                thickness: 1,
                                                indent: 0,
                                                endIndent: 0,
                                              ),
                                              AppText(
                                                notesList[index]["Notes"],
                                                margin: 5,
                                              )
                                            ],
                                          ),
                                        ],
                                      ));
                                }),
                          ),
                        ),
                      ],
                    ),
    );
  }

  InputDecoration buildInputDecoration(BuildContext context, hint) {
    return InputDecoration(
        prefixIcon: Icon(Icons.search, color: Colors.black),
        filled: true,
        fillColor: Colors.white,
        hintText: hint,
        hintStyle: TextStyle(fontSize: 2 * SizeConfig.textMultiplier),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          borderSide: BorderSide(color: Hexcolor('#CCCCCC')),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          borderSide: BorderSide(color: Colors.grey), //),
        ));
  }

  searchData(String str) {
    var strExist = str.length > 0 ? true : false;

    if (strExist) {
      filteredNotesList = null;
      filteredNotesList = patientsProv.patientProgressNoteList
          .where((note) =>
              note["DoctorName"].toString().contains(str.toUpperCase()))
          .toList();
      setState(() {
        notesList = filteredNotesList;
      });
    } else {
      setState(() {
        notesList = patientsProv.patientProgressNoteList;
      });
    }
  }

  convertDateFormat(String str) {
    const start = "/Date(";
    const end = "+0300)";

    final startIndex = str.indexOf(start);
    final endIndex = str.indexOf(end, startIndex + start.length);

    var date = new DateTime.fromMillisecondsSinceEpoch(
        int.parse(str.substring(startIndex + start.length, endIndex)));
    String newDate = date.year.toString() +
        "-" +
        date.month.toString().padLeft(2, '0') +
        "-" +
        date.day.toString().padLeft(2, '0');

    return newDate.toString();
  }
}
