import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../text_field_custom_formatter.dart';

class CarNumberField extends StatefulWidget {
  final double? width;
  final double fontSize;
  final TextEditingController textEditingControllerRegion;
  final TextEditingController textEditingControllerNumber;
  final context;

  const CarNumberField(
      {this.width,
      this.fontSize = 24,
      required this.textEditingControllerRegion,
      required this.textEditingControllerNumber,
      this.context});

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

class _CarNumberFieldState extends State<CarNumberField> {
  double? width;
  String carNumber = "";
  double fontSize = 24;
  double scala = 1;
  int autoType = 100;
  var nodeNumber = FocusNode();
  var nodeRegion = FocusNode();
  var isRegionFilled = false;

  @override
  void initState() {
    super.initState();
    width = widget.width;

    fontSize = widget.fontSize;

    scala = fontSize / 24;

    widget.textEditingControllerRegion.addListener(() {
      var text = widget.textEditingControllerRegion.text.toUpperCase().trim();

      if (text.length == 2 && !isRegionFilled) {
        if (mounted)
          setState(() {
            isRegionFilled = true;
            autoType = getRegionType(text);
          });

        print("type id is $autoType");
        // if (nodeNumber.canRequestFocus)
        FocusScope.of(widget.context).requestFocus(nodeNumber);
      } else if (text.length < 2) {
        print("here length is less thsn 2");
        if (mounted)
          setState(() {
            isRegionFilled = false;
            autoType = 100;
          });
      }
      // else if (text.length > 7) {
      //   // if (mounted)
      //   print("get umber type");
      //   setState(() {
      //     autoType = getNumberType(text);
      //   });
      // }
    });

    widget.textEditingControllerNumber.addListener(() {
      var text = widget.textEditingControllerRegion.text.trim() +
          widget.textEditingControllerNumber.text.trim();

      if (mounted && text.length > 7)
        setState(() {
          autoType = getNumberType(text);
        });
    });
  }

  int getNumberType(String carNumber) {
    carNumber = carNumber.replaceAll(" ", "");
    final List<RegExp> regexs = [
      RegExp("^[0-9]{2}[A-Z]{1}[0-9]{3}[A-Z]{2}\$"),
      //01M123MM //white
      RegExp("^[0-9]{5}[A-Z]{3}\$"),
      //01123MMM //white
      RegExp("^[0-9]{5}[A-Z]{2}\$"),
      //01123MM //white
      RegExp("^UN[0-9]{4}\$"),
      //UN0123 //blue
      RegExp("^CMD[0-9]{4}\$"),
      //CMD1234 //green
      RegExp("^T[0-9]{6}\$"),
      //T012345 //green
      RegExp("^PAA[0-9]{3}\$"),
      //PAA123 //white
      RegExp("^D[0-9]{6}\$"),
      //D000000 //green
      RegExp("^[0-9]{2}M[0-9]{6}\$"),
      //01M123456 //green
      RegExp("^[0-9]{2}H[0-9]{6}\$"),
      //01H123456 //orange

      RegExp("^[0-9]{5}[A-Z]{2}E"),
      //01123MME //electro yur (hudud yashil)
      RegExp("^[0-9]{2}[A-Z]{1}[0-9]{3}[A-Z]{1}E"),
      //01M123ME //electro fiz (hudud yashil)
    ];
    for (int i = 0; i < regexs.length; i++)
      if (regexs[i].hasMatch(carNumber)) return i;
    return -1;
  }

  int getRegionType(String carNumber) {
    carNumber = carNumber.replaceAll(" ", "");
    print("region type checking  $carNumber");
    final List<RegExp> regexs = [
      RegExp("^[0-9]{2}"),
      //01M123MM //white  =>0
      RegExp("^[0-9]{2}"),
      //01123MMM //white =>1
      RegExp("^[0-9]{2}"),
      //01123MM //white  =>2
      RegExp("^UN"),
      //UN0123 //blue  =>3
      RegExp("^CM"),
      //CMD1234 //green  =>4
      RegExp("^T[0-9]{1}"),
      //T012345 //green  =>5
      RegExp("^PA"),
      //PAA123 //white  =>6
      RegExp("^D[0-9]{1}"),
      //D000000 //green  =>7
      RegExp("^[0-9]{2}"),
      //01M123456 //green  =>8
      RegExp("^[0-9]{2}"),
      //01H123456 //orange =>9

      // RegExp("^[0-9]{2}"),
      // //01123MME //electro yur (hudud yashil) =>10
      // RegExp("^[0-9]{2}"),
      //01M123ME //electro fiz (hudud yashil) =>11
    ];

    for (int i = 0; i < regexs.length; i++)
      if (regexs[i].hasMatch(carNumber)) {
        return i;
      }
    return -1;
  }

  Color getBackgroundColor(int type) {
    switch (type) {
      case 0:
      case 1:
      case 2:
        return Colors.white;
      case 3:
        return Colors.blueAccent;
      case 4:
      case 5:
      case 7:
      case 8:
        return Colors.green;

      case 9:
        return Colors.orange;

      // case :

      default:
        return Colors.white;
    }
  }

  Color getColor(int type) {
    switch (type) {
      case 0:
      case 1:
      case 2:
        return Colors.black87;
      case 3:
      case 4:
      case 5:
      case 7:

      case 8:
        return Colors.white;

      case 9:
        return Colors.black87;

      default:
        return Colors.black87;
    }
  }

  Widget _circle({
    Color color = Colors.black87,
    double radius = 4,
    double marginLeft = 0,
    double marginRight = 0,
  }) {
    return Container(
      width: radius * 0.5,
      height: radius * 0.5,
      margin: EdgeInsets.only(left: marginLeft, right: marginRight),
      decoration: BoxDecoration(color: color, shape: BoxShape.circle),
    );
  }

