import 'package:farm_tpf/custom_model/action_form/RequestActivity.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
import 'package:farm_tpf/presentation/screens/actions/controller/ChangeFieldInForm.dart';
import 'package:farm_tpf/presentation/screens/actions/controller/ChangeWorker.dart';
import 'package:farm_tpf/utils/const_string.dart';
import 'package:farm_tpf/utils/validators.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

class WidgetWorker extends StatefulWidget {
  final Function(List<TbNurseryDetailsDTO>) onChangeWorkers;
  const WidgetWorker({required this.onChangeWorkers});

  @override
  _WidgetWorkerState createState() => _WidgetWorkerState();
}

class _WidgetWorkerState extends State<WidgetWorker> {
  GlobalKey<FormState> _formWorkerKey = GlobalKey();
  TextEditingController _workerNameController = TextEditingController();
  TextEditingController _trayNumberController = TextEditingController();
  ChangeWorker? controller;
  final changeFormField = Get.put(ChangeFieldFormSupply());
  @override
  void initState() {
    super.initState();
    controller = Get.put(ChangeWorker());
    controller?.init([]);
    changeFormField.init();
  }

  Widget _buildListWorker() {
    return GetBuilder<ChangeWorker>(
        init: controller,
        builder: (data) {
          widget.onChangeWorkers(data.currentItems ?? []);
          if (data.currentItems?.length == 0 || data.currentItems == null) {
            return Container();
          } else {
            return Container(
                height: 70,
                child: ListView.builder(
                    physics: ClampingScrollPhysics(),
                    scrollDirection: Axis.horizontal,
                    shrinkWrap: true,
                    itemCount: data?.currentItems?.length ?? 0,
                    itemBuilder: (context, index) {
                      return GestureDetector(
                          onTap: () {
                            print("edit worker");
                          },
                          child: Card(
                              child: Stack(
                            alignment: Alignment.bottomCenter,
                            children: <Widget>[
                              Positioned(
                                  child: ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: Container(
                                  padding: EdgeInsets.all(4),
                                  width: 120,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      SizedBox(
                                        height: 12.0,
                                      ),
                                      Flexible(
                                        child: Text(data.currentItems?[index].workerName ?? '', overflow: TextOverflow.ellipsis, maxLines: 1),
                                      ),
                                      Validators.stringNotNullOrEmpty(data.currentItems?[index].trayNumber ?? '')
                                          ? Flexible(child: Text(data.currentItems?[index].trayNumber ?? ''))
                                          : SizedBox()
                                    ],
                                  ),
                                ),
                              )),
                              Positioned(
                                top: -10,
                                right: -10,
                                child: IconButton(
                                    icon: Icon(
                                      Icons.cancel,
                                      color: Colors.redAccent,
                                    ),
                                    onPressed: () {
                                      controller?.deleteNurseryDetail(index);
                                      print("Delete worker");
                                    }),
                              )
                            ],
                          )));
                    }));
          }
        });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChangeWorker>(
        init: controller,
        builder: (data) {
          return Container(
              child: Form(
            key: _formWorkerKey,
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  height: 16,
                  color: Colors.grey[200],
                ),
                SizedBox(
                  height: 8.0,
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      'Người thực hiện',
                      style: TextStyle(color: Colors.black54, fontSize: 14),
                    ),
                  ),
                ),
                _buildListWorker(),
                Container(
                  padding: EdgeInsets.all(8.0),
                  margin: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.white,
                      border: Border.all(color: Colors.grey)),
                  child: Column(
                    children: [
                      TextFormField(
                        keyboardType: TextInputType.text,
                        controller: _workerNameController,
                        decoration: InputDecoration(labelText: "Tên công nhân *"),
                        validator: (value) {
                          return Validators.validateNotNullOrEmpty(value ?? '', label_validate_input_empty);
                        },
                        onSaved: (newValue) {},
                        onChanged: (value) {
                          if (!Validators.stringNotNullOrEmpty(value)) {
                            changeFormField.change(false);
                          } else {
                            changeFormField.change(true);
                          }
                        },
                      ),
                      TextFormField(
                        keyboardType: TextInputType.text,
                        controller: _trayNumberController,
                        decoration: InputDecoration(labelText: "Ươm khây số"),
                        onSaved: (newValue) {},
                        onChanged: (value) {
                          if (!Validators.stringNotNullOrEmpty(value)) {
                            changeFormField.change(false);
                          } else {
                            changeFormField.change(true);
                          }
                        },
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.all(8),
                  child: TextButton(
                      onPressed: () {
                        if (_formWorkerKey.currentState!.validate()) {
                          _formWorkerKey.currentState!.save();
                          if (Validators.stringNotNullOrEmpty(_workerNameController.text)) {
                            TbNurseryDetailsDTO _nurseryDetail = TbNurseryDetailsDTO()
                              ..workerName = _workerNameController.text
                              ..trayNumber = _trayNumberController.text;
                            controller?.addNurseryDetail(_nurseryDetail);
                            _workerNameController.clear();
                            _trayNumberController.clear();
                            changeFormField.change(false);
                          } else {
                            Utils.showSnackBarWarning(message: "Vui lòng nhập tên công nhân");
                          }
                        } else {
                          //
                          if (!Validators.stringNotNullOrEmpty(_workerNameController.text)) {
                            Utils.showSnackBarWarning(message: "Vui lòng nhập tên công nhân");
                          }
                        }
                      },
                      child: Text(
                        "+ Thêm người thực hiện",
                        style: TextStyle(color: Colors.blue),
                      )),
                ),
              ],
            ),
          ));
        });
  }
}
