import 'dart:async';
import 'package:absenkuv3/UI/Template/DatePicker/Bloc/TemplateTimePickerBloc.dart';
import 'package:absenkuv3/UI/Template/DatePicker/UI/templateTimePicker.dart';
import 'package:intl/intl.dart' as intl;
import 'package:absenkuv3/Bloc/CustomFunction.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownJenisAktivitasBloc.dart';
import 'package:absenkuv3/Bloc/MapsBloc.dart';
import 'package:absenkuv3/Bloc/SalesActivity/DataAktivitasSalesBloc.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Dropdown/DropdownJenisAktivitas.dart';
import 'package:absenkuv3/UI/Template/DatePicker/Bloc/DatePickerTglKawinBloc.dart';
import 'package:absenkuv3/UI/Template/DatePicker/UI/templateDatePickerTglKawin.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Bloc/MultiImagePicker3Bloc.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Model/MultiImagePickerModel.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/UI/templateMultiImagePicker3.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:absenkuv3/UI/Template/templateIconInformation.dart';
import 'package:absenkuv3/UI/Template/templateTextFormAkun.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:absenkuv3/Repository/Model/SalesActivity/mJenisAktivitasSales.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';


class HalamanAddAktivitasSales extends StatefulWidget {
  var data; // 0 = id_pelanggan; 1 = nama pelanggan; 2 = id pipeline main; 3 = Data Kanban
  HalamanAddAktivitasSales(this.data);

  @override
  State<HalamanAddAktivitasSales> createState() => _HalamanAddAktivitasSalesState();
}

