import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/enum_extensions.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/models/lookup.dart';
import 'package:test_sa/modules/asset_delivery_module/models/cost_center_model.dart';
import 'package:test_sa/modules/asset_delivery_module/models/cost_center_serial_no_form_model.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/cost_center_provider.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.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/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';

class CostCenterFormView extends StatefulWidget {
  final List<CostCenterModel>? costCenterList;
  final String? itemNo;
  final String? itemDescription;
  final int? lineId;
  final int? tableItemId;
  final int? requestId;
  final bool? isHmg;
  final double? cardPadding;

  const CostCenterFormView({
    super.key,
    this.costCenterList,
    this.lineId,
    this.requestId,
    this.tableItemId,
    this.itemNo,
    this.isHmg,
    this.itemDescription,
    this.cardPadding,
  });

  @override
  State<CostCenterFormView> createState() => _CostCenterFormViewState();
}

class _CostCenterFormViewState extends State<CostCenterFormView> {
  CostCenterSerialNoFormModel formModel = CostCenterSerialNoFormModel(costCenters: [], serialNos: []);
  late AssetDeliveryProvider assetDeliveryProvider;
  CostCenterType _selectedType = CostCenterType.costCenter;

  @override
  void initState() {
    super.initState();
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
  }

  void getInitialData() async {
    formModel = await assetDeliveryProvider.getAssetDeliveryCostCenterListForLines(
      lineId: widget.lineId,
      tableItemId: widget.tableItemId,
    );
    if (formModel.costCenters!.isEmpty) {
      formModel.costCenters!.add(CostCenterModel(
        id: 0,
      ));
    }
    // if (formModel.serialNos!.isEmpty) {
    //   formModel.serialNos!.add(SerialNoModel(
    //     id: 0,
    //   ));
    // }
    if (widget.isHmg == true) {
      CostCenterProvider costCenterProvider = Provider.of<CostCenterProvider>(context, listen: false);
      if (costCenterProvider.items.isEmpty) {
        await costCenterProvider.getData(id: widget.requestId);
      }
    }
    setState(() {});
  }

  void addItem<T>(List<T> list, T Function() creator) {
    setState(() {
      list.add(creator());
    });
  }

  void removeItem<T>(List<T> list, int index) {
    setState(() {
      list.removeAt(index);
    });
  }

  void updateItem<T>(List<T> list, int index, void Function(T item) updater) {
    setState(() {
      updater(list[index]);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: DefaultAppBar(
        title: 'Cost Center for Item'.addTranslation,
        // onBackPress: () {
        //   Navigator.pop(context);
        // },
      ),
      body: Consumer<AssetDeliveryProvider>(builder: (context, provider, child) {
        return provider.isLoading
            ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
            : Column(
          children: [
            ListView(
              padding: const EdgeInsets.all(16),
              children: [
                itemDetails(),
                12.height,
                selectionButton(),
                12.height,
                _selectedType == CostCenterType.costCenter ? _buildCostCenterList() : _buildSerialNumberList(),
              ],
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                  buttonColor: AppColor.primary10,
                  label: 'Save'.addTranslation,
                  maxWidth: true,
                  onPressed: () async {
                    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                    await assetDeliveryProvider
                        .saveCostCenterToLineDeliveryInspection(tableItemId: widget.tableItemId, lineId: widget.lineId, list: formModel.costCenters, serialNoList: formModel.serialNos)
                        .then((status) async {
                      Navigator.pop(context);
                      if (status) {
                        Navigator.pop(context);
                        assetDeliveryProvider.getDeliveryLinesListById(
                          itemId: widget.tableItemId,
                        );
                      }
                    });
                  }),
            ),
          ],
        );
      }),
    );
  }

  Widget _buildCostCenterList() {
    return ListView.separated(
      itemCount: formModel.costCenters!.length + 1,
      shrinkWrap: true,
      padding: EdgeInsets.zero,
      physics: const NeverScrollableScrollPhysics(),
      separatorBuilder: (context, index) => 12.height,
      itemBuilder: (context, index) {
        if (index == formModel.costCenters!.length) {
          return AppFilledButton(
            label: "Add Cost Center".addTranslation,
            maxWidth: true,
            textColor: AppColor.textColor(context),
            buttonColor: context.isDark ? AppColor.neutral60 : AppColor.white10,
            icon: Icon(Icons.add_circle, color: AppColor.blueStatus(context)),
            showIcon: true,
            onPressed: () {
              addItem(formModel.costCenters!, () => CostCenterModel(costCenter: Lookup()));
            },
          );
        }

        return CostCenterItemCard(
          model: formModel.costCenters![index],
          index: index,
          isReadOnly: false,
          isHmg: widget.isHmg,
          requestId: widget.requestId,
          onUpdate: (update) {
            updateItem<CostCenterModel>(formModel.costCenters!, index, update);
          },
          onRemove: () {
            removeItem<CostCenterModel>(formModel.costCenters!, index);
          },
        );
      },
    ).expanded;
  }

  Widget _buildSerialNumberList() {
    return ListView.separated(
      itemCount: formModel.serialNos!.length + 1,
      shrinkWrap: true,
      padding: EdgeInsets.zero,
      physics: const NeverScrollableScrollPhysics(),
      separatorBuilder: (context, index) => 12.height,
      itemBuilder: (context, index) {
        if (index == formModel.serialNos!.length) {
          return AppFilledButton(
            label: "Add Serial Number".addTranslation,
            maxWidth: true,
            textColor: AppColor.textColor(context),
            buttonColor: context.isDark ? AppColor.neutral60 : AppColor.white10,
            icon: Icon(Icons.add_circle, color: AppColor.blueStatus(context)),
            showIcon: true,
            onPressed: () {
              addItem(formModel.serialNos!, () => SerialNoModel());
            },
          );
        }

        return SerialNumberItemCard(
          model: formModel.serialNos![index],
          onUpdate: (update) {
            updateItem<SerialNoModel>(formModel.serialNos!, index, update);
          },
          onRemove: () {
            removeItem<SerialNoModel>(formModel.serialNos!, index);
          },
        );
      },
    ).expanded;
  }

