import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';

import '../../../app/app.dart';
import 'controller.dart';
import 'multi_select_item.dart';

class MultiSelectBottomSheetGetX extends StatelessWidget {
  /// The list of selected values before interaction.
  // final List<FilterOption> initialValue;

  /// The text at the top of the BottomSheet.
  // final String title;

  /// Used to [getData] from api.
  // final String modelCode;

  final FilterModel model;

  /// Fires when the an item is selected / unselected.
  final void Function(List<FilterOption>)? onSelectionChanged;

  /// Fires when confirm is tapped.
  final void Function(List<FilterOption>) onConfirm;

  /// Fires when clear is tapped.
  final void Function(List<FilterOption>) onClear;

  MultiSelectBottomSheetGetX({
    // required this.initialValue,
    // required this.title,
    // required this.modelCode,
    required this.model,
    required this.onConfirm,
    required this.onClear,
    this.onSelectionChanged,
  });

  /// Returns a CheckboxListTile
  Widget _buildListItem(BuildContext context, MultiSelectController msc, MultiSelectItem<FilterOption> item) {
    final theme = Theme.of(context);
    final oldCheckboxTheme = theme.checkboxTheme;

    final newCheckBoxTheme = oldCheckboxTheme.copyWith(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(300)),
    );
    return Theme(
      data: theme.copyWith(checkboxTheme: newCheckBoxTheme),
      child: Transform.translate(
        offset: Offset(-24, 0),
        child: Transform.scale(
          scale: 1.h,
          child: CheckboxListTile(
            checkColor: ThemeColor.white,
            value: item.selected,
            activeColor: ThemeColor.mainColor,
            title: model.code != 'color'
                ? Text(item.label)
                : Align(
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        item.value.swatchValue.isNotEmpty
                            ? CircleAvatar(
                                backgroundColor: Colors.grey,
                                maxRadius: 8.40.w,
                                child: CircleAvatar(
                                  backgroundColor: HexColor(item.value.swatchValue),
                                  maxRadius: 8.0.w,
                                ),
                              )
                            : SizedBox.shrink(),
                        SizedBox(width: 16.w),
                        Text(item.label),
                      ],
                    ),
                  ),
            controlAffinity: ListTileControlAffinity.leading,
            onChanged: (checked) => msc.onListBoxListTileChanged(
              item,
              onSelectionChanged,
              checked,
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final EdgeInsets mqPadding = MediaQuery.of(context).padding;
    var screenSize = MediaQuery.of(context).size;
    return GetBuilder<MultiSelectController>(
      init: MultiSelectController(model),
      builder: (msc) {
        final bool isLastPage = msc.lastPage.value;
        return Container(
          constraints: BoxConstraints(maxHeight: screenSize.height - mqPadding.top),
          padding: EdgeInsets.only(bottom: mqPadding.bottom + 16, top: 16, left: 16, right: 16),
          decoration: new BoxDecoration(
            color: ThemeColor.white,
            borderRadius: BorderRadius.only(topRight: Radius.circular(16), topLeft: Radius.circular(16)),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                padding: const EdgeInsets.only(top: 8),
                child: Center(child: SvgPicture.asset('assets/icons/drag_line.svg')),
              ),
              SizedBox(height: 8.h),
              // title
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(model.name, style: AppTheme.bottomSheetHeaderStyle),
                  SizedBox(height: 16),
                  // search box
                  Container(
                    padding: const EdgeInsets.all(8),
                    height: 40.h,
                    width: double.infinity,
                    decoration: new BoxDecoration(
                      color: ThemeColor.colorEFF0F4,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: TextFormField(
                      cursorColor: Colors.black,
                      inputFormatters: [new LengthLimitingTextInputFormatter(30)],
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        prefixIcon: Icon(
                          Icons.search,
                          size: 24.h,
                          color: Colors.grey,
                        ),
                      ),
                      onChanged: (val) => msc.onSearchChanged(val),
                    ),
                  ),
                  SizedBox(height: 20),
                  Row(
                    children: [
                      FadeIn(child: CircleNumberWidget(number: msc.selectedValues.length)),
                      SizedBox(width: 8),
                      Text(
                        'applied'.tr,
                        style: new TextStyle(
                          color: ThemeColor.color717278,
                          fontSize: 16.sp,
                        ),
                      ),
                      Spacer(),
                      msc.selectedValues.isNotEmpty
                          ? FadeIn(
                              child: TextButton(
                                child: Text('clear'.tr),
                                style: TextButton.styleFrom(foregroundColor: ThemeColor.mainColor),
                                onPressed: () => msc.clearFilter(context, onClear),
                              ),
                            )
                          : SizedBox.shrink(),
                    ],
                  ),
                ],
              ),

              AppTheme.appSizeDivider10H,

              // body
              Expanded(
                child: ConstrainedBox(
                  constraints: new BoxConstraints(minHeight: 0.3.sh),
                  child: msc.obx(
                    (state) => state != null
                        ? RefreshIndicator(
                            onRefresh: msc.getData,
                            color: ThemeColor.mainColor,
                            child: MediaQuery.removePadding(
                              context: context,
                              removeTop: true,
                              child: ListView.builder(
                                shrinkWrap: true,
                                controller: msc.scroll,
                                itemCount: state.length + 1,
                                itemBuilder: (context, index) {
                                  if (index < state.length) {
                                    return FadeIn(
                                      child: _buildListItem(context, msc, state[index]),
                                    );
                                  } else if (index == state.length && !isLastPage)
                                    return Padding(
                                      padding: const EdgeInsets.only(top: 10, bottom: 40),
                                      child: Center(
                                        child: CustomLoader(),
                                      ),
                                    );
                                  else {
                                    return SizedBox.shrink();
                                  }
                                },
                              ),
                            ),
                          )
                        : Center(
                            child: Text(
                              'error_occurred'.tr,
                              style: TextStyle(fontSize: 18),
                              textAlign: TextAlign.center,
                            ),
                          ),
                    onLoading: Center(child: CustomLoader()),
                    onEmpty: Align(
                      alignment: Alignment.topCenter,
                      child: ItemNotFoundWidget(),
                    ),
                    onError: (error) => Center(
                      child: Text(
                        'error_occurred'.tr,
                        style: TextStyle(fontSize: 18),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                ),
              ),

              // footer
              msc.selectedValues.isNotEmpty
                  ? FadeIn(
                      duration: Duration(milliseconds: 900),
                      child: ColoredButton(
                        title: 'done'.tr,
                        btnColor: ThemeColor.mainColor,
                        callback: () => msc.onConfirmSelection(
                          context,
                          onConfirm,
                        ),
                      ),
                    )
                  : SizedBox.shrink(),
            ],
          ),
        );
      },
    );
  }
}
