import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:road24_mobile/data/repository/SelectBrandsRepository.dart';
import 'package:road24_mobile/model/blocs/brands/select_brands_bloc.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'widgets/select_brand_item.dart';
import 'widgets/other_dialog.dart';

mixin SelectBrandImp {
  void onUpdateBrand({String brandName = '', String? imageUrl, int? brandId});
}

class SelectBrandDialog extends StatefulWidget {
  final String title;
  final SelectBrandImp imp;

  SelectBrandDialog._(this.title, this.imp);

  static void show(
    BuildContext context, {
    required String title,
    required SelectBrandImp imp,
  }) {
    showBarModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      builder: (_) => SelectBrandDialog._(title, imp),
    );
  }

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

class _SelectBrandDialogState extends State<SelectBrandDialog> {
  final TextEditingController _controller = TextEditingController();
  final focusNode = FocusNode();

  var brandBloc = SelectBrandBloc(repository: SelectBrandsRepository());

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

    brandBloc.add(GetBrandsList());

    _controller.addListener(() {
      brandBloc.add(SearchBrandsFromList(_controller.text));
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    focusNode.dispose();
    brandBloc.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return
        // ViewModelBuilder<SelectBrandViewModel>.reactive(
        //   viewModelBuilder: () => SelectBrandViewModel(),
        //   onModelReady: (model) async {
        //     _controller.addListener(() => model.onChangedText(_controller.text));
        //     await model.init();
        //   },
        //   onDispose: (model) => _controller.dispose(),
        //   builder: (context, model, child) =>

        BlocBuilder(
            bloc: brandBloc,
            builder: (context, state) {
              return GestureDetector(
                onTap: () => focusNode.canRequestFocus = false,
                child: Container(
                  width: double.infinity,
                  height: MediaQuery.of(context).size.height * 0.8,
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  color: Colors.white,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(height: 20),
                      Text(
                        widget.title,
                        style: AppStyle.textStyle().copyWith(
                          color: Colors.black,
                          fontSize: 17,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const SizedBox(height: 20),
                      TextField(
                        controller: _controller,
                        focusNode: focusNode,
                        decoration: InputDecoration(
                          hintText: widget.title,
                          hintStyle: TextStyle(
                              fontSize: 17.0, color: Color(0xff959595)),
                          suffixIcon: Icon(Icons.search, color: Colors.black),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12.0),
                            borderSide: BorderSide(color: Colors.transparent),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12.0),
                            borderSide: BorderSide(
                                color: Color(0xFFE0E0E0), width: 1.0),
                          ),
                          fillColor: const Color(0xffEFEFEF),
                          filled: true,
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12.0),
                            borderSide:
                                BorderSide(color: Colors.black, width: 1.5),
                          ),
                          contentPadding: EdgeInsets.all(15.0),
                        ),
                      ),
                      const SizedBox(height: 10),
                      Expanded(child: _widgetList(state)),
                    ],
                  ),
                ),
                // ),
              );
            });
  }

  Widget _widgetList(state) {
    var _brandList = [];
    if (state is LoadingState || state is FoundBrandFromList) {
      if (state is FoundBrandFromList) {
        print("state is Found list ${state.carBrandList}");

        _brandList.clear();

        _brandList.addAll(state.carBrandList);
      }

      return Scrollbar(
        thickness: 8,
        radius: const Radius.circular(6),
        child: SingleChildScrollView(
          child: Column(
            children: [
              if (state is LoadingState) _widgetOtherButton(),
              ListView.separated(
                physics: const NeverScrollableScrollPhysics(),
                itemCount: (state is LoadingState) ? 50 : _brandList.length + 1,
                shrinkWrap: true,
                separatorBuilder: (context, i) {
                  return const Divider(thickness: 1, color: Color(0xFFCACACA));
                },
                itemBuilder: (context, i) {
                  if (state is LoadingState) return const SelectBrandItem();

                  if (i == _brandList.length) return _widgetOtherButton();

                  if (state is FoundBrandFromList) {
                    return SelectBrandItem(
                      isLoading: false,
                      imageUrl: _brandList[i].logo?.file,
                      text: _brandList[i].name,
                      term: _controller.text,
                      onPressed: () {
                        widget.imp.onUpdateBrand(
                          brandName: _brandList[i].name,
                          imageUrl: _brandList[i].logo?.file,
                          brandId: _brandList[i].id,
                        );
                        Navigator.pop(context);
                      },
                    );
                  }

                  return _widgetOtherButton();
                },
              ),
            ],
          ),
        ),
      );
    }
    return ListView(children: [_widgetOtherButton()]);
  }

  Widget _widgetOtherButton() {
    return GestureDetector(
      onTap: () async {
        await OtherDialog.show(
          context,
          imp: widget.imp,
          title: widget.title,
          text: _controller.text,
        );
        Navigator.pop(context);
      },
      child: Container(
        width: double.infinity,
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: AppColors.selectedColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Text(
          S.of(context).my_car_other,
          style: AppStyle.textStyle().copyWith(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }
}
