import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:healthcare_pharmacy/medicinedetailspage.dart';
import 'package:healthcare_pharmacy/models/GetMedecineDetailsModel.dart';
import 'package:healthcare_pharmacy/settings.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:cloudinary_public/cloudinary_public.dart';
import 'package:photo_view/photo_view.dart';


class GetMedicines extends StatefulWidget {
  var medicinebookingid;

  GetMedicines({
    this.medicinebookingid
  });

  @override
  State<GetMedicines> createState() => _GetMedicinesState();
}

class _GetMedicinesState extends State<GetMedicines> with TickerProviderStateMixin {
  bool isMedecineDataLoading=false;
  bool isSereverIssue = false;
  List<GetMedecineDetailsModel> medecineList = [];
  List<GetMedecineDetailsModel> FilteredList = [];
  String userAddress='';

  TextEditingController searchController = TextEditingController();
  String medicine_name='';
  String medicine_manufacturers='';
  String medicine_salt_composition='';
  String medicine_mrp='';
  String medicine_primary_use='';
  String medbookingid = '';
  List medImages=[];

  Future<void> getAllMedecineData(var medicineName) async {
    FilteredList=[];
    isMedecineDataLoading = true;
    try {
      var medecineResponse = await AppSettings.getAllMedecines(medicineName);

      print(jsonDecode(medecineResponse));
      if(jsonDecode(medecineResponse)!=''){
        setState(() {
          medicine_name=jsonDecode(medecineResponse)['medicine'][0]['name'];
          medicine_manufacturers=jsonDecode(medecineResponse)['medicine'][0]['manufacturers'];
          medicine_salt_composition=jsonDecode(medecineResponse)['medicine'][0]['salt_composition'];
          medicine_mrp=jsonDecode(medecineResponse)['medicine'][0]['mrp'];
          medicine_primary_use=jsonDecode(medecineResponse)['medicine'][0]['primary_use'];
          medImages=jsonDecode(medecineResponse)['imageUrls'];
          /* medecineList =
            ((jsonDecode(medecineResponse)['medicine']) as List).map((dynamic model) {
              return GetMedecineDetailsModel.fromJson(model);
            }).toList();*/
          isMedecineDataLoading = false;
        });
      }
      else{
        setState(() {
          medicine_name='';
          isMedecineDataLoading = false;
        });
      }



    } catch (e) {
      setState(() {
        medicine_name='';
        isMedecineDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    medbookingid=widget.medicinebookingid;
  }


  showPicDialog(var imageUrl){
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return AlertDialog(
                title: const Text(''),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: <Widget>[
                      Container(
                          width: MediaQuery.of(context).size.width * .10,
                          height: MediaQuery.of(context).size.height * .30,
                          child: PhotoView(
                            imageProvider: NetworkImage(imageUrl) as ImageProvider,
                            maxScale: PhotoViewComputedScale.contained * 4.0,
                            minScale: PhotoViewComputedScale.contained,
                            initialScale: PhotoViewComputedScale.contained,
                            basePosition: Alignment.center,

                          )
                      )
                    ],
                  ),
                ),
                actions: <Widget>[
                  TextButton(
                    child: Text('Close', style: textButtonStyle()),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            });
      },
    );
  }

  Widget _bindMedicines() {
    if (medicine_name!='') {
      return Padding(padding: EdgeInsets.all(10),
        child: Container(
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              GestureDetector(
                child: Container(
                  width: MediaQuery.of(context).size.width * .18,
                  height:
                  MediaQuery.of(context).size.height * .10,
                  decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      image: DecorationImage(
                          image: NetworkImage(medImages[0]) as ImageProvider, // picked file
                          fit: BoxFit.contain)),
                ),
                onTap: () async {
                  showPicDialog(medImages[0]);
                },
              ),
              GestureDetector(
                child: Column(
                  children: [
                    Text(("Name :"+ medicine_name),
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(("Manufacturers :"+ medicine_manufacturers),
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      medicine_salt_composition,
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(("Estimate Price :"+ medicine_mrp),
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(("Medicine_Use :"+ medicine_primary_use),
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                onTap: ()  {
                 /* Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (__) => new MedicineDetailsCount()));*/
                   Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (__) => new MedicineDetails(name: medicine_name,price: medicine_mrp,bookid:medbookingid)));
                },



              ),


            ],
          ),


        ),
      );
    }
    else {
      return Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: isSereverIssue
                ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  height: 20,
                ),
                Text(
                  'No medicine found with your search',style:serverIssueTextStyle() ,),
              ],
            )
                :  userAddress==''?Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.search,color: primaryColor,size: 40,),
                SizedBox(
                  height: 20,
                ),
                Text(
                  'Please enter atleast 4 letters to continue search',style:TextStyle(
                  color: primaryColor,
                  fontWeight: FontWeight.bold,
                ),),
              ],
            ):
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.dataset_rounded,color: primaryColor,size: 40,),
                SizedBox(
                  height: 20,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  'No medicine found with your search',style:serverIssueTextStyle() ,),
              ],
            ),
          ));
    }
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Medecine Details'),
        backgroundColor: primaryColor,),
      /* body: */
      body:  Container(
        //color: Colors.purpleAccent,
        child:Column(
          children: [
            Padding(padding:EdgeInsets.all(10) ,
              child: Container(
                  height: MediaQuery.of(context).size.height * .07,
                  padding:  EdgeInsets.all(5),
                  child: Center(child: TextField(

                    cursorColor: greyColor,
                    controller: searchController,
                    onChanged: (string) {
                      if(string.length>=1){
                         getAllMedecineData(searchController.text);
                      }
                      else{
                        setState(() {
                          medicine_name='';
                        });
                      }
                    },
                    decoration:  InputDecoration(
                      prefixIcon: Icon(
                        Icons.search,
                        color: greyColor,
                      ),
                      suffixIcon: IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: greyColor,
                        ),
                        onPressed: () {
                          setState(() {
                            searchController.text='';
                            medicine_name='';
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      //labelText: 'Search by phone number',
                      hintText: 'Search by medicine name',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),)
              ),),



            Expanded(child: Container(
              child:isMedecineDataLoading
                  ? Center(
                child: CircularProgressIndicator(
                  color: primaryColor,
                  strokeWidth: 5.0,
                ),
              )
                  : _bindMedicines() ,
            ))
          ],
        ),
      ),
    );
  }

}