class _HalamanAddAktivitasSalesState extends State<HalamanAddAktivitasSales> with WidgetsBindingObserver {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  TextEditingController pelanggan = TextEditingController();
  TextEditingController keterangan = TextEditingController();
  String tanggal = '00-00-0000';
  TimeOfDay? jam;
  TextEditingController jamRaw = new TextEditingController();
  TextEditingController tanggalRaw = new TextEditingController();
  Data jenisAktivitas = Data();
  List<MultiImagePickerModel>? listImage;
  Position? _position;
  final dateFormat = new intl.DateFormat('dd-MM-yyyy');
  intl.DateFormat dateFormatRaw = intl.DateFormat('d MMM yyyy', 'id_ID');

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    pelanggan.text = widget.data[1];
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  Future<void> animateCamera(Completer<GoogleMapController> _controller, Position currentLocation) async {
    final GoogleMapController controller = await _controller.future;
    CameraPosition _current = CameraPosition(
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 17.151926040649414);
    controller.animateCamera(CameraUpdate.newCameraPosition(_current));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
          centerTitle: true,
          flexibleSpace: Image(
            image: AssetImage(ValueImage.headerBiruDashboard),
            fit: BoxFit.cover,
          ),
          backgroundColor: Colors.transparent,
          title: Text(
            'Tambah Aktivitas',
            style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
          )
      ),
      body: Container(
        margin: EdgeInsets.only(top: 17),
        child: SingleChildScrollView(
          child: Column(
            children: [
              TemplateTextFormAkun(
                adaValidasi: false,
                controller: pelanggan,
                color: Colors.black,
                marginHorizontal: 27,
                fontSize: 13,
                titleText: '',
                // suffixIcon: Icon(Icons.arrow_drop_down_outlined),
                radius: CustomStyle.formRadius,
                enabled: false,
                flagColorBackground: true,
                onChange: (val){

                },
              ),
              BlocListener<DropdownJenisAktivitasBloc, DropdownJenisAktivitasState>(
                listener: (BuildContext context, DropdownJenisAktivitasState state) {
                  if (state is DropdownJenisAktivitasSuccessState && state.selectedValue != null) {
                    jenisAktivitas = state.selectedValue!;
                    BlocProvider.of<MapsBloc>(context).add(GetMapsEvent(context));
                  }
                },
                child: DropdownJenisAktivitas(
                  'Jenis Aktivitas',
                  initialData: jenisAktivitas.nama==null?null:jenisAktivitas.nama,
                  color: Colors.grey[600],
                  marginHorizontal: 27,
                ),
              ),
              BlocBuilder<DropdownJenisAktivitasBloc, DropdownJenisAktivitasState>(
                builder: (BuildContext context, DropdownJenisAktivitasState stateJenisAktivitas) {
                  bool enableClicked = true;
                  if(stateJenisAktivitas is DropdownJenisAktivitasSuccessState && stateJenisAktivitas.selectedValue != null){
                    if(stateJenisAktivitas.selectedValue!.flagLokasi == '1'){
                      tanggal = dateFormat.format(DateTime.now());
                      tanggalRaw.text = dateFormatRaw.format(DateTime.now());
                      jam = TimeOfDay.now();
                      jamRaw.text = "${jam!.hour}:${jam!.minute}";
                      enableClicked = false;
                    }
                  }

                  return Row(
                    children: [
                      Expanded(
                        child: BlocListener<DatePickerTglKawinBloc, DateTime>(
                          listener: (BuildContext context, DateTime date) {
                            tanggal = dateFormat.format(date);//dateFormat.format(date);
                            tanggalRaw.text = dateFormatRaw.format(date);
                          },
                          child: Container(
                            margin: EdgeInsets.only(left: 27),
                            child: TemplateDatePickerTglKawin(
                              'Tanggal',
                              textEditingController: tanggalRaw,
                              // marginHorizontal: 27,
                              nextDate: false,
                              validasi: true,
                              enableClick: enableClicked,
                              initialData: tanggal == '00-00-0000'
                                  ? null
                                  : DateTime(int.parse(tanggal.split('-')[2]),int.parse(tanggal.split('-')[1]),int.parse(tanggal.split('-')[0])),),
                          ),
                        ),
                      ),
                      SizedBox(width: 17),
                      Expanded(
                        child: BlocListener<TemplateTimePickerBloc, TimeOfDay>(
                          listener: (BuildContext context, TimeOfDay date) {
                            if(date != null) {
                              jam = date;
                              jamRaw.text = "${jam!.hour}:${jam!.minute}";
                            }
                          },
                          child: Container(
                            margin: EdgeInsets.only(right: 19),
                            child: TemplateTimePicker(
                              "Jam",
                              validasi: true,
                              initialData: jam,
                              enableClicked: enableClicked,
                              textEditingController: jamRaw,
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
              TemplateTextFormAkun(
                adaValidasi: true,
                controller: keterangan,
                color: Colors.black,
                marginHorizontal: 27,
                fontSize: 13,
                titleText: 'Keterangan',
                maxLine: 4,
                radius: CustomStyle.formRadius,
                flagColorBackground: true,
                onChange: (val){

                },
              ),
              BlocBuilder<DropdownJenisAktivitasBloc, DropdownJenisAktivitasState>(
                builder: (BuildContext context, DropdownJenisAktivitasState state) {
                  if(state is DropdownJenisAktivitasSuccessState && state.selectedValue != null){
                    return Column(
                      children: [
                        state.selectedValue!.flagLokasi! == '1'
                          ? BlocBuilder<MapsBloc, MapsState>(
                              builder: (BuildContext context, MapsState maps) {
                                Set<Marker> _markers = {};
                                Completer<GoogleMapController> _controller = Completer();
                                CameraPosition _initPosition = CameraPosition(target: LatLng(-6.9932, 110.4203));
                                if(maps is MapsSuccess){
                                  animateCamera(_controller, maps.position!);
                                  _markers = maps.markers;
                                  _position = maps.position;
                                  return Column(
                                    children: [
                                      SizedBox(height: 13),
                                      Container(
                                        decoration: BoxDecoration(
                                            border: Border.all(color: Colors.grey.shade300),
                                            borderRadius: BorderRadius.circular(13)
                                        ),
                                        margin: EdgeInsets.symmetric(horizontal: 27),
                                        child: Column(
                                          children: [
                                            Container(
                                              height: 200,
                                              width: MediaQuery.of(context).size.width-56,
                                              child: ClipRRect(
                                                borderRadius: BorderRadius.only(
                                                  topLeft: Radius.circular(13),
                                                  topRight: Radius.circular(13),
                                                ),
                                                child: GoogleMap(
                                                  myLocationButtonEnabled: false,
                                                  zoomControlsEnabled: false,
                                                  initialCameraPosition: _initPosition,
                                                  mapType: MapType.normal,
                                                  onMapCreated: (GoogleMapController controllers) {
                                                    _controller.complete(controllers);
                                                  },
                                                  markers: _markers,
                                                ),
                                              ),
                                            ),
                                            Container(
                                              child: Column(
                                                mainAxisAlignment: MainAxisAlignment.end,
                                                children: [
                                                  Container(
                                                    width: double.infinity,
                                                    decoration: BoxDecoration(
                                                        boxShadow: [
                                                          BoxShadow(
                                                            color: Colors.grey.withOpacity(0.2),
                                                            spreadRadius: 1.6,
                                                            blurRadius: 4,
                                                            offset: Offset(0, 1), // changes position of shadow
                                                          ),
                                                        ],
                                                        color: Colors.white,
                                                        borderRadius: new BorderRadius.only(
                                                            bottomRight: Radius.circular(13),
                                                            bottomLeft: Radius.circular(13)
                                                        )),
                                                    child: Padding(
                                                      padding: const EdgeInsets.symmetric(
                                                          horizontal: 0, vertical: 8),
                                                      child: Column(
                                                        children: [
                                                          IconInformation(
                                                              icon: ValueImage.iconLokasi,
                                                              title: "Lokasi",
                                                              subtitle: "${maps.position!.latitude}, ${maps.position!.longitude}",
                                                              sizeIcon: 33,
                                                              contentColor:
                                                              Colors.redAccent),
                                                          Divider(),
                                                          Stack(
                                                            children: [
                                                              IconInformation(
                                                                icon: ValueImage.iconRadius,
                                                                title: "Akurasi",
                                                                subtitle: '${maps.position!.accuracy.round().toString()} Meter',
                                                                sizeIcon: 29,
                                                              ),
                                                              GestureDetector(
                                                                onTap: (){
                                                                  BlocProvider.of<MapsBloc>(context).add(GetMapsEvent(context));
                                                                },
                                                                child: Container(
                                                                  margin: EdgeInsets.only(top: 7, right: 17),
                                                                  child: Align(
                                                                    alignment: Alignment.centerRight,
                                                                    child: ConstrainedBox(
                                                                      constraints: BoxConstraints(
                                                                        maxWidth: 100
                                                                      ),
                                                                      child: Container(
                                                                        decoration: BoxDecoration(
                                                                            borderRadius: BorderRadius.circular(13),
                                                                            border: Border.all(color: CustomStyle.color1),
                                                                          color: CustomStyle.color1
                                                                        ),
                                                                        child: Row(
                                                                          mainAxisAlignment: MainAxisAlignment.center,
                                                                          crossAxisAlignment: CrossAxisAlignment.center,
                                                                          children: [
                                                                            Icon(Icons.refresh, color: CustomStyle.backgroundDashboardColor),
                                                                            SizedBox(width: 3),
                                                                            Text('Refresh', style: TextStyle(color: CustomStyle.backgroundDashboardColor),)
                                                                          ],
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  ),
                                                                ),
                                                              )
                                                            ],
                                                          )
                                                        ],
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      )
                                    ],
                                  );
                                } else
                                  return Container(
                                    decoration: BoxDecoration(
                                        border: Border.all(color: Colors.grey.shade300),
                                        borderRadius: BorderRadius.circular(13)
                                    ),
                                    margin: EdgeInsets.symmetric(horizontal: 27),
                                    child: Column(
                                      children: [
                                        Container(
                                          height: 213,
                                          width: MediaQuery.of(context).size.width-56,
                                          child: Center(
                                            child: CircularProgressIndicator(strokeWidth: 8),
                                          ),
                                        ),
                                        Container(
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.end,
                                            children: [
                                              Container(
                                                width: double.infinity,
                                                decoration: BoxDecoration(
                                                    boxShadow: [
                                                      BoxShadow(
                                                        color: Colors.grey.withOpacity(0.2),
                                                        spreadRadius: 1.6,
                                                        blurRadius: 4,
                                                        offset: Offset(0, 1), // changes position of shadow
                                                      ),
                                                    ],
                                                    color: Colors.white,
                                                    borderRadius: new BorderRadius.only(
                                                        bottomRight: Radius.circular(13),
                                                        bottomLeft: Radius.circular(13)
                                                    )),
                                                child: Padding(
                                                  padding: const EdgeInsets.symmetric(
                                                      horizontal: 0, vertical: 8),
                                                  child: Column(
                                                    children: [
                                                      IconInformation(
                                                          icon: ValueImage.iconLokasi,
                                                          title: "Lokasi",
                                                          subtitle: "",
                                                          sizeIcon: 33,
                                                          contentColor:
                                                          Colors.redAccent),
                                                      Divider(),
                                                      Stack(
                                                        children: [
                                                          IconInformation(
                                                            icon: ValueImage.iconRadius,
                                                            title: "Akurasi",
                                                            subtitle: "",
                                                            sizeIcon: 29,
                                                          ),
                                                        ],
                                                      )
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  );


                              }
                            )

                        : Container(),
                        state.selectedValue!.flagUploadFoto! == '1'
                          ? Column(
                              children: [
                                SizedBox(height: 27),
                                Container(
                                  margin: EdgeInsets.symmetric(horizontal: 27),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Padding(
                                        padding: const EdgeInsets.only(bottom: 5),
                                        child: Text(
                                          'Upload Foto',
                                          style: TextStyle(
                                              color: Colors.grey[600],
                                              fontWeight: FontWeight.bold,
                                              fontSize: 14),
                                        ),
                                      ),
                                      BlocListener<MultiImagePicker3Bloc, ImagePickerState>(
                                        listener: (BuildContext context,ImagePickerState state){
                                          if (state is gettImageSuccessState) {
                                            listImage = state.listImage;
                                          }
                                        },
                                        child: TemplateImagePicker3(totalUpload: 1, title: "Foto Aktivitas", fromGaleri: false),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ) : Container()
                      ],
                    );
                  }else{
                    return Container();
                  }
                }
              ),

              Container(
                margin: EdgeInsets.only(left: 27, right: 27, top: 27, bottom: 17),
                child: TemplateButton(
                  label: "SUBMIT",
                  textAlignCenter: true,
                  enabled: true,
                  color: CustomStyle.color1,
                  expandText: true,
                  heightButton: 45,
                  fontSize: 14,
                  bold: true,
                  onClick: (){
                    if(jenisAktivitas.nama == null){
                      showSnackBarDelayed(scaffoldKey, "Jenis Aktivitas belum dipilih", context, backgroundColor: Colors.red, textColor: Colors.white);
                    }else if(tanggal == '00-00-0000'){
                      showSnackBarDelayed(scaffoldKey, "Tanggal belum dipilih", context, backgroundColor: Colors.red, textColor: Colors.white);
                    }else if(jam == null){
                      showSnackBarDelayed(scaffoldKey, "Jam belum dipilih", context, backgroundColor: Colors.red, textColor: Colors.white);
                    }
                    else if(keterangan.text.trim().isEmpty){
                      showSnackBarDelayed(scaffoldKey, "Keterangan belum diisi", context, backgroundColor: Colors.red, textColor: Colors.white);
                    }else if(jenisAktivitas.flagLokasi=='1' && _position == null){
                      showSnackBarDelayed(scaffoldKey, "Lokasi belum terdeteksi, silahkan refresh map terlebih dahulu", context, backgroundColor: Colors.red, textColor: Colors.white);
                    }else if(jenisAktivitas.flagUploadFoto=='1' && (listImage==null||listImage!.length==0)){
                      showSnackBarDelayed(scaffoldKey, "Wajib melampirkan foto", context, backgroundColor: Colors.red, textColor: Colors.white);
                    }else{
                      BlocProvider.of<DataAktivitasSalesBloc>(context).add(
                          addDataAktivitasSalesEvent(
                              scaffoldKey,
                              context,
                              widget.data[0],
                              widget.data[2],
                              jenisAktivitas,
                              keterangan.text,
                              jenisAktivitas.flagLokasi=='0'?"":_position!.latitude.toString(),
                              jenisAktivitas.flagLokasi=='0'?"":_position!.longitude.toString(),
                              listImage==null?null:listImage!.length==0?null:listImage![0].base64,
                              '${tanggal.split('-')[2]}-${tanggal.split('-')[1]}-${tanggal.split('-')[0]}',
                              "${jam!.hour}:${jam!.minute}",
                            widget.data[3],
                            widget.data[4]
                          ));
                    }
                  },
                ),
              )



            ],
          ),
        ),
      ),
    );
  }


}
