import 'package:flutter/material.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';

import '../../../../../controllers/validator/validator.dart';
import '../../../../../models/service_request/spare_parts.dart';
import '../../../../../new_views/app_style/app_color.dart';
import '../../../../../new_views/common_widgets/app_filled_button.dart';
import '../../../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../../../new_views/common_widgets/single_item_drop_down_menu.dart';
import '../../../../../providers/loading_list_notifier.dart';

class PartNoButton extends StatefulWidget {
  final List<SparePart> spareParts;
  final List<SparePartsWorkOrders>? initialList;
  final TextEditingController controller;
  final bool disablePartEdit;
  final Function(List<SparePartsWorkOrders> sparePart)? onChange;

  const PartNoButton({required this.spareParts, required this.controller, this.initialList, this.onChange, this.disablePartEdit = false, Key? key}) : super(key: key);

  @override
  State<PartNoButton> createState() => _PartNoButtonState();
}

class _PartNoButtonState extends State<PartNoButton> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  List<SparePartsWorkOrders> list = [];
  SparePartsWorkOrders current = SparePartsWorkOrders();

  @override
  void initState() {
    super.initState();
    list = widget.initialList ?? [];
  }

  @override
  void didUpdateWidget(covariant PartNoButton oldWidget) {
    if (widget.initialList != oldWidget.initialList) {
      setState(() {
        list = widget.initialList ?? [];
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: ExpansionTile(
        title: context.translation.partNo.heading6(context),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        collapsedShape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        tilePadding: const EdgeInsets.symmetric(horizontal: 16),
        childrenPadding: const EdgeInsets.symmetric(horizontal: 16),
        backgroundColor: AppColor.background(context),
        collapsedBackgroundColor: AppColor.background(context),
        iconColor: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
        collapsedIconColor: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
        children: [
          SingleItemDropDownMenu<SparePart, NullableLoadingProvider>(
            context: context,
            title: context.translation.partNo,
            staticData: widget.spareParts,
            initialValue: current.sparePart,
            backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral30,
            // initialValue: (_serviceReport.sparePartsWorkOrders?.isNotEmpty ?? false) ? _serviceReport.sparePartsWorkOrders.first.sparePart : null,
            onSelect: (part) {
              current = SparePartsWorkOrders(id: 0, sparePart: part, qty: 0);
              setState(() {});
            },
          ),
          8.height,
          AppTextFormField(
            controller: widget.controller,
            labelText: context.translation.quantity,
            textInputType: TextInputType.number,
            backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral30,
            enable: current.sparePart?.id != null,
            validator: (value) => value == null || value.isEmpty
                ? context.translation.requiredField
                : Validator.isNumeric(value)
                    ? null
                    : context.translation.onlyNumbers,
            onSaved: (text) {
              current.qty = num.tryParse(text ?? "");
            },
          ),
          8.height,
          AppFilledButton(
            label: context.translation.add,
            maxWidth: true,
            textColor: Colors.white,
            buttonColor: widget.disablePartEdit ? AppColor.neutral20 : AppColor.neutral50,
            onPressed: widget.disablePartEdit
                ? null
                : () {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState!.save();
                      list.add(current);
                      if (widget.onChange != null) widget.onChange!(list);
                      current = SparePartsWorkOrders();
                      widget.controller.text = "";
                      setState(() {});
                    }
                  },
          ),
          16.height,
          const Divider().defaultStyle(context),
          if (list.isNotEmpty) 16.height,
          if (list.isNotEmpty)
            ListView.separated(
              shrinkWrap: true,
              itemCount: list.length,
              padding: EdgeInsets.only(bottom: 16.toScreenHeight),
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (context, index) => Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      "${list[index].sparePart?.partNo} / ${list[index].sparePart?.partName}".bodyText(context).expanded,
                      list[index].qty.toString().bodyText(context),
                      32.width,
                      "trash".toSvgAsset(color: widget.disablePartEdit ? Colors.grey : null).onPress(widget.disablePartEdit
                          ? null
                          : () {
                              list.remove(list[index]);
                              if (widget.onChange != null) widget.onChange!(list);
                              setState(() {});
                            }),
                    ],
                  ),
                  if (widget.disablePartEdit)
                    Row(
                      children: [
                        AppTextFormField(
                          controller: TextEditingController(),
                          labelText: "Installed Qty",
                          textInputType: TextInputType.number,
                          backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral30,
                          enable: true,
                          initialValue: list[index].installQty?.toInt().toString() ?? "",
                          validator: (value) => value == null || value.isEmpty
                              ? context.translation.requiredField
                              : Validator.isNumeric(value)
                                  ? null
                                  : context.translation.onlyNumbers,
                          onChange: (text) {
                            list[index].installQty = num.tryParse(text ?? "");
                            if (widget.onChange != null) widget.onChange!(list);
                          },
                          onSaved: (text) {
                            list[index].installQty = num.tryParse(text ?? "");
                          },
                        ).expanded,
                        8.width,
                        AppTextFormField(
                          controller: TextEditingController(),
                          labelText: "Returned Qty",
                          textInputType: TextInputType.number,
                          backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral30,
                          enable: true,
                          initialValue: list[index].returnQty?.toInt().toString() ?? "",
                          validator: (value) => value == null || value.isEmpty
                              ? context.translation.requiredField
                              : Validator.isNumeric(value)
                                  ? null
                                  : context.translation.onlyNumbers,
                          onChange: (text) {
                            list[index].returnQty = num.tryParse(text ?? "");
                            if (widget.onChange != null) widget.onChange!(list);
                          },
                          onSaved: (text) {
                            list[index].returnQty = num.tryParse(text ?? "");
                          },
                        ).expanded,
                      ],
                    ).paddingOnly(top: 4, bottom: 4),
                ],
              ).paddingOnly(top: 4, bottom: 4),
              separatorBuilder: (context, index) => 8.height,
            )
        ],
      ),
    );
  }
}