  Widget selectionButton() {
    return Row(
      children: [
        Expanded(
          child: _radioItem(
            value: CostCenterType.costCenter,
            groupValue: _selectedType,
            title: 'Cost Center',
            onTap: () {
              setState(() {
                _selectedType = CostCenterType.costCenter;
              });
            },
          ),
        ),
        Expanded(
          child: _radioItem(
            value: CostCenterType.serialNumber,
            groupValue: _selectedType,
            title: 'Serial Number',
            onTap: () {
              setState(() {
                _selectedType = CostCenterType.serialNumber;
              });
            },
          ),
        ),
      ],
    );
  }

  Widget _radioItem({
    required CostCenterType value,
    required CostCenterType groupValue,
    required String title,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Row(
        children: [
          Radio<CostCenterType>(
            value: value,
            activeColor: AppColor.primary10,
            fillColor: WidgetStateColor.resolveWith((states) {
              if (states.contains(WidgetState.selected)) {
                return AppColor.primary10; // Thumb color when selected
              }
              return AppColor.icon2Color(context); // Thumb color when unselected (grey)
            }),
            groupValue: groupValue,
            onChanged: (_) => onTap(),
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            visualDensity: VisualDensity.compact,
          ),
          4.width,
          title.addTranslation.bodyText(context),
        ],
      ),
    );
  }

  Widget itemDetails() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      spacing: 4,
      children: [
        InfoTextWidget(label: "Item No", value: "\n${widget.itemNo ?? '-'}"),
        InfoTextWidget(label: "Item Description", value: "\n${widget.itemDescription ?? '-'}"),
      ],
    ).toShadowContainer(context);
  }
}

class CostCenterItemCard extends StatelessWidget {
  final CostCenterModel model;
  final bool? isHmg;
  final int index;
  final int? requestId;
  final bool isReadOnly;
  final void Function(void Function(CostCenterModel model)) onUpdate;
  final VoidCallback onRemove;

  const CostCenterItemCard({
    super.key,
    required this.model,
    this.requestId,
    this.isHmg,
    required this.index,
    required this.isReadOnly,
    required this.onUpdate,
    required this.onRemove,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        if (!isReadOnly)
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              'Cost Center'.addTranslation.bodyText(context).custom(color: AppColor.textColor(context)),
              if (!isReadOnly)
                Container(
                  height: 28,
                  width: 28,
                  padding: const EdgeInsets.all(6),
                  child: "trash".toSvgAsset(height: 20, width: 20),
                ).onPress(onRemove),
            ],
          ),
        8.height,
        Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            isHmg == true
                ? SingleItemDropDownMenu<Lookup, CostCenterProvider>(
              context: context,
              height: 56.toScreenHeight,
              title: 'Cost Center'.addTranslation,
              showShadow: false,
              backgroundColor: AppColor.fieldBgColor(context),
              requestById: requestId,
              showAsBottomSheet: true,
              matchBy: DropDownMatchType.name,
              initialValue: model.costCenter,
              onSelect: (status) {
                if (status != null) {
                  model.costCenter = status;
                  model.costCenterName = status.name;
                }
              },
            )
                : AppTextFormField(
              labelText: 'Cost Center'.addTranslation,
              backgroundColor: AppColor.fieldBgColor(context),
              initialValue: model.costCenterName ?? '',
              textAlign: TextAlign.center,
              labelStyle: AppTextStyles.textFieldLabelStyle,
              showShadow: false,
              onChange: (value) {
                model.costCenterName = value;
              },
              style: Theme.of(context).textTheme.titleMedium,
            ),
            8.height,
            AppTextFormField(
              labelText: 'Quantity'.addTranslation,
              backgroundColor: AppColor.fieldBgColor(context),
              initialValue: model.quantity != null ? model.quantity.toString() : '',
              textAlign: TextAlign.center,
              enable: true,
              textInputType: TextInputType.number,
              labelStyle: AppTextStyles.textFieldLabelStyle,
              showShadow: false,
              onChange: (value) {
                if (value.isNotEmpty) {
                  model.quantity = double.tryParse(value);
                }
              },
              style: Theme.of(context).textTheme.titleMedium,
            ),
          ],
        )
      ],
    ).toShadowContainer(context);
  }
}

class SerialNumberItemCard extends StatelessWidget {
  final SerialNoModel model;
  final VoidCallback onRemove;
  final void Function(void Function(SerialNoModel model)) onUpdate;

  const SerialNumberItemCard({
    super.key,
    required this.model,
    required this.onRemove,
    required this.onUpdate,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            'Serial Number'.addTranslation.bodyText(context),
            Container(
              height: 28,
              width: 28,
              padding: const EdgeInsets.all(6),
              child: "trash".toSvgAsset(height: 20, width: 20),
            ).onPress(onRemove),
          ],
        ),
        8.height,
        AppTextFormField(
          labelText: 'Serial Number'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          initialValue: model.serialNo ?? '',
          textAlign: TextAlign.center,
          showShadow: false,
          onChange: (value) {
            model.serialNo = value;
          },
          style: Theme.of(context).textTheme.titleMedium,
        ),
      ],
    ).toShadowContainer(context);
  }
}
