import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:provider/provider.dart';
import 'package:searchfield/searchfield.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/components/widgets.dart';
import 'package:telnow_mobile_new/src/layouts/functions/request.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/pickup_asset.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/cache_manager.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';
// import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
import 'package:toggle_switch/toggle_switch.dart';

class MobReqCreatePage extends StatefulWidget {
  final Map<String, dynamic> user;
  final Map<String, dynamic> request;
  final bool fromSearch;
  const MobReqCreatePage({required this.user, required this.request, this.fromSearch = false, super.key});

  @override
  State<MobReqCreatePage> createState() => _MobReqCreatePageState();
}

getColorScheme(val){
  Color color;
  switch (val){
    case 0: color = Color(0xFF4FB66C); break;
    case 50: color = Color(0xFFFFA800); break;
    case 100: color = Color(0xFFC9223B); break;
    default: color = Color(0xFF4FB66C);
  }
  return color;
}

class _MobReqCreatePageState extends State<MobReqCreatePage> {
  final RequestFunction reqFunc = RequestFunction();
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();

  TextEditingController controllerDate = TextEditingController()..text = '';
  TextEditingController controllerDateString = TextEditingController()..text = '';
  TextEditingController controllerNote = TextEditingController()..text = '';
  TextEditingController controllerLocation = TextEditingController()..text = '';
  TextEditingController controllerUserId = TextEditingController()..text = '';
  TextEditingController controllerReferenceNumber = TextEditingController()..text = '';

  FocusNode focusNodeLocation = new FocusNode();
  double _currentSliderValue = 0;
  Color sliderColor = getColorScheme(0);
  Map<String, dynamic> asset = {};

