// ignore_for_file: non_constant_identifier_names, must_be_immutable

import 'dart:convert';

import 'package:cached_memory_image/cached_memory_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:general_package/constants/constants.dart';
import 'package:general_package/dynamic_form/src/model/dynamic_form_model.dart';
import 'package:general_package/dynamic_form/src/view/dynamic_form_button.dart';
import 'package:general_package/dynamic_form/src/view/dynamic_form_input.dart';
import 'package:general_package/themes/themes.dart';
import 'package:get/get.dart';

class DynamicForm extends StatefulWidget {
  DynamicForm({super.key, required this.dynamicForm});
  DynamicFormModel dynamicForm;

  @override
  State<DynamicForm> createState() => _DynamicFormState();
}

class _DynamicFormState extends State<DynamicForm> {
  final _globalFormKey = GlobalKey<FormBuilderState>();
  bool doneInit = false;
  @override
  void initState() {
    super.initState();
    for (var field in widget.dynamicForm.fields) {
      if (field.value != null) {
        _globalFormKey.currentState!.fields[field.name]!.didChange(field.value);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    var dynamicForm = widget.dynamicForm;
    if (!doneInit) {
      for (var element in dynamicForm.fields) {
        if (element.onCondition != null) {
          var keyName = element.onCondition!.conditionFieldName.toString();
          var keyValue = element.onCondition!.equalValue.toString();
          var indexFelid = dynamicForm.fields
              .indexWhere((element) => element.name == keyName);
          // print("have condition on init");
          // print(indexFelid);
          if (keyValue == dynamicForm.fields[indexFelid].value) {
            setState(() {
              element.visible = true;
              doneInit = true;
            });
          } else {
            setState(() {
              element.visible = false;
              doneInit = true;
            });
          }
        } else {
          // print(element.name);
        }
      }
      for (var dynamicFormData in dynamicForm.sections) {
        for (var element in dynamicFormData.fields) {
          if (element.onCondition != null) {
            var keyName = element.onCondition!.conditionFieldName.toString();
            var keyValue = element.onCondition!.equalValue.toString();
            var indexSection = dynamicForm.sections.indexOf(dynamicFormData);
            var indexFelid = dynamicForm.sections[indexSection].fields
                .indexWhere((element) => element.name == keyName);

            // print("have condition on init sections");
            // print(indexFelid);
            if (keyValue ==
                dynamicForm.sections[indexSection].fields[indexFelid].value) {
              setState(() {
                element.visible = true;
                doneInit = true;
              });
            } else {
              setState(() {
                element.visible = false;
                doneInit = true;
              });
            }
          } else {
            // print(element.name);
          }
        }
      }
    }
    return FormBuilder(
      key: _globalFormKey,
      onChanged: () {
        _globalFormKey.currentState!.save();
        if (kDebugMode) {
          print(_globalFormKey.currentState!.value);
        }
        for (var element in dynamicForm.buttons) {
          Map<String, dynamic> tempPostDate = Map.from(element.postData);
          _globalFormKey.currentState!.value.forEach((key, value) {
            element.postData.forEach((keyPostData, valuePostData) {
              if (keyPostData != key) {
                tempPostDate.addAll({key: value});
              }
            });
          });
          setState(() {
            element.postData = tempPostDate;
          });
        }
        for (var element in dynamicForm.fields) {
          if (element.onCondition != null) {
            if (_globalFormKey.currentState!
                        .value[element.onCondition!.conditionFieldName] !=
                    null ||
                _globalFormKey.currentState!
                        .value[element.onCondition!.conditionFieldName] !=
                    '') {
              if (_globalFormKey.currentState!
                      .value[element.onCondition!.conditionFieldName] ==
                  element.onCondition!.equalValue) {
                setState(() {
                  element.visible = true;
                });
              } else {
                setState(() {
                  element.visible = false;
                });
              }
            } else {
              setState(() {
                element.visible = false;
              });
            }
          } else {
            print(element.name);
          }
        }

        for (var dynamicFormData in dynamicForm.sections) {
          for (var element in dynamicFormData.fields) {
            if (element.onCondition != null) {
              // print("have condition on change sections");
              // print(indexFelid);
              // if (keyValue == dynamicForm.sections[indexSection].fields[indexFelid].value)
              if (_globalFormKey.currentState!
                          .value[element.onCondition!.conditionFieldName] !=
                      null ||
                  _globalFormKey.currentState!
                          .value[element.onCondition!.conditionFieldName] !=
                      '') {
                if (_globalFormKey.currentState!
                        .value[element.onCondition!.conditionFieldName] ==
                    element.onCondition!.equalValue) {
                  setState(() {
                    print(element.onCondition!.equalValue);
                    element.visible = true;
                    doneInit = true;
                  });
                } else {
                  setState(() {
                    element.visible = false;
                    doneInit = true;
                  });
                }
              } else {
                // print(element.name);
              }
            } else {
              // print("don't have condition on change sections");
            }
          }
        }
      },
      child: Container(
        padding: GeneralConstants.instance.padding20,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            if (dynamicForm.isBackButton)
              SizedBox(
                height: 100,
                child: InkWell(
                    onTap: () {
                      Get.back();
                    },
                    child: const Icon(
                      Icons.arrow_back,
                      size: 32,
                    )),
              ),
            if (dynamicForm.image != null)
              Center(
                child: CachedMemoryImage(
                  uniqueKey: dynamicForm.image!,
                  base64: dynamicForm.image,
                  width: dynamicForm.imageWidth,
                  height: dynamicForm.imageHeight,
                ),
                // child: Image.memory(
                //   base64Decode(dynamicForm.image!),
                //   width: dynamicForm.imageWidth,
                //   height: dynamicForm.imageHeight,
                // ),
              ),
            if (dynamicForm.title != null)
              const SizedBox(
                height: 20,
              ),
            if (dynamicForm.title != null)
              Container(
                padding: GeneralConstants.instance.padding5,
                child: Text(
                  dynamicForm.title!,
                  style: Theme.of(context).textTheme.headline3,
                  textAlign: TextAlign.left,
                ),
              ),
            if (dynamicForm.description != null)
              const SizedBox(
                height: 20,
              ),
            if (dynamicForm.description != null)
              Container(
                padding: GeneralConstants.instance.padding5,
                child: Text(
                  dynamicForm.description!,
                  style: Theme.of(context).textTheme.subtitle1,
                ),
              ),
            const SizedBox(
              height: 20,
            ),
            Column(
              children: dynamicForm.fields
                  .map((dynamicFormField) => DynamicFormInput(
                        dynamicFormFieldModel: dynamicFormField,
                      ))
                  .toList(),
            ),
            Column(
              children: dynamicForm.sections
                  .map((DynamicFormSection) => Container(
                        margin: GeneralConstants.instance.margin5,
                        padding: GeneralConstants.instance.padding10,
                        decoration: BoxDecoration(
                          color: AppTheme.whiteColor,
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Column(
                          children: [
                            Padding(
                              padding: GeneralConstants.instance.padding5,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  if (DynamicFormSection.title != null)
                                    Text(DynamicFormSection.title!,
                                        style: Theme.of(context)
                                            .textTheme
                                            .headline3),
                                  if (DynamicFormSection.prefixTitle != null)
                                    Text(DynamicFormSection.prefixTitle!,
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodyText2!
                                            .copyWith(
                                                color: DynamicFormSection
                                                    .prefixTitleColor)),
                                ],
                              ),
                            ),
                            if (DynamicFormSection.subTitle != null)
                              Padding(
                                padding: GeneralConstants.instance.padding5,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text(DynamicFormSection.subTitle!,
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodyText1),
                                  ],
                                ),
                              ),
                            Column(
                              children: DynamicFormSection.fields
                                  .map((dynamicFormField) => DynamicFormInput(
                                        dynamicFormFieldModel: dynamicFormField,
                                      ))
                                  .toList(),
                            ),
                          ],
                        ),
                      ))
                  .toList(),
            ),
            if (dynamicForm.bottomImage != null)
              SizedBox(
                width: double.infinity,
                child: Center(
                  child: CachedMemoryImage(
                    uniqueKey: dynamicForm.bottomImage!,
                    base64: dynamicForm.bottomImage,
                    width: dynamicForm.bottomImageWidth,
                    height: dynamicForm.bottomImageHeight,
                  ),
                ),
              ),
            const SizedBox(
              height: 20,
            ),
            Center(
              child: Column(
                  children: dynamicForm.buttons
                      .map((dynamicFormButton) => Padding(
                            padding: GeneralConstants.instance.padding10,
                            child: DynamicFormButton(
                              dynamicFormButtonModel: dynamicFormButton,
                            ),
                          ))
                      .toList()),
            ),
            const SizedBox(
              height: 20,
            ),
          ],
        ),
      ),
    );
  }
}
