import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/viewModel/patient_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/models/patient/insurance_aprovals_request.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.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 '../../../config/shared_pref_kay.dart';
import '../../../config/size_config.dart';
import '../../../models/patient/patiant_info_model.dart';
import '../../../util/dr_app_shared_pref.dart';
import '../../../widgets/shared/app_scaffold_widget.dart';
import '../../../widgets/shared/app_texts_widget.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();

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

class InsuranceApprovalsScreen extends StatefulWidget {
  @override
  _InsuranceApprovalsState createState() => _InsuranceApprovalsState();
}

class _InsuranceApprovalsState extends State<InsuranceApprovalsScreen> {
  var approvalsList;
  var filteredApprovalsList;
  final _controller = TextEditingController();

  /* 
 *@author: ibrahim al bitar 
 *@Date:21/5/2020  
 *@param: 
 *@return:
 *@desc:
 */
  getInsuranceApprovalsList(
      BuildContext context, PatientViewModel model) 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);
    InsuranceAprovalsRequest insuranceApprovalsRequest =
        InsuranceAprovalsRequest(
            patientID: patient.patientId,
            projectID: patient.projectId,
            tokenID: token,
            patientTypeID: patient.patientType,
            languageID: 2);
    model
        .getPatientInsuranceApprovals(insuranceApprovalsRequest.toJson()).then((c){
      approvalsList = model.insuranceApporvalsList;
    });
  }


  @override
  Widget build(BuildContext context) {
    return BaseView<PatientViewModel>(
      onModelReady: (model) => getInsuranceApprovalsList(context, model),
      builder: (_, model, w) =>
          AppScaffold(
            baseViewModel: model,
            appBarTitle: TranslationBase
                .of(context)
                .insuranceApprovals,
            body: model.insuranceApporvalsList == null ||
                model.insuranceApporvalsList.length == 0
                ? DrAppEmbeddedError(
                error:
                TranslationBase
                    .of(context)
                    .errorNoInsuranceApprovals)
                : Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.all(10),
                  width: SizeConfig.screenWidth * 0.80,
                  child: TextField(
                    controller: _controller,
                    onChanged: (String str) {
                      this.searchData(str, model);
                    },
                    textInputAction: TextInputAction.done,
                    decoration: buildInputDecoration(
                        context,
                        TranslationBase
                            .of(context)
                            .searchInsuranceApprovals),
                  ),
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.fromLTRB(
                        SizeConfig.realScreenWidth * 0.05,
                        0,
                        SizeConfig.realScreenWidth * 0.05,
                        0),
                    child: ListView.builder(
                        itemCount: approvalsList.length,
                        itemBuilder: (BuildContext ctxt, int index) {
                                  return RoundedContainer(
                                      child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      ExpansionTile(
                                        title: Row(
                                          children: <Widget>[
                                            Column(
                                              children: <Widget>[
                                                Icon(
                                                  approvalsList[index][
                                                              "ApprovalStatusDescption"]
                                                          .toString()
                                                          .contains("Approved")
                                                      ? DoctorApp.approved_icon
                                                      : approvalsList[index][
                                                                  "ApprovalStatusDescption"]
                                                              .toString()
                                                              .contains(
                                                                  "Cancelled")
                                                          ? DoctorApp
                                                              .reject_icon
                                                          : DoctorApp
                                                              .pending_icon,
                                                  color: approvalsList[index][
                                                              "ApprovalStatusDescption"]
                                                          .toString()
                                                          .contains("Approved")
                                                      ? Colors.green
                                                      : approvalsList[index][
                                                                  "ApprovalStatusDescption"]
                                                              .toString()
                                                              .contains(
                                                                  "Cancelled")
                                                          ? Colors.red
                                                          : Colors.yellow,
                                                ),
                                                AppText(
                                                  approvalsList[index][
                                                      "ApprovalStatusDescption"],
                                                  fontSize: SizeConfig
                                                          .textMultiplier *
                                                      1.5,
                                                  color: approvalsList[index][
                                                              "ApprovalStatusDescption"]
                                                          .toString()
                                                          .contains("Approved")
                                                      ? Colors.green
                                                      : approvalsList[index][
                                                                  "ApprovalStatusDescption"]
                                                              .toString()
                                                              .contains(
                                                                  "Cancelled")
                                                          ? Colors.red
                                                          : Colors.yellow,
                                                )
                                              ],
                                            ),
                                            Expanded(
                                              child: Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: <Widget>[
                                                  AppText(
                                                    approvalsList[index]
                                                        ["ClinicName"],
                                                    marginTop: 10,
                                                    marginLeft: 10,
                                                    marginBottom: 5,
                                                    fontWeight: FontWeight.bold,
                                                  ),
                                                  AppText(
                                                    approvalsList[index]
                                                        ["DoctorName"],
                                                    marginLeft: 10,
                                                    marginTop: 1,
                                                  ),
                                                  AppText(
                                                    convertDateFormat(
                                                        approvalsList[index]
                                                            ["ApprovalDate"]),
                                                    marginLeft: 10,
                                                    marginBottom: 5,
                                                    color: Colors.grey[600],
                                                  ),
                                                ],
                                              ),
                                            )
                                          ],
                                        ),
                                        children: <Widget>[
                                          Divider(
                                            color: Colors.black,
                                            height: 20,
                                            thickness: 1,
                                            indent: 0,
                                            endIndent: 0,
                                          ),
                                          RoundedContainer(
                                              backgroundColor:
                                                  Color(PRIMARY_COLOR),
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: <Widget>[
                                                  AppText(
                                                    approvalsList[index]
                                                            ["ApprovalNo"]
                                                        .toString(),
                                                    color: Colors.white,
                                                    fontSize: 19,
                                                    fontWeight: FontWeight.bold,
                                                    marginTop: 10,
                                                    marginLeft: 10,
                                                    marginRight: 10,
                                                    marginBottom: 2,
                                                  ),
                                                  AppText(
                                                    TranslationBase.of(context)
                                                        .approvalNo,
                                                    color: Colors.white,
                                                    fontSize: 16,
                                                    marginTop: 2,
                                                    marginLeft: 10,
                                                    marginBottom: 15,
                                                    marginRight: 10,
                                                  ),
                                                  Row(
                                                    children: <Widget>[
                                                      Expanded(
                                                        flex: 1,
                                                        child: Column(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          children: <Widget>[
                                                            AppText(
                                                              TranslationBase.of(
                                                                      context)
                                                                  .producerName,
                                                              fontSize: 10,
                                                              color:
                                                                  Colors.white,
                                                              marginLeft: SizeConfig
                                                                      .widthMultiplier *
                                                                  3,
                                                            ),
                                                            AppText(
                                                              checkList(approvalsList[
                                                                          index]
                                                                      [
                                                                      "ApporvalDetails"])
                                                                  ? approvalsList[
                                                                              index]
                                                                          [
                                                                          "ApporvalDetails"][0]
                                                                      [
                                                                      "ProcedureName"]
                                                                  : "",
                                                              fontSize: 12,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold,
                                                              marginLeft: SizeConfig
                                                                      .widthMultiplier *
                                                                  3,
                                                              marginTop: 3,
                                                              color:
                                                                  Colors.white,
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                      Expanded(
                                                        flex: 1,
                                                        child: Column(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          children: <Widget>[
                                                            AppText(
                                                              TranslationBase.of(
                                                                      context)
                                                                  .status,
                                                              fontSize: 10,
                                                              color:
                                                                  Colors.white,
                                                              marginLeft: SizeConfig
                                                                      .widthMultiplier *
                                                                  9,
                                                            ),
                                                            AppText(
                                                              approvalsList[
                                                                      index][
                                                                  "ApprovalStatusDescption"],
                                                              fontSize: 12,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold,
                                                              marginLeft: SizeConfig
                                                                      .widthMultiplier *
                                                                  9,
                                                              marginTop: 3,
                                                              color:
                                                                  Colors.white,
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  Row(
                                                    children: <Widget>[
                                                      Expanded(
                                                        flex: 1,
                                                        child: Column(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          children: <Widget>[
                                                            AppText(
                                                              TranslationBase.of(
                                                                      context)
                                                                  .receiptOn,
                                                              fontSize: 10,
                                                              color:
                                                                  Colors.white,
                                                              marginLeft: SizeConfig
                                                                      .widthMultiplier *
                                                                  3,
                                                              marginTop: SizeConfig
                                                                      .heightMultiplier *
                                                                  1.5,
                                                            ),
                                                            AppText(
                                                              convertDateFormat(
                                                                  approvalsList[
                                                                          index]
                                                                      [
                                                                      "ReceiptOn"]),
                                                              fontSize: 12,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold,
                                                              marginLeft: SizeConfig
                                                                      .widthMultiplier *
                                                                  3,
                                                              marginTop: 3,
                                                              marginBottom:
                                                                  SizeConfig
                                                                          .heightMultiplier *
                                                                      2,
                                                              color:
                                                                  Colors.white,
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                      Expanded(
                                                        flex: 1,
                                                        child: Column(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          children: <Widget>[
                                                            AppText(
                                                              TranslationBase.of(
                                                                      context)
                                                                  .expiryDate,
                                                              fontSize: 10,
                                                              color:
                                                                  Colors.white,
                                                              marginTop: SizeConfig
                                                                      .heightMultiplier *
                                                                  1.5,
                                                              marginLeft: SizeConfig
                                                                      .widthMultiplier *
                                                                  9,
                                                            ),
                                                            AppText(
                                                              convertDateFormat(
                                                                  approvalsList[
                                                                          index]
                                                                      [
                                                                      "ExpiryDate"]),
                                                              fontSize: 12,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold,
                                                              marginLeft: SizeConfig
                                                                      .widthMultiplier *
                                                                  9,
                                                              marginTop: 3,
                                                              marginBottom:
                                                                  SizeConfig
                                                                          .heightMultiplier *
                                                                      2,
                                                              color:
                                                                  Colors.white,
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ],
                                              )),
                                        ],
                                      ),
                                    ],
                                      ));
                        }),
                  ),
                ),
              ],
            ),
          ),);
  }

  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, PatientViewModel model) {
    var strExist = str.length > 0 ? true : false;

    if (strExist) {
      filteredApprovalsList = null;
      filteredApprovalsList = approvalsList
          .where((note) =>
          note["ClinicName"].toString().contains(str.toUpperCase()))
          .toList();
      setState(() {
        approvalsList = filteredApprovalsList;
      });
    } else {
      setState(() {
        approvalsList = model.insuranceApporvalsList;
      });
    }
  }

  convertDateFormat(String str) {
    if (str == null) return '';
    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();
  }

  bool checkList(List list) {
    return list.length > 0 ? true : false;
  }
}
