import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/dashboard_latest/widgets/app_bar_widget.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/asset_delivery_module/models/inspection_person_model.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/delivery_inspection/oracle_user_autocomplete_field.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/e_signature/e_signature.dart';

class InspectionPersonBottomSheet extends StatefulWidget {
  final String title;
  bool isHmg;
  final InspectionPersonModel model;
  int? tableId;

  InspectionPersonBottomSheet({
    super.key,
    required this.title,
    required this.isHmg,
    required this.model,
    this.tableId,
  });

  @override
  State<InspectionPersonBottomSheet> createState() => _InspectionPersonBottomSheetState();
}

class _InspectionPersonBottomSheetState extends State<InspectionPersonBottomSheet> {
  late InspectionPersonModel _model;

  late TextEditingController nameController;
  late TextEditingController emailController;

  @override
  void initState() {
    super.initState();

    _model = InspectionPersonModel(name: widget.model.name, email: widget.model.email, signature: widget.model.signature, localSignature: widget.model.localSignature);
    nameController = TextEditingController(text: _model.name ?? '');
    emailController = TextEditingController(text: _model.email ?? '');
  }

  @override
  void dispose() {
    nameController.dispose();
    emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Padding(
        padding: EdgeInsets.only(
          top: 16,
          left: 16,
          right: 16,
          bottom: MediaQuery.of(context).viewInsets.bottom + MediaQuery.of(context).padding.bottom,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 12,
          children: [
            widget.title.heading4(context),
            if (widget.isHmg)
              OracleUserAutoCompleteField(
                clearAfterPick: false,
                initialValue: _model.name ?? '',
                label: 'Name'.addTranslation,
                onPick: (value) {
                  _model.name = value.fullName;
                  nameController.text = value.fullName ?? '';
                  emailController.text = value.employeeEmail ?? '';
                  setState(() {});
                },
              )
            else
              AppTextFormField(
                labelText: 'Name'.addTranslation,
                controller: nameController,
                backgroundColor: AppColor.fieldBgColor(context),
                showShadow: false,
                textAlign: TextAlign.center,
                labelStyle: AppTextStyles.textFieldLabelStyle,
                style: Theme.of(context).textTheme.titleMedium,
                onChange: (v) {
                  _model.name = v;
                  setState(() {});
                },
              ),
            Row(
              children: [
                AppTextFormField(
                  labelText: 'Email'.addTranslation,
                  controller: emailController,
                  textInputType: TextInputType.emailAddress,
                  backgroundColor: AppColor.fieldBgColor(context),
                  showShadow: false,
                  enable: widget.isHmg ? false : true,
                  textAlign: TextAlign.center,
                  labelStyle: AppTextStyles.textFieldLabelStyle,
                  style: Theme.of(context).textTheme.titleMedium,
                  onChange: (v) {
                    setState(() {
                      _model.email = v;
                    });
                  },
                ).expanded,
                if (emailController.text.isNotEmpty) ...[
                  12.width,
                  AppFilledButton(
                      buttonColor: AppColor.primary10,
                      label: 'SendEmail'.addTranslation,
                      width: 100.toScreenWidth,
                      height: 54,
                      onPressed: () async {
                        AssetDeliveryProvider assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
                        if (nameController.text.isEmpty) {
                          return 'Enter Name'.showToast;
                        }
                        String type = '';
                        if (widget.title.contains('Inspected')) {
                          type = 'Inspected';
                        } else if (widget.title.contains('Approved')) {
                          type = 'Approved';
                        } else if (widget.title.contains('ThirdApprover')) {
                          type = 'ThirdApprover';
                        }

                        Map<String, dynamic> payload = {
                          "recordId": widget.tableId,
                          "parameter1": "DeliveryInspection",
                          "parameter2": type,
                          "username": nameController.text,
                          "email": emailController.text
                        };
                        showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                        await assetDeliveryProvider.sendEmailToAddSignature(requestPayload: payload).then((status) async {
                          Navigator.pop(context);
                          if (status) {
                            'Email sent successfully'.showToast;
                          }
                        });

                        //send email.
                      }),
                ],
              ],
            ),
            ESignature(
              title: '',
              editable: false,
              oldSignature: _model.localSignature == null ? _model.signature : null,
              newSignature: _model.localSignature,
              backgroundColor: AppColor.neutral100,
              showShadow: false,
              // onChange: (signature) {
              //   if (signature.isEmpty) return;
              //   setState(() {
              //     _model.localSignature = signature;
              //     _model.signature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
              //   });
              // },
              // onSaved: (signature) {
              //   if (signature == null || signature.isEmpty) return;
              //   setState(() {
              //     _model.localSignature = signature;
              //     _model.signature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
              //   });
              // },
            ),
            AppFilledButton(
              label: context.translation.save,
              maxWidth: true,
              buttonColor: AppColor.primary10,
              onPressed: () async {
                _model.name = nameController.text.trim();
                _model.email = emailController.text.trim();
                Navigator.pop(context, _model);
              },
            ),
          ],
        ),
      ),
    );
  }
}