  @override
  void initState() {
    Provider.of<CreateSerModule>(context, listen: false).reset();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if(widget.request['scanToRequest']) Provider.of<CreateSerModule>(context, listen: false).setLocationType(2);
      Provider.of<CreateSerModule>(context, listen: false).setDefaultLocation(widget.user['_isRelated'] ? sharedPreferencesManager.getString(SharedPreferencesManager.keyScoope) == 'INSIDE' ? widget.user['_2ndLocation'] : widget.user['location'] : widget.user['location']);
    });

    reqFunc.getSuggestionLocation(context);
    U.getOtherLabelList(context);

    switch (widget.request['requestPriority']){
      case 'RENDAH': _currentSliderValue = 0; break;
      case 'NORMAL': _currentSliderValue = 50; break;
      case 'TINGGI': _currentSliderValue = 100; break;
    }
    sliderColor = getColorScheme(_currentSliderValue);

    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final FocusNode inputIdFocusNode = FocusNode();
    var imageWidth = ((U.bodyWidth(context)-32)/5)-5;

    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: appBarTemplate(context: context, exc: false, title: widget.request[U.langColumn(context, 'subject')]),
      body: Column(
        children: [
          divider(),
          Expanded(
            child: Container(
              alignment: Alignment.topCenter,
              width: U.bodyWidth(context),
              child: SingleChildScrollView(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      margin: EdgeInsets.only(bottom: 21),
                      width: double.infinity, height: U.bodyWidth(context)/(kIsWeb?2.1:1.7),
                      decoration: widget.request['_mobileImage'] != null ? BoxDecoration(
                        color: Color(0xff292D32).withValues(alpha: 0.1),
                        borderRadius: BorderRadius.all(Radius.circular(12)),
                        image: DecorationImage(
                          image: CachedNetworkImageProvider(widget.request['_mobileImage']+'?bridge-cache=true', cacheManager: CacheManager(CacheMan.config(widget.request['_mobileImage']))),
                          fit: BoxFit.cover,
                        ),
                      ) : BoxDecoration(
                        color: Colors.black12,
                        borderRadius: BorderRadius.all(Radius.circular(12)),
                      ),
                      child: widget.request['_mobileImage'] == null ? Center(child: Text("noImage".tr(), style: TextStyle(fontStyle: FontStyle.italic, color: Colors.black38), textAlign: TextAlign.center,)) : Container(),
                    ),
                    Container(
                      padding: EdgeInsets.all(16),
                      margin: EdgeInsets.only(bottom: 21),
                      width: double.infinity,
                      decoration: BoxDecoration(
                          border: Border.all(color: textColor.withValues(alpha: 0.15)),
                          borderRadius: BorderRadius.all(Radius.circular(12))
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(widget.request[U.langColumn(context, '_requestGroupDescription')]??'', style: TextStyle(color: textColor, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                          dashed(),
                          Text(widget.request[U.langColumn(context, 'subjectDescription')], style: TextStyle(color: textColor, fontSize: 13, fontWeight: FontWeight.w300), maxLines: 3, overflow: TextOverflow.ellipsis)
                        ],
                      ),
                    ),

                    widget.request['autoResponse'] ? infoContainer('autoResponseText'.tr()) : Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('yourLocation'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                        // SizedBox(height: 6.0,),
                        !widget.request['scanToRequest'] ? GestureDetector(
                          child: Container(
                            margin: EdgeInsets.only(top: 8),
                            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
                            decoration: BoxDecoration(
                                color: Provider.of<CreateSerModule>(context).locationType()==1?primaryColor.withValues(alpha: 0.15):Colors.white,
                                border: Border.all(color: Provider.of<CreateSerModule>(context).locationType()==1?primaryColor:textColor.withValues(alpha: 0.15)),
                                borderRadius: BorderRadius.only(topLeft: Radius.circular(12), topRight: Radius.circular(12))
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                U.iconsax('location', color: textColor, size: 20),
                                SizedBox(width: 15),
                                Expanded(child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('defaultLocation'.tr(), style: TextStyle(color: textColor, fontSize: 12, fontWeight: FontWeight.w300)),
                                    SizedBox(height: 5),
                                    Text(Provider.of<CreateSerModule>(context).defaultLocation(), style: TextStyle(color: textColor), maxLines: 2, overflow: TextOverflow.ellipsis)
                                  ],
                                ))
                              ],
                            ),
                          ),
                          onTap: (){
                            if(!widget.request['scanToRequest']) Provider.of<CreateSerModule>(context, listen: false).setLocationType(1);
                          },
                        ) : Container(),
                        GestureDetector(
                          child: Container(
                            margin: EdgeInsets.only(bottom: 21, top: widget.request['scanToRequest'] ? 8 : 0),
                            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
                            decoration: BoxDecoration(
                                color: Provider.of<CreateSerModule>(context).locationType()==2?primaryColor.withValues(alpha: 0.15):Colors.white,
                                border: Border.all(color: Provider.of<CreateSerModule>(context).locationType()==2?primaryColor:textColor.withValues(alpha: 0.15)),
                                borderRadius: widget.request['scanToRequest'] ? BorderRadius.all(Radius.circular(12.0)) : BorderRadius.only(bottomLeft: Radius.circular(12), bottomRight: Radius.circular(12))
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                U.iconsax('location', color: Color(0xffD91B1B), size: 20),
                                SizedBox(width: 15),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(widget.request['scanToRequest'] ? "findQRcode".tr() : 'specifyAnotherLocation'.tr(), style: TextStyle(color: textColor, fontSize: 12, fontWeight: FontWeight.w300)),
                                      SizedBox(height: 5),

                                      GestureDetector(
                                        child: SizedBox(
                                          width: double.infinity,
                                          child: SearchField(
                                            focusNode: focusNodeLocation,
                                            suggestions: Provider.of<CreateSerModule>(context).suggestion().map((e) => SearchFieldListItem(e, child: Padding(
                                              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 13),
                                              child: Text(e, style: TextStyle(fontSize: 14, color: Colors.black)),
                                            ))).toList(),
                                            controller: controllerLocation,
                                            enabled: (!kIsWeb && widget.request['scanToRequest']) || Provider.of<CreateSerModule>(context).locationType() == 1 ? false : true,
                                            readOnly: (!kIsWeb && widget.request['scanToRequest']) || Provider.of<CreateSerModule>(context).locationType() == 1 ? true : false,
                                            searchInputDecoration: SearchInputDecoration(
                                                hintText: widget.request['scanToRequest'] && !kIsWeb ? 'pleaseScan'.tr() : 'placeholderLocation'.tr(),
                                                hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                                                filled: true,
                                                fillColor: backgroundColor,
                                                hoverColor: Colors.black.withValues(alpha: 0.1),
                                                contentPadding: EdgeInsets.all(13),
                                                border: InputBorder.none,
                                                disabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
                                                enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
                                                focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: primaryColor)),
                                                isDense: true
                                            ),
                                            maxSuggestionsInViewPort: 3,
                                            itemHeight: 40,
                                          ),
                                        ),
                                        onTap: ()async{
                                          Provider.of<CreateSerModule>(context, listen: false).setLocationType(2);
                                          if(!kIsWeb && widget.request['scanToRequest']){
                                            try {
                                              // String barcode = await FlutterBarcodeScanner.scanBarcode('#ff6666', 'Cancel', true, ScanMode.QR);
                                              // var decrypted = U.decodeBase64Url(barcode);
                                              // controllerLocation.text = decrypted.split('#')[1];
                                            } catch (e) {
                                              showError(context, 'messageInvalidCode'.tr());
                                            }
                                          }
                                        },
                                        onTapCancel: () => print(" "),
                                      ),
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                          onTap: (){
                            Provider.of<CreateSerModule>(context, listen: false).setLocationType(2);
                          },
                        ),

                        widget.user['roomAttendant'] ? Container(
                          margin: EdgeInsets.only(bottom: 32),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(U.otherLabelList()['main-${context.locale.toString()}']??'someone_else'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                              SizedBox(height: 12),
                              Row(
                                children: [
                                  Container(
                                    decoration: BoxDecoration(color: Provider.of<CreateSerModule>(context).others() == 0 ? disabledColor : primaryColor, borderRadius: BorderRadius.all(Radius.circular(20))),
                                    child: ToggleSwitch(
                                      cornerRadius: 20,
                                      minWidth: 20,
                                      minHeight: 20,
                                      borderWidth: 2,
                                      activeBgColors: [[Colors.white], [Colors.white]],
                                      inactiveBgColor: Provider.of<CreateSerModule>(context).others() == 0 ? disabledColor : primaryColor,
                                      initialLabelIndex: Provider.of<CreateSerModule>(context).others(),
                                      totalSwitches: 2,
                                      radiusStyle: true,
                                      onToggle: (index) {
                                        if(index == 1) {
                                          FocusScope.of(context).requestFocus(inputIdFocusNode);
                                        } else {
                                          FocusScope.of(context).unfocus();
                                        }
                                        Provider.of<CreateSerModule>(context, listen: false).setOthers(index);
                                      },
                                    ),
                                  ),
                                  SizedBox(width: 8),
                                  Expanded(child: Text(Provider.of<CreateSerModule>(context).others() == 0 ? 'reqForMySelf'.tr() : 'reqForOthers'.tr(), style: TextStyle(color: textColor, fontSize: 12), maxLines: 2, overflow: TextOverflow.ellipsis))
                                ],
                              ),
                              Provider.of<CreateSerModule>(context).others()==1?Container(
                                margin: EdgeInsets.only(top: 12),
                                width: double.infinity,
                                child: TextField(
                                  controller: controllerUserId,
                                  focusNode: inputIdFocusNode,
                                  style: const TextStyle(fontSize: 14, color: Colors.black),
                                  autofocus: Provider.of<CreateSerModule>(context).others() == 1 ? true : false,
                                  readOnly: false,
                                  decoration: InputDecoration(
                                      hintText: U.otherLabelList()['placeholder-${context.locale.toString()}']??'typeId'.tr(),
                                      hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                                      filled: true,
                                      fillColor: backgroundColor,
                                      hoverColor: Colors.black.withValues(alpha: 0.1),
                                      contentPadding: EdgeInsets.all(13),
                                      border: InputBorder.none,
                                      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
                                      focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: primaryColor)),
                                      isDense: true
                                  ),
                                ),
                              ):Container()
                            ],
                          ),
                        ):Container(),

                        widget.request['noteFormat'] == 'DATE' ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                          Text("askScheduleTime".tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                          SizedBox(height: 8,),
                          TextField(
                            controller: controllerDate,
                            style: TextStyle(fontSize: 14, color: Colors.black),
                            readOnly: true,
                            decoration: InputDecoration(
                                hintText: 'selectDate'.tr(),
                                hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                                filled: true,
                                fillColor: backgroundColor,
                                hoverColor: Colors.black.withValues(alpha: 0.1),
                                contentPadding: EdgeInsets.all(13),
                                prefixIcon: Padding(padding: EdgeInsets.only(left: 13, right: 13), child: U.iconsax('calendar-edit', color: textColor, size: 24)),
                                border: InputBorder.none,
                                enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
                                focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: primaryColor)),
                                isDense: true
                            ),
                            onTap: () {
                              DatePicker.showDateTimePicker(context, showTitleActions: true,
                                  minTime: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, DateTime.now().hour, DateTime.now().minute),
                                  onConfirm: (date) {
                                    try {
                                      setState(() {
                                        controllerDate.text = DateFormat('dd MMM yyyy HH:mm:ss', 'id').format(date);
                                        controllerDateString.text = DateFormat('ddMMyyyy HHmm', 'id').format(date);
                                      });
                                    } catch (e) {
                                      print(e.toString());
                                    }
                                  }, currentTime: DateTime.now(), locale: LocaleType.id
                              );
                            },
                          ),
                          SizedBox(height: 32,)
                        ],) : Container(),

                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('addImage'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                            SizedBox(height: 8),
                            Provider.of<CreateSerModule>(context).images().isNotEmpty ? Row(
                              children: [
                                Row(
                                  children: List.generate(Provider.of<CreateSerModule>(context).images().length, (i){
                                    return GestureDetector(
                                        child: Container(
                                          width: imageWidth, height: imageWidth, alignment: Alignment.topRight,
                                          margin: EdgeInsets.only(right: i == 4 ? 0 : 6),
                                          decoration: BoxDecoration(
                                              color: Colors.black12, borderRadius: BorderRadius.all(Radius.circular(5)), border: Border.all(color: Colors.black26, width: 0.5),
                                              image: DecorationImage(image: MemoryImage(Provider.of<CreateSerModule>(context).images()[i]), fit: BoxFit.cover)
                                          ),
                                          child: Transform.translate(
                                            offset: Offset(3, -3),
                                            child: GestureDetector(
                                              child: Container(
                                                padding: EdgeInsets.all(3),
                                                decoration: BoxDecoration(color: Colors.black54, border: Border.all(color: Colors.white, width: 2), borderRadius: BorderRadius.all(Radius.circular(50))),
                                                child: Icon(Icons.close_rounded, color: Colors.white, size: 18),
                                              ),
                                              onTap: ()=>Provider.of<CreateSerModule>(context, listen: false).removeImages(i),
                                            ),
                                          ),
                                        ),
                                        onTap: ()=>navigateTo(context, PhotoPreviewGallery(title: 'image'.tr(), imageList: Provider.of<CreateSerModule>(context, listen: false).images(), startIndex: i, isUrl: false))
                                    );
                                  }),
                                ),
                                Provider.of<CreateSerModule>(context).images().length < 5 ? GestureDetector(
                                  child: Container(
                                    width: imageWidth, height: imageWidth, alignment: Alignment.center,
                                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(5)), border: Border.all(color: Colors.black26, width: 2)),
                                    child:  Provider.of<CreateSerModule>(context).setLoadingEffect() ? SizedBox(
                                      height: 30,
                                      child: LoadingIndicator(
                                        indicatorType: Indicator.ballPulseRise,
                                        colors: U.defaultRainbowColors(),
                                        strokeWidth: 1,
                                        backgroundColor: Colors.black.withValues(alpha: 0),
                                        pathBackgroundColor: Colors.black,
                                      ),
                                    ) : Icon(Icons.add_rounded, color: Colors.black26, size: 40),
                                  ),
                                  onTap: ()=>pickupImageNew(),
                                ) : Container(),
                              ],
                            ) : GestureDetector(
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 8, vertical: 12),
                                decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(10)), border: Border.all(color: Color(0xFF078C84)), color: Color(0xFFFFFFFF).withValues(alpha: 0.2)),
                                child: Row(
                                  children: [
                                    U.iconsax('image', color: primaryColor, size: 30),
                                    SizedBox(width: 8,),
                                    Expanded(child: Text('addImageMsg'.tr(), style: TextStyle(color: textColor, fontSize: 12, fontWeight: FontWeight.w300), maxLines: 2, overflow: TextOverflow.ellipsis)),
                                  ],
                                ),
                              ),
                              onTap: ()=>pickupImageNew(),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: 32),
                                Text('changePriority'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                                SizedBox(height: 12),
                                Container(
                                  height: 32,
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(25.0),
                                    border: Border.all(
                                      width: 3.0,
                                      color: Colors.transparent,
                                    ),
                                    gradient: LinearGradient(
                                      colors: [
                                        Color(0xFF4FB66C).withValues(alpha: 1),
                                        Color(0xFFFFA800).withValues(alpha: 1),
                                        Color(0xFFC9223B).withValues(alpha: 1),
                                      ],
                                      begin: Alignment.topLeft,
                                      end: Alignment.bottomRight,
                                    ),
                                  ),
                                  child: Container(
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(25.0),
                                    ),
                                    child: SliderTheme(
                                      data: SliderThemeData(
                                        inactiveTrackColor: Colors.white,
                                      ),
                                      child: Slider(
                                        activeColor: sliderColor,
                                        value: _currentSliderValue,
                                        max:100,
                                        divisions: 2,
                                        onChanged: (double value) {
                                          setState(() {
                                            _currentSliderValue = value;
                                            sliderColor = getColorScheme(value);
                                          });
                                        },
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 4,),
                                Center(
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text('priorityLow'.tr(), style: TextStyle(fontSize: 12),),
                                        Text('priorityNormal'.tr(), style: TextStyle(fontSize: 12)),
                                        Text('priorityHigh'.tr(), style: TextStyle(fontSize: 12)),
                                      ],
                                    )
                                )
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: 32),
                                Text('referenceNumber'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                                SizedBox(height: 8),
                                SizedBox(
                                  width: double.infinity,
                                  child: TextField(
                                    controller: controllerReferenceNumber,
                                    style: TextStyle(fontSize: 14, color: Colors.black),
                                    decoration: InputDecoration(
                                        hintText: 'enterTicketNumber'.tr(),
                                        hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                                        filled: true,
                                        fillColor: backgroundColor,
                                        hoverColor: Colors.black.withValues(alpha: 0.1),
                                        contentPadding: EdgeInsets.all(13),
                                        prefixIcon: Padding(padding: EdgeInsets.only(left: 13, right: 13), child: U.iconsax('ticket', color: textColor, size: 24)),
                                        border: InputBorder.none,
                                        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
                                        focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: primaryColor)),
                                        isDense: true
                                    ),
                                  ),
                                )
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: 32),
                                Text(asset.isEmpty ? 'addAsset'.tr() : 'asset'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                                SizedBox(height: 8),
                                asset.isEmpty ? GestureDetector(
                                  onTap: () async {
                                    final res = await Navigator.push(
                                      context, MaterialPageRoute(
                                        builder: (_) => BlocProvider(
                                          create: (_) => AssetCubit()..getData(),
                                          child: PickupAsset(web: false),
                                        ),
                                      ),
                                    );

                                    if(res != null) {
                                      setState(() {
                                        for (var item in res) {
                                          asset['_mobileImage'] = item['_mobileImage']+'?bridge-cache=true';
                                          asset['name'] = item['name'];
                                          asset['code'] = item['code'];
                                          asset['description'] = item['description'];
                                        }
                                      });
                                    }
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(horizontal: 13, vertical: 12),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(12),
                                      border: Border.all(color: Color(0xff262626).withValues(alpha: 0.5))
                                    ),
                                    child: Row(
                                      spacing: 12,
                                      children: [
                                        Icon(Icons.widgets_outlined,),
                                        Text("selectAsset".tr(), style: TextStyle(color: Color(0xff262626).withValues(alpha: 0.5)),),
                                      ],
                                    ),
                                  ),
                                ) : Container(
                                  decoration: BoxDecoration(
                                    border: Border.all(color: Color(0xff262626).withValues(alpha: 0.5)),
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: Padding(
                                    padding: EdgeInsets.symmetric(vertical: 0),
                                    child: Row(
                                      spacing: 12,
                                      children: [
                                        ClipRRect(
                                          borderRadius: BorderRadius.circular(12.0),
                                          child: Image.network(
                                            asset['_mobileImage'],
                                            width: 80,
                                            height: 64,
                                            fit: BoxFit.cover,
                                            errorBuilder: (context, error, stackTrace) =>
                                            const Icon(Icons.broken_image, size: 60, color: Colors.grey),
                                            loadingBuilder: (context, child, loadingProgress) {
                                              if (loadingProgress == null) return child;
                                              return const SizedBox(
                                                width: 80,
                                                height: 64,
                                                child: Center(child: CupertinoActivityIndicator()),
                                              );
                                            },
                                          ),
                                        ),
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            spacing: 4,
                                            children: [
                                              Text(asset['name'],
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  color: textColor,
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w600,
                                                ),),
                                              Text(asset['description'],
                                                maxLines: 2,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(color: textColor, fontSize: 14)),
                                            ],
                                          ),
                                        ),
                                        GestureDetector(
                                          onTap: () => setState(() {
                                            asset = {};
                                          }),
                                          child: Padding(
                                            padding: const EdgeInsets.all(12.0),
                                            child: Icon(Icons.delete_rounded, size: 24, color: Colors.red.withValues(alpha: 0.85),),
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ],
                        ),
                      ],
                    ),

                    widget.request['canNotCancel'] ? Padding(
                      padding: EdgeInsets.only(top: 21),
                      child: infoContainer('canNotCancel1'.tr()),
                    ) : Container()
                  ],
                ),
              ),
            ),
          ),
          divider(color: primaryColor, thickness: 2.0, opacity: 1.0),
          Container(
            alignment: Alignment.bottomCenter,
            width: U.bodyWidth(context), color: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
            child: SafeArea(
              child: Column(
                children: [
                  widget.request['autoResponse'] ? Container() : Container(
                    margin: EdgeInsets.only(bottom: 10),
                    width: double.infinity,
                    child: TextField(
                      controller: controllerNote,
                      style: TextStyle(fontSize: 14, color: Colors.black),
                      minLines: 1,
                      maxLines: 3,
                      keyboardType: widget.request['noteFormat'] == 'NUMBER' ? TextInputType.number : null,
                      decoration: InputDecoration(
                          hintText: 'placeholderNote'.tr(),
                          hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                          filled: true,
                          fillColor: backgroundColor,
                          hoverColor: Colors.black.withValues(alpha: 0.1),
                          contentPadding: EdgeInsets.all(13),
                          prefixIcon: Padding(padding: EdgeInsets.only(left: 13, right: 13), child: U.iconsax('edit-2', color: textColor, size: 24)),
                          border: InputBorder.none,
                          enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
                          focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: primaryColor)),
                          isDense: true
                      ),
                    ),
                  ),
                  buttonTemplate(text: 'buttonSendRequest'.tr(), action: () async{
                    if ((Provider.of<CreateSerModule>(context, listen: false).locationType() == 2 && controllerLocation.text.trim().isNotEmpty) || (Provider.of<CreateSerModule>(context, listen: false).locationType() == 1 && Provider.of<CreateSerModule>(context, listen: false).defaultLocation() != '')) {
                      if (controllerNote.text.length <= 128) {
                        if (widget.user['roomAttendant'] && Provider.of<CreateSerModule>(context, listen: false).others() == 1){
                          if (controllerUserId.text.trim().isNotEmpty){
                            if (controllerDateString.text.trim().isEmpty && widget.request['noteFormat'] == 'DATE'){
                              showError(context, 'dateRequired'.tr());
                            } else {
                              reqFunc.sendRequestToOthers(context, widget, controllerUserId, controllerNote, controllerReferenceNumber, controllerLocation, controllerDateString, _currentSliderValue);
                            }
                          } else {
                            showError(context, 'idRequired'.tr());
                          }
                        } else if (controllerDateString.text.trim().isNotEmpty && widget.request['noteFormat'] == 'DATE'){
                          dialogSendLater();
                        } else {
                          reqFunc.sendRequest(context, widget, controllerNote, controllerReferenceNumber, controllerLocation, controllerDateString, _currentSliderValue, asset['code']);
                        }
                      } else {
                        showError(context, 'lengthMax'.tr());
                      }
                    } else {
                      showError(context, 'locRequired'.tr()+(!kIsWeb && widget.request['scanToRequest']?' ${'pleaseScan'.tr()}.':''));
                    }
                  })
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  dialogSendLater(){
    showDialog(
      context: context,
      builder: (contexts) => AlertDialog(
        title: Text('sendingOpt'.tr(), style: TextStyle(color: textColor, fontSize: 16, fontWeight: FontWeight.w500)),
        titlePadding: EdgeInsets.all(20),
        contentPadding: EdgeInsets.fromLTRB(20, 4, 20, 28),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('sendingOptMsg'.tr(), style: TextStyle(fontSize: 14, color: textColor)),
            SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 20),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(12)),
                          gradient: LinearGradient(
                              begin: Alignment.topLeft, end: Alignment.bottomRight,
                              colors: [
                                Color(0xff131480).withValues(alpha: 0.56), Color(0xff131480).withValues(alpha: 0.90), Color(0xff131480).withValues(alpha: 0.75)
                              ]
                          )
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          U.iconsax('timer-start', color: Colors.white, size: 30),
                          SizedBox(height: 9),
                          Text('scheduled'.tr(), style: TextStyle(color: Colors.white, fontSize: 14))
                        ],
                      ),
                    ),
                    onTap: (){
                      navigateBack(contexts);
                      Provider.of<CreateSerModule>(context, listen: false).setSendLater(true);
                      reqFunc.sendRequest(context, widget, controllerNote, controllerReferenceNumber, controllerLocation, controllerDateString, _currentSliderValue, asset['code']);
                    },
                  ),
                ),
                SizedBox(width: 16),
                Expanded(
                  child: GestureDetector(
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 20),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(12)),
                          gradient: LinearGradient(
                              begin: Alignment.topLeft, end: Alignment.bottomRight,
                              colors: [
                                Color(0xff078C84).withValues(alpha: 0.56), Color(0xff078C84).withValues(alpha: 0.90), Color(0xff078C84).withValues(alpha: 0.75)
                              ]
                          )
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          U.iconsax('star-1', color: Colors.white, size: 30),
                          SizedBox(height: 9),
                          Text('sendNow'.tr(), style: TextStyle(color: Colors.white, fontSize: 14))
                        ],
                      ),
                    ),
                    onTap: (){
                      navigateBack(contexts);
                      reqFunc.sendRequest(context, widget, controllerNote, controllerReferenceNumber, controllerLocation, controllerDateString, _currentSliderValue, asset['code']);
                    },
                  ),
                ),
              ],
            ),
            SizedBox(height: 12),
            divider(),
            SizedBox(height: 12),
            Container(
              padding: EdgeInsets.all(3),
              decoration: BoxDecoration(
                  color: Color(0xffCCA600).withValues(alpha: 0.2),
                  borderRadius: BorderRadius.all(Radius.circular(3))
              ),
              child: Text('scheduledMsg'.tr(), style: TextStyle(color: textColor, fontSize: 12, fontWeight: FontWeight.w300)),
            )
          ],
        ),
      ),
    );
  }

  pickupImageNew() async{
    if(Provider.of<CreateSerModule>(context, listen: false).images().length < 5){
      if (kIsWeb) {
        await reqFunc.getImageNew(context, ImageSource.gallery).then((img){
          img != null ? Provider.of<CreateSerModule>(context, listen: false).setImages(img) : (){};
        });
      } else{
        showModalBottomSheet<void>(
            context: context,
            backgroundColor: Colors.white,
            builder: (BuildContext context) {
              return SafeArea(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(top: 15, bottom: 15),
                      child: Center(
                        child: Text('selectPicture'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                      ),
                    ),
                    divider(),
                    ListTile(
                      leading: Icon(Icons.image),
                      title: Text('fromGallery'.tr(), style: TextStyle(color: textColor)),
                      onTap: () async{
                        var image = await reqFunc.getImageNew(context, ImageSource.gallery);
                        Provider.of<CreateSerModule>(context, listen: false).setImages(image);
                        Navigator.of(context).pop();
                      },
                    ),
                    ListTile(
                      leading: Icon(Icons.camera),
                      title: Text('fromCamera'.tr(), style: TextStyle(color: textColor)),
                      onTap: () async{
                        var image = await reqFunc.getImageNew(context, ImageSource.camera);
                        Provider.of<CreateSerModule>(context, listen: false).setImages(image);
                        Navigator.of(context).pop();
                      },
                    )
                  ],
                ),
              );
            }
        );
      }
    }
  }
}
