import 'package:boilerplate/domain/entities/product/product_list_filter_data.dart';
import 'package:boilerplate/presentation/widgets/ipm_textfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../../core/i18n/translations.g.dart';
import '../../../../../core/styles/my_colors.dart';
import '../../../../../core/styles/my_dimensions.dart';
import '../../../../../core/styles/my_font.dart';
import '../../../../bloc/products_list/products_bloc.dart';

class ProductListPriceFilter extends StatefulWidget {
  final GlobalKey<FormState> formkey;

  const ProductListPriceFilter({Key? key, required this.formkey})
      : super(key: key);

  @override
  State<ProductListPriceFilter> createState() => _ProductListPriceFilterState();
}

class _ProductListPriceFilterState extends State<ProductListPriceFilter> {
  late final TextEditingController fromCtrl;
  late final TextEditingController endCtrl;

  bool isFirstPrice = false;
  bool isSecondProce = false;
  bool isThirdPrice = false;
  late String lang = "";

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

    final bloc = BlocProvider.of<ProductListBloc>(context);

    fromCtrl = TextEditingController(
      text: (bloc.state.data.filterData?.startPrice ?? 0) > 0
          ? bloc.state.data.filterData?.startPrice.toString()
          : '',
    );
    endCtrl = TextEditingController(
      text: (bloc.state.data.filterData?.endPrice ?? 0) > 0
          ? bloc.state.data.filterData?.endPrice.toString()
          : '',
    );
    getLang();
  }

  getLang() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      lang = prefs.getString('lang').toString();
    });
  }

  String? _validateField(String? txt) {
    final start = double.parse(fromCtrl.text.isNotEmpty ? fromCtrl.text : '0');
    final end = double.parse(endCtrl.text.isNotEmpty ? endCtrl.text : '0');

    if (start > end) {
      return '';
    }

    return null;
  }

  void _blocListener(BuildContext context, ProductListState state) {
    print(state);
    if (state is CleanFilterState) {
      fromCtrl.clear();
      endCtrl.clear();
    }
  }

  @override
  void dispose() {
    fromCtrl.dispose();
    endCtrl.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<ProductListBloc, ProductListState>(
      listener: _blocListener,
      builder: (context, state) {
        return Padding(
          padding: EdgeInsets.only(top: MyDimens.dimen12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                lang == 'th' || lang == ""
                    ? AppLocalizations.products.price_level
                    : AppLocalizations.products.price_level_en,
                style: MyFont.medium16,
              ),
              SizedBox(height: MyDimens.dimen8),
              _priceRange(),
              SizedBox(height: MyDimens.dimen8),
              _priceOptions(state.data.filterData),
            ],
          ),
        );
      },
    );
  }

  Widget _priceOptions(ProductListFilterData? filterData) {
    if (filterData != null) {
      isFirstPrice = filterData.priceChoice == FilterPriceChoice.first;
      isSecondProce = filterData.priceChoice == FilterPriceChoice.second;
      isThirdPrice = filterData.priceChoice == FilterPriceChoice.third;
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        GestureDetector(
          onTap: () {
            BlocProvider.of<ProductListBloc>(context).add(
              SelectPriceChoiceFilterEvent(FilterPriceChoice.first),
            );
          },
          child: Chip(
            side: isFirstPrice
                ? BorderSide(
                    color: MyColor.orange,
                  )
                : null,
            backgroundColor: (isFirstPrice ? MyColor.orange : Color(0xFF252B42))
                .withOpacity(0.1),
            label: Text(
              '0 - 10,000',
              style: MyFont.medium12.copyWith(
                color: isFirstPrice ? MyColor.orange : Color(0xFF121212),
              ),
            ),
          ),
        ),
        GestureDetector(
          onTap: () {
            BlocProvider.of<ProductListBloc>(context).add(
              SelectPriceChoiceFilterEvent(FilterPriceChoice.second),
            );
          },
          child: Chip(
            side: isSecondProce
                ? BorderSide(
                    color: MyColor.orange,
                  )
                : null,
            backgroundColor:
                (isSecondProce ? MyColor.orange : Color(0xFF252B42))
                    .withOpacity(0.1),
            label: Text(
              '10,001 - 50,000',
              style: MyFont.medium12.copyWith(
                color: isSecondProce ? MyColor.orange : Color(0xFF121212),
              ),
            ),
          ),
        ),
        GestureDetector(
          onTap: () {
            BlocProvider.of<ProductListBloc>(context).add(
              SelectPriceChoiceFilterEvent(FilterPriceChoice.third),
            );
          },
          child: Chip(
            side: isThirdPrice
                ? BorderSide(
                    color: MyColor.orange,
                  )
                : null,
            backgroundColor: (isThirdPrice ? MyColor.orange : Color(0xFF252B42))
                .withOpacity(0.1),
            label: Text(
              '50,000 ${AppLocalizations.products.or_more}',
              style: MyFont.medium12.copyWith(
                color: isThirdPrice ? MyColor.orange : Color(0xFF121212),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _priceRange() {
    return Form(
      key: widget.formkey,
      child: Row(
        children: [
          Expanded(
            child: IPMTextField(
              controller: fromCtrl,
              borderColor: Color(0xFFD9DBE1),
              hintText: AppLocalizations.products.from,
              hintStyle: MyFont.medium12.copyWith(
                color: Color(0xFF737B7D),
              ),
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp('[0-9]'))
              ],
              keyboardType: TextInputType.number,
              validator: _validateField,
              errorStyle: TextStyle(height: 0),
              onChanged: (_) {
                BlocProvider.of<ProductListBloc>(context).add(
                  InputPriceFromEvent(fromCtrl.text),
                );
              },
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(horizontal: MyDimens.dimen4),
            color: Color(0xFFCFD2D5),
            width: MyDimens.dimen32,
            height: 1,
          ),
          Expanded(
            child: IPMTextField(
              controller: endCtrl,
              borderColor: Color(0xFFD9DBE1),
              hintText: AppLocalizations.products.to,
              hintStyle: MyFont.medium12.copyWith(
                color: Color(0xFF737B7D),
              ),
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp('[0-9]'))
              ],
              keyboardType: TextInputType.number,
              validator: _validateField,
              errorStyle: TextStyle(height: 0),
              onChanged: (_) {
                BlocProvider.of<ProductListBloc>(context).add(
                  InputPriceEndEvent(endCtrl.text),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
