// ignore_for_file: must_be_immutable, no_leading_underscores_for_local_identifiers, use_build_context_synchronously

import 'dart:convert';
import 'dart:developer' as logDev;
import 'package:cached_memory_image/cached_memory_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:general_package/coloredcontainer/coloredcontainer.dart';
import 'package:general_package/constants/constants.dart';
import 'package:general_package/dynamic_form/src/model/dynamic_form_model.dart';
import 'package:general_package/responsive/responsive.dart';
import 'package:general_package/themes/themes.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';

class DynamicFormImageUpload extends StatefulWidget {
  DynamicFormImageUpload({
    super.key,
    required this.name,
    this.title,
    this.placeHolder,
    this.initialValue,
    this.padding,
  });

  String name;
  String? title;
  String? placeHolder;
  String? initialValue;
  EdgeInsetsGeometry? padding;

  @override
  State<DynamicFormImageUpload> createState() => _DynamicFormImageUploadState();
}

class _DynamicFormImageUploadState extends State<DynamicFormImageUpload> {
  DateTime? selectedDate;
  static imagePickerFromGallery(BuildContext context,FormFieldState fieldState) async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      Navigator.of(context).pop();
      var imageBytes = await image.readAsBytes();
      fieldState.didChange(base64Encode(imageBytes));
      // logDev.log(fieldState.value);
    } else {
      Fluttertoast.showToast(
          msg: "Error",
          toastLength: Toast.LENGTH_LONG,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          webPosition: "center",
          webBgColor: "#FF0000",
          fontSize: 16.0);
    }
  }

  static imagePickerFromCamera(BuildContext context,FormFieldState fieldState) async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.camera);
    if (image != null) {
      Navigator.of(context).pop();
      var imageBytes = await image.readAsBytes();
      fieldState.didChange(base64Encode(imageBytes));
    } else {
      Fluttertoast.showToast(
          msg: "Error",
          toastLength: Toast.LENGTH_LONG,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          webPosition: "center",
          webBgColor: "#FF0000",
          fontSize: 16.0);
    }
  }

  static showModalBottomSheetFormImageUpload(BuildContext context,FormFieldState field) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          width: double.infinity,
          color: AppTheme.lightWhiteColor,
          child: Column(mainAxisSize: MainAxisSize.min, children: [
            GestureDetector(
              onTap: () => imagePickerFromCamera(context, field),
              child: Container(
                padding: GeneralConstants.instance.margin10,
                child: Row(
                  children: [
                    const Icon(Icons.camera),
                    Container(
                        padding: GeneralConstants.instance.margin10,
                        child: const Text("Camera"))
                  ],
                ),
              ),
            ),
            GestureDetector(
              onTap: () => imagePickerFromGallery(context, field),
              child: Container(
                padding: GeneralConstants.instance.margin10,
                child: Row(
                  children: [
                    const Icon(Icons.image),
                    Container(
                        padding: GeneralConstants.instance.margin10,
                        child: const Text("Gallery"))
                  ],
                ),
              ),
            )
          ]),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return FormBuilderField<String?>(
        name: widget.name,
        initialValue: widget.initialValue,
        builder: (FormFieldState field) {
          return GestureDetector(
            onTap: () => showModalBottomSheetFormImageUpload(context, field),
            child: Container(
              margin: GeneralConstants.instance.margin10,
              padding: widget.padding,
              height: 110,
              constraints: BoxConstraints(
                  maxWidth: ScreenTypeData.fullWidth(context) * .35,
                  minWidth: ScreenTypeData.fullWidth(context) * .35),
              decoration: BoxDecoration(
                  color: AppTheme.whiteColor,
                  borderRadius: BorderRadius.circular(15.0),
                  border: Border.all(width: 1, color: AppTheme.secondaryColor)),
              child: (field.value != null)
                  // ? Image.memory(base64Decode(field.value))
                  ? CachedMemoryImage(uniqueKey: field.value,base64: field.value,height: 110,fit: BoxFit.cover,)
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                          const SizedBox(
                            height: 10,
                          ),
                          const Icon(Icons.image),
                          const SizedBox(
                            height: 20,
                          ),
                          if (widget.title != null) Text(widget.title!),
                          if (widget.title != null)
                            const SizedBox(
                              height: 5,
                            ),
                          if (widget.placeHolder != null)
                            Text(
                              widget.placeHolder!,
                              style: Theme.of(context).textTheme.caption,
                            ),
                        ]),
            ),
          );
        });
  }
}
