import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:healthcare_pharmacy/dashboard.dart';
import 'package:healthcare_pharmacy/settings.dart';
import 'package:intl/intl.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:image_picker/image_picker.dart';



class CompanyOffers extends StatefulWidget {
  var phid;

  CompanyOffers({
    this.phid
  });

  @override
  State<CompanyOffers> createState() => _CompanyOffersState();
}

class _CompanyOffersState extends State<CompanyOffers> {

  TextEditingController offer_nameController = TextEditingController();
  TextEditingController offer_codeController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();
  TextEditingController eligiblepharma_Controller = TextEditingController();
  TextEditingController starting_dateController = TextEditingController();
  TextEditingController ending_dateController = TextEditingController();

  var selIOS;
  final ImagePicker _picker = ImagePicker();
  String offerUrl='';
  String medphid="";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    medphid = widget.phid.toString();
    medphid = medphid.replaceAll('[', '').replaceAll(']', '');
    eligiblepharma_Controller.text = medphid;
  }


  Future pickImageFromGallery() async {

    try {
      final image = await _picker.pickImage(source: ImageSource.gallery);
      if (image == null) return;
      final imageTemp = File(image.path);

      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.offeruploadImageHTTPNew(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        AppSettings.offerPictureUrl = jsonDecode(res)['picture'];
      });
      AppSettings.saveData('offer', jsonDecode(res)['picture'], 'STRING');
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Future takeImageFromCamera() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) return;
      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.offeruploadImageHTTPNew(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        //AppSettings.offerPictureUrl = jsonDecode(res)['picture']['url'];
        offerUrl=jsonDecode(res)['picture'][0]['url'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          appBar: AppSettings.appBar('Cteate Offers'),
          body: Stack(children: <Widget>[

            GestureDetector(
              onTap: () {
                FocusManager.instance.primaryFocus?.unfocus();
              },
              child: SafeArea(
                  child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[

                        SizedBox(
                          height: 20,
                        ),
                        Container(child:  GestureDetector(
                          child: Container(
                            width: MediaQuery.of(context).size.width * .60,
                            height: MediaQuery.of(context).size.height * .15,
                            decoration: BoxDecoration(
                                shape: BoxShape.rectangle,
                                border: Border.all(width: 2, color: Colors.blueGrey),
                                image: DecorationImage(
                                    image: (offerUrl!= ''&&
                                        offerUrl!= 'null') ?
                                    NetworkImage(offerUrl) as ImageProvider : AssetImage("images/mobilebg.png"), // picked file
                                    fit: BoxFit.fitWidth)),
                          ),
                          onTap: () {
                            showModalBottomSheet<void>(
                                context: context,
                                builder: (BuildContext context) {
                                  return SizedBox(
                                    height: 200,
                                    child: Center(
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: <Widget>[
                                          GestureDetector(
                                            child: Icon(
                                              Icons.camera_alt_outlined,
                                              size: 100,
                                              color: primaryColor,
                                            ),
                                            onTap: () async {
                                              await takeImageFromCamera();
                                              Navigator.pop(context);
                                            },
                                          ),
                                          SizedBox(
                                            width:
                                            MediaQuery.of(context).size.width * .20,
                                          ),
                                          GestureDetector(
                                            child: Icon(
                                              Icons.photo,
                                              size: 100,
                                              color: primaryColor,
                                            ),
                                            onTap: () async {
                                              await pickImageFromGallery();
                                              Navigator.pop(context);
                                            },
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                });
                          },
                        ),),
                        SizedBox(
                          height: 05,
                        ),
                        Container(
                          padding: const EdgeInsets.all(10),
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: offer_nameController,
                            textCapitalization: TextCapitalization.words,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.person,
                                color: primaryColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: primaryColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              labelText: 'Enter Offer Name',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ), //name
                        SizedBox(
                          height: 05,
                        ),
                        Container(
                          padding: const EdgeInsets.all(10),
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: offer_codeController,
                            textCapitalization: TextCapitalization.words,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.numbers,
                                color: primaryColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: primaryColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              labelText: 'Enter Offer Code',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(
                          height: 5,
                        ),



                        Container(
                          padding: const EdgeInsets.all(10),
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: descriptionController,
                            textCapitalization: TextCapitalization.words,
                            keyboardType: TextInputType.multiline,
                            maxLines: null,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.description,
                                color:primaryColor,
                              ),
                              contentPadding: const EdgeInsets.symmetric(vertical:40.0, horizontal:30.0),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              labelText: 'Enter Offer Description',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.all(10),
                          child: TextFormField(
                            cursorColor: greyColor,
                            readOnly: true,
                            controller: eligiblepharma_Controller,
                            textCapitalization: TextCapitalization.characters,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.local_pharmacy,
                                color: primaryColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: primaryColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              labelText: 'Enter Eligible Pharmacies',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ), //mobile
                        const SizedBox(
                          height: 5,
                        ),
                        Container(
                          padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                          child: TextFormField(
                            readOnly: true,
                            cursorColor: greyColor,
                            controller: starting_dateController,
                            decoration: InputDecoration(
                              labelText: 'Select Start Date',
                              prefixIcon: const Icon(Icons.date_range, color: primaryColor,),
                              labelStyle: const TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                              border: const OutlineInputBorder(
                                  borderSide: BorderSide(color: primaryColor)),
                              focusedBorder: const OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              enabledBorder: const OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              suffixIcon: IconButton(
                                icon:  Icon(
                                  Icons.date_range,
                                ),
                                onPressed: () async {
                                  DatePicker.showDatePicker(
                                    context,
                                    dateFormat: 'dd MMMM yyyy',
                                    initialDateTime: DateTime.now(),
                                    minDateTime:DateTime.now(),
                                    maxDateTime: DateTime.now().add(Duration(days: 365)),
                                    onMonthChangeStartWithFirstDate: true,
                                    pickerMode: DateTimePickerMode.datetime,
                                    pickerTheme: DateTimePickerTheme(
                                      // backgroundColor: Colors.white,
                                      cancelTextStyle: labelTextStyle(),
                                      confirmTextStyle: labelTextStyle(),
                                      // showTitle: true,
                                      //title: Text('Pick date and time'),
                                      itemTextStyle: valuesTextStyle(),
                                    ),
                                    onConfirm: (dateTime, List<int> index)async {
                                      DateTime selectdate = dateTime;
                                      setState(() {
                                        selIOS = DateFormat('dd-MMM-yyyy').format(selectdate);
                                      });

                                      if(selIOS!=''){
                                        setState(() {
                                          starting_dateController.text=selIOS.toString();
                                        });
                                      }
                                      else {
                                        AppSettings.longFailedToast('please select date');
                                      }
                                    },
                                  );
                                },
                              ),

                            ),

                          ),
                        ),

                        const SizedBox(
                          height: 5,
                        ),
                        Container(
                          padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                          child: TextFormField(
                            readOnly: true,
                            cursorColor: greyColor,
                            controller: ending_dateController,
                            decoration: InputDecoration(
                              labelText: 'Select End Date',
                              prefixIcon: const Icon(Icons.date_range, color: primaryColor,),
                              labelStyle: const TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                              border: const OutlineInputBorder(
                                  borderSide: BorderSide(color: primaryColor)),
                              focusedBorder: const OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              enabledBorder: const OutlineInputBorder(
                                borderSide: BorderSide(color: primaryColor),
                              ),
                              suffixIcon: IconButton(
                                icon:  Icon(
                                  Icons.date_range,
                                ),
                                onPressed: () async {
                                  DatePicker.showDatePicker(
                                    context,
                                    dateFormat: 'dd MMMM yyyy',
                                    initialDateTime: DateTime.now(),
                                    minDateTime:DateTime.now(),
                                    maxDateTime: DateTime.now().add(Duration(days: 365)),
                                    onMonthChangeStartWithFirstDate: true,
                                    pickerMode: DateTimePickerMode.datetime,
                                    pickerTheme: DateTimePickerTheme(
                                      // backgroundColor: Colors.white,
                                      cancelTextStyle: labelTextStyle(),
                                      confirmTextStyle: labelTextStyle(),
                                      // showTitle: true,
                                      //title: Text('Pick date and time'),
                                      itemTextStyle: valuesTextStyle(),
                                    ),
                                    onConfirm: (dateTime, List<int> index)async {
                                      DateTime selectdate = dateTime;
                                      setState(() {
                                        selIOS = DateFormat('dd-MMM-yyyy').format(selectdate);
                                      });

                                      if(selIOS!=''){
                                        setState(() {
                                          ending_dateController.text=selIOS.toString();
                                        });
                                      }
                                      else {
                                        AppSettings.longFailedToast('please select date');
                                      }
                                    },
                                  );
                                },
                              ),

                            ),

                          ),
                        ),//address description

                        const SizedBox(
                          height:15,
                        ),
                        Container(
                            width:MediaQuery.of(context).size.width * .99,
                            height: 55,
                            padding: const EdgeInsets.fromLTRB(3, 0, 3, 0),
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: buttonColor, // background
                                onPrimary: Colors.white, // foreground
                              ),
                              onPressed: () async {
                                if (offer_nameController.text != '' &&
                                    offer_codeController.text != '' ) {
                                  AppSettings.preLoaderDialog(context);
                                  var payload = new Map<String, dynamic>();
                                  payload["offer_name"] = offer_nameController.text.toString();
                                  payload["offer_code"] = offer_codeController.text.toString();
                                  payload["description"] =  descriptionController.text.toString();
                                  payload["pharmacies_eligible"] = [eligiblepharma_Controller.text.toString()];
                                  payload["starting_date"] = starting_dateController.text.toString();
                                  payload["ending_date"] = ending_dateController.text.toString();
                                  payload["offer_status"] ="active";
                                  bool offerStatus = await AppSettings.createCompanyOffers(payload);
                                  try{
                                    if (offerStatus) {
                                      Navigator.pop(context);
                                      Navigator.of(context,rootNavigator: true).pop();
                                     Navigator.push(
                                        context,
                                        MaterialPageRoute(builder: (context) => Dashboard()),
                                      );
                                      AppSettings.longSuccessToast("Company Offer Created Succesfully!!");
                                    } else {
                                     AppSettings.longFailedToast("Fields should not be empty !!");
                                    }
                                  }
                                  catch(exception){
                                    print(exception);
                                    AppSettings.longFailedToast("Please enter valid details");
                                  }
                                } else {
                                  AppSettings.longFailedToast("Company Offer Not Created!!");

                                }
                              },
                              child: Text('Create'),
                            )),//login button

                      ],
                    ),
                  )),
            ),
          ])), );
  }
}
