import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:initial_folder/screens/coupon/success_radem_coupon_page.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/custom_navigator_bottom.dart';
import 'package:initial_folder/widgets/login_regist/default_button.dart';
import 'package:initial_folder/widgets/login_regist/loading_button.dart';
import 'package:tap_debouncer/tap_debouncer.dart';

class CouponPage extends StatefulWidget {
  CouponPage({Key? key}) : super(key: key);

  @override
  State<CouponPage> createState() => _CouponPageState();
}

class _CouponPageState extends State<CouponPage> {
  final kuponController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool isLoading = false;
  bool failed = false;
  String _iconPath = 'assets/icons/not_checklist.svg';
  String? errorMessage;

  handleRadeem() {
    setState(() {
      isLoading = true;
    });

    if (kuponController.text.isEmpty) {
      setState(() {
        isLoading = false;
        errorMessage = 'Kupon tidak boleh kosong';
      });
    } else if (kuponController.text.length <= 3) {
      setState(() {
        isLoading = false;
        errorMessage = 'Kupon tidak valid';
      });
    } else {
      setState(() {
        errorMessage = null;
      });
      Navigator.pushReplacement(
        context,
        CustomNavigatorBottom(
          child: SuccessRademCouponPage(
            coupon: kuponController.text,
          ),
        ),
      );
      setState(() {
        _iconPath = 'assets/icons/not_checklist.svg';
        isLoading = false;
      });
    }
  }

  void _validateInputs() {
    if (this._formKey.currentState!.validate()) {
      handleRadeem();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).viewInsets.bottom > 0
          ? MediaQuery.of(context).size.height / 1.6
          : MediaQuery.of(context).size.height / 2.4,
      child: SingleChildScrollView(
        child: Center(
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Padding(
                    padding: EdgeInsets.only(
                      right: getProportionateScreenWidth(5),
                      top: getProportionateScreenHeight(5),
                    ),
                    child: IconButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      icon: Icon(Icons.close),
                    ),
                  ),
                ],
              ),
              Text(
                'Tukarkan Voucher',
                style: thirdTextStyle.copyWith(
                    letterSpacing: 1,
                    fontWeight: semiBold,
                    fontSize: getProportionateScreenWidth(12)),
              ),
              SizedBox(height: getProportionateScreenHeight(5)),
              Text(
                'Masukkan kode voucher untuk klaim promo menarik dari\nVocasia',
                textAlign: TextAlign.center,
                style: thirdTextStyle.copyWith(
                    fontWeight: reguler,
                    fontSize: getProportionateScreenWidth(10)),
              ),
              SizedBox(height: getProportionateScreenHeight(20)),
              Padding(
                padding: EdgeInsets.symmetric(
                    horizontal: getProportionateScreenWidth(30)),
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Theme.of(context).brightness == Brightness.dark
                        ? seventeenColor
                        : secondaryColor.withOpacity(0.3),
                  ),
                  height: 40,
                  child: Form(
                    key: _formKey,
                    child: TextFormField(
                      autofocus: false,
                      controller: kuponController,
                      onChanged: (value) {
                        setState(() {
                          if (value.isEmpty) {
                            _iconPath = 'assets/images/not_checklist.svg';
                          } else if (value.length > 2) {
                            _iconPath = 'assets/icons/checklist.svg';
                          } else {
                            _iconPath = 'assets/icons/wrong.svg';
                          }
                        });
                      },
                      style: primaryTextStyle.copyWith(
                        fontSize: getProportionateScreenWidth(14),
                        letterSpacing: 0.5,
                      ),
                      cursorColor: secondaryColor,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: sevenColor),
                            borderRadius: BorderRadius.circular(10)),
                        contentPadding: EdgeInsets.only(
                          left: getProportionateScreenWidth(20),
                          bottom: getProportionateScreenHeight(8),
                          top: getProportionateScreenHeight(2),
                        ),
                        hintText: 'Masukkan Kode Voucher',
                        hintStyle: primaryTextStyle.copyWith(
                          fontSize: getProportionateScreenWidth(12),
                          color: secondaryColor,
                          letterSpacing: 0.5,
                        ),
                        suffixIcon: Transform.scale(
                          scale: 0.5,
                          child: Padding(
                            padding: EdgeInsets.only(
                                right: getProportionateScreenWidth(15)),
                            child: SvgPicture.asset(_iconPath),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(height: getProportionateScreenHeight(10)),
              if (errorMessage != null)
                Text(
                  errorMessage!,
                  style: TextStyle(color: Colors.red),
                ),
              Padding(
                padding: EdgeInsets.only(
                  left: getProportionateScreenWidth(16),
                  right: getProportionateScreenWidth(16),
                  top: getProportionateScreenHeight(10),
                ),
                child: isLoading
                    ? LoadingButton(
                        backgroundButtonColor: primaryColor,
                        textButtonColor: Colors.white,
                      )
                    : TapDebouncer(
                        cooldown: const Duration(milliseconds: 3000),
                        onTap: () async => await {_validateInputs()},
                        builder:
                            (BuildContext context, TapDebouncerFunc? onTap) {
                          return DefaultButton(
                            text: 'Tukarkan',
                            press: onTap,
                          );
                        },
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
