import 'dart:convert';
import 'dart:io';
import 'package:capture/common/settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/medicinesdata_model.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:image_picker/image_picker.dart';
class MedicineCapture extends StatefulWidget {
  const MedicineCapture({Key? key}) : super(key: key);

  @override
  State<MedicineCapture> createState() => _MedicineCaptureState();
}

class _MedicineCaptureState extends State<MedicineCapture> {
  bool isLoading = false;
  bool isSereverIssue = false;
  List<MedicinesDataModel> medicinesList = [];
  List<MedicinesDataModel> FilteredList = [];
  SwiperController _controller = SwiperController();
  SwiperControl _control = SwiperControl(color: Colors.white);
  double get _width => MediaQuery.of(context).size.width;
  double get _height => MediaQuery.of(context).size.height;
  bool inFirstPage = true;
  bool inLastPage = false;
  int currentIndex = 0;
  List uiMedicineImages = [];
  String reportsPictureId = '';
  Map<String,dynamic> reports={};
  final ImagePicker _picker = ImagePicker();

  Future<void> getAllMedicines() async {
    isLoading = true;

    try {
      var pharmacyResponse = await AppSettings.getAllMedicinesData();

      setState(() {
        medicinesList = ((jsonDecode(pharmacyResponse)['medicine']) as List)
            .map((dynamic model) {
          return MedicinesDataModel.fromJson(model);
        }).toList();

        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
        isSereverIssue = true;
      });
    }
  }

  Widget captureMedicineUi() {
    if (medicinesList.length != 0) {
      return Column(
        children: <Widget>[
          Container(
            //color: Colors.red,
            child: Row(
              children: <Widget>[
                Visibility(
                  visible: !inFirstPage,
                  child: TextButton(
                    child: const Text(
                      'Previous',
                      style: TextStyle(
                        fontSize: 15,
                        color: primaryColor,
                        decoration: TextDecoration.underline,
                      ),
                    ),
                    onPressed: () {
                      _controller.previous();
                    },
                  ),
                ),
                Spacer(),
                Visibility(
                  visible: !inLastPage,
                  child: TextButton(
                    child: const Text(
                      'More Tanks ----> Next',
                      style: TextStyle(
                        fontSize: 15,
                        color: primaryColor,
                        decoration: TextDecoration.underline,
                      ),
                    ),
                    onPressed: () {
                      _controller.next();
                    },
                  ),
                )
              ],
            ),
          ),
          Expanded(
            child: Container(
              color: Colors.white,
              child: Swiper(
                controller: _controller,
                //control:_control,
                loop: false,

                scrollDirection: Axis.horizontal,
                itemCount: medicinesList.length,
                onIndexChanged: (value) {
                  if (value == medicinesList.length - 1)
                    setState(() {
                      inLastPage = true;
                    });
                  else if (value == 0)
                    setState(() {
                      inFirstPage = true;
                    });
                  else {
                    setState(() {
                      inFirstPage = false;
                      inLastPage = false;
                    });
                  }

                },

                itemBuilder: (context, index) {
                  return Padding(
                    padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                    child: Center(
                        child: Row(
                          children: [
                            Container(
                                height: MediaQuery.of(context).size.height * .18,
                                width: MediaQuery.of(context).size.width * .35,
                                decoration: BoxDecoration(
                                    //color: medicinesList[index].cardColor,
                                    border: Border.all(
                                      width: 0,
                                      color: screenBackgroundColor,
                                    ),
                                    borderRadius: BorderRadius.circular(
                                      20,
                                    )),
                                child: Padding(
                                  padding: EdgeInsets.fromLTRB(20, 20, 30, 0),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                          medicinesList[index]
                                              .medicine_name
                                              .toString()
                                              .toUpperCase(),
                                          style: valuesTextStyle()),

                                    ],
                                  ),
                                )),
                          ],
                        )),
                  );
                },
              ),
            ),
          ),
        ],
      );
    } else {
      return Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(
                  height: MediaQuery.of(context).size.height * .25,
                ),
                Text('No medicines available'),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: primaryColor,
                  radius: 40,
                  child: IconButton(
                    iconSize: 40,
                    icon: const Icon(
                      Icons.add,
                      color: Colors.white,
                    ),
                    onPressed: () async {
                      // Navigator.pop(context);
                      // await Navigator.push(
                      //   context,
                      //   MaterialPageRoute(builder: (context) => AddTanks()),
                      // );
                    },
                  ),
                )
              ],
            ),
          ));
    }
  }

  void displayNextItem() {
    setState(() {
      if (currentIndex < medicinesList.length - 1) {
        currentIndex++;
      }
    });
  }

  Future takeImageFromCameraForMedicines() 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.uploadMedicinesCamera(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiMedicineImages = jsonDecode(res)['previewUrls'];
        /*reports=jsonDecode(res)['reportsPictureUpload'];
        reportsPictureId=jsonDecode(res)['reportsPictureUpload']['reportsPictureId'];*/
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    getAllMedicines();
    super.initState();
  }

  Widget _medicinesUI(){
    if(medicinesList.length!=0){
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: Text(
              medicinesList[currentIndex].medicine_name,
              style: TextStyle(fontSize: 24),
            ),
          ),
          GestureDetector(
            child: Icon(
              Icons.camera_alt_outlined,
              size: 100,
              color: primaryColor,
            ),
            onTap: () async {
              await takeImageFromCameraForMedicines();
            },
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              displayNextItem();
            },
            child: Text('Next Item'),
          ),
        ],
      );
    }
    else{
      return Center(
          child: Padding(
              padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
              child: isSereverIssue
                  ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image(
                    image: AssetImage('images/serverissue.png'),
                    //  height: MediaQuery.of(context).size.height * .10,
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Text(
                    'There is an issue at server please try after some time',
                    style: serverIssueTextStyle(),
                  ),
                ],
              )
                  : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  /*Image(
                  image: AssetImage('images/resourceblue.pngs'),
                  //  height: MediaQuery.of(context).size.height * .10,
                ),*/
                  Icon(
                    Icons.info,
                    color: primaryColor,
                    size: 40,
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Text(
                    'No Medicines available',
                    style: TextStyle(
                      color: primaryColor,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              )));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppSettings.appBar('Medicine'),
      body: Container(
        child: isLoading
            ? Center(
                child: CircularProgressIndicator(
                  color: primaryColor,
                  strokeWidth: 5.0,
                ),
              )
            : _medicinesUI(),
      ),
    );
  }
}