  TextStyle getStyle(int type) {
    return TextStyle(
      // height: 1.05,
      fontSize: fontSize * 1.3,
      fontWeight: FontWeight.w500,
      color: getColor(type),
      fontFamily: "FE Schrift3",
      letterSpacing: 2,
    );
  }

  var isError = false;
  _regionNumberField() {
    return TextField(
      controller: widget.textEditingControllerRegion,
      // key: ValueKey("region"),
      autofocus: true,
      textAlign: (autoType == 6 || autoType == 100)
          ? TextAlign.start
          : TextAlign.center,
      // showCursor: true,
      cursorColor: getColor(autoType),
      // cursorHeight: 24,
      decoration: InputDecoration(
        contentPadding: EdgeInsets.only(bottom: 2),
        border: InputBorder.none,
        counterText: "",
        hintText: "01",
        hintStyle: TextStyle(
          color: Colors.black26,
          fontFamily: "FE Schrift3",
        ),
      ),
      style: getStyle(autoType),
      focusNode: nodeRegion,
      inputFormatters: [
        UpperCaseTextFormatter(),
        CustomTextInputFormatter(fieldLength()),
        FilteringTextInputFormatter.allow(RegExp("[0-9a-zA-Z]")),
      ],
    );
  }

  int fieldLength() {
    int length = 9;
    switch (autoType) {
      case 3:
        length = 6;
        break;
      case 4:
      case 5:
      case 7:
        length = 7;
        break;
      case 6:
        length = 6;
        break;

      default:
        length = 2;
        break;
    }
    return length;
  }

  _carNumberField() {
    return TextFormField(
      controller: widget.textEditingControllerNumber,
      cursorColor: getColor(autoType),
      decoration: InputDecoration(
        contentPadding: const EdgeInsets.only(bottom: 2),
        border: InputBorder.none,
        counterText: "",
        hintText: "A 111 AA",
        hintStyle: TextStyle(color: Colors.black26),
      ),
      style: getStyle(autoType),
      // key: ValueKey("carNumber"),
      focusNode: nodeNumber,
      inputFormatters: [
        UpperCaseTextFormatter(),
        CustomTextInputFormatter(7),
        FilteringTextInputFormatter.allow(RegExp("[0-9a-zA-Z]")),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: scala * 23,
        width: width,
        padding: EdgeInsets.all(3 * scala),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          color: getBackgroundColor(autoType),
        ),
        child: ClipRRect(
            borderRadius: BorderRadius.circular(6 * scala),
            child: Container(
                padding: EdgeInsets.symmetric(
                  horizontal: (autoType != 6 && autoType != 7 && autoType != 8)
                      ? 4 * scala
                      : 0,
                ),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  border:
                      Border.all(color: getColor(autoType), width: 1 * scala),
                  color: getBackgroundColor(autoType),
                ),
                child: cases9_11(autoType, carNumber))));
  }

  cases9_11(int type, String number) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        autoType == 6
            ? Expanded(
                child: Row(
                  children: [
                    Stack(
                      children: [
                        if (autoType == 6)
                          Row(
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(12),
                                    bottomLeft: Radius.circular(12)),
                                child: Container(
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(12)),
                                  // padding: EdgeInsets.only(bottom: 2, left: 2),
                                  height: 48,
                                  child: Image.asset(
                                    "assets/png/falg.png",
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                              const SizedBox(
                                width: 8,
                              )
                            ],
                          ),
                        Positioned(
                          bottom: 0,
                          top: 0,
                          left: 2,
                          child: _circle(
                            radius: 4 * scala,
                            marginRight: 4 * scala,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              )
            : Align(
                alignment: Alignment.center,
                child: _circle(radius: 4 * scala, marginRight: 4 * scala)),
        SizedBox(
          width: width == null && autoType != 6 ? 0 : 6,
        ),
        Expanded(flex: flexSize(), child: _regionNumberField()),
        if (isNumberNeeded(type))
          Expanded(
            flex: 10,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Container(width: scala, color: getColor(type)),
                    SizedBox(
                      width: (autoType != 8 && autoType != 9) ? 14 : 16,
                    ),
                    SizedBox(
                      width: (autoType != 8 && autoType != 9) ? 124 : 150,
                      child: _carNumberField(),
                    ),
                  ],
                ),
                if (autoType != 8 && autoType != 9)
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        "assets/png/falg.png",
                        fit: BoxFit.fill,
                        height: 14,
                      ),
                      const SizedBox(height: 4),
                      Text("UZ",
                          style: getStyle(type).copyWith(
                            fontSize: 13 * scala,
                            color: Colors.blue,
                          )),
                      SizedBox(height: scala),
                    ],
                  ),
              ],
            ),
          ),
        Align(
            alignment: Alignment.center,
            child: _circle(radius: 4 * scala, marginLeft: 4 * scala)),
        if (!isNumberNeeded(type))
          const SizedBox(
            width: 4,
          ),
      ],
    );
  }

  bool isNumberNeeded(int autoType) {
    try {
      var needed = true;
      switch (autoType) {
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
          needed = false;
          break;

        default:
          needed = true;
          break;
      }
      return needed;
    } catch (e) {
      print("number need exception: $e");
      return true;
    }
  }

  int flexSize() {
    switch (autoType) {
      case 3:
      case 4:
      case 5:
      case 6:
        return 2;
      case 7:
        return 4;

      default:
        return 3;
    }
  }

  int getFlex() {
    switch (autoType) {
      case 3:
        return 4;
      case 4:
      case 5:
      case 7:
        return 5;
      case 6:
        return 2;

      default:
        return 8;
    }
  }
}
