import 'dart:io';
import 'package:country_picker/country_picker.dart';
import 'package:echo_app/models/user.dart';
import 'package:echo_app/widgets/general_text_form_field.widget.dart';
import 'package:echo_app/widgets/no_data.widget.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../theme/variables.dart';

// ignore: must_be_immutable
class Main extends StatefulWidget {
  final bool isCustomerNameMandatory;
  final bool isPhoneNoMandatory;
  final bool isTradeLicenseMandatory;
  final UserModel signUpUser;
  Country countryselected = Country(phoneCode: '+962', countryCode: 'JO', e164Sc: -1, geographic: false, level: 1, name: 'Jordan', example: '+96278891234', displayName: 'Jordan', displayNameNoCountryCode: 'Jordan', e164Key: 'e164Key');


  Main(this.signUpUser, this.isCustomerNameMandatory, this.isPhoneNoMandatory,
      this.isTradeLicenseMandatory);

  @override
  State<Main> createState() => _MainState();
}

class _MainState extends State<Main> {
  var isFullBorder = true;
  var constPadding = EdgeInsets.symmetric(vertical: 5);
  final TextEditingController customerNameController =
      new TextEditingController();
  final TextEditingController phoneController = new TextEditingController();
  final TextEditingController usernameController = new TextEditingController();
  final TextEditingController passController = new TextEditingController();
  final TextEditingController retypePassController =
      new TextEditingController();
  final TextEditingController tradeController = new TextEditingController();
  final TextEditingController identityController = new TextEditingController();

  final _customerName = FocusNode();
  final _phoneNumber = FocusNode();
  final _username = FocusNode();
  final _password = FocusNode();
  final _retypePassword = FocusNode();
  final _tradeLicense = FocusNode();
  String _errorMsg = '';

  @override
  initState() {
    super.initState();
    print('initState');
  }

  @override
  didUpdateWidget(Main oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  addingIdentificationFiles() async {
    FilePickerResult? result =
        await FilePicker.platform.pickFiles(allowMultiple: true);
    if (result != null) {
      setState(() {
        if (result.files.length > 0 && result.paths.length > 0) {
          widget.signUpUser.files
              .addAll(result.paths.map((path) => File(path!)).toList());

          widget.signUpUser.filesName
              .addAll(result.files.map((file) => file.name).toList());

          widget.signUpUser.filesPath
              .addAll(result.files.map((file) => file.path!).toList());
        }
      });
    } else {}
  }
  String getFlagIcon(String countryCode) {
    return 'icons/flags/png/${countryCode.toLowerCase()}.png';
  }
  deleteIdentificationFiles(index) {
    setState(() {
      var list = widget.signUpUser.files;
      var names = widget.signUpUser.filesName;

      list.removeAt(index);
      names.removeAt(index);

      widget.signUpUser.files = list;
      widget.signUpUser.filesName = names;
    });
  }

  @override
  Widget build(BuildContext context) {
    customerNameController.text = widget.signUpUser.customerName;
    phoneController.text = widget.signUpUser.phoneNumber;
    usernameController.text = widget.signUpUser.userName;
    passController.text = widget.signUpUser.password;
    retypePassController.text = widget.signUpUser.retypePassword;
    tradeController.text = widget.signUpUser.tradeLicenseNumber;
    if (widget.signUpUser.passwordsNotMatch) {
      _errorMsg = 'Password-mismatch';
    } else {
      _errorMsg = '';
    }

    _onSubmitCustomerName() {
      FocusScope.of(context).requestFocus(_phoneNumber);
    }

    _onCustomerNameValueChanged(value) {
      widget.signUpUser.customerName = value;
      if (value == '' && widget.isCustomerNameMandatory) {
        widget.signUpUser.invalidCustomerName = true;
      } else {
        widget.signUpUser.invalidCustomerName = false;
      }
    }

    _onSubmitPhoneNumber() {
      FocusScope.of(context).requestFocus(_username);
    }

    _onPhoneValueChanged(value) {
      widget.signUpUser.phoneNumber = value;
      if (value == '' && widget.isPhoneNoMandatory) {
        widget.signUpUser.invalidPhoneNumber = true;
      } else {
        widget.signUpUser.invalidPhoneNumber = false;
      }
    }

    _onSubmitUsername() {
      // FocusScope.of(context).requestFocus(_password);
    }

    _onUsernameChanged(value) {
      widget.signUpUser.userName = value;
      if (value == '') {
        widget.signUpUser.invalidUsername = true;
      } else {
        widget.signUpUser.invalidUsername = false;
      }
    }

    _onSubmitPassword() {
      FocusScope.of(context).requestFocus(_retypePassword);
      // setState(() {
      //   _errorMsg = '';
      // });
    }

    _onPasswordChanged(value) {
      widget.signUpUser.password = value;
      if (value == '') {
        widget.signUpUser.invalidPassword = true;
      } else {
        widget.signUpUser.invalidPassword = false;
      }
      widget.signUpUser.passwordsNotMatch = false;
      // setState(() {
      //   _errorMsg = '';
      // });
    }

    _onSubmitRetypePassword() {
      FocusScope.of(context).requestFocus(_tradeLicense);
      // setState(() {
      //   _errorMsg = '';
      // });
    }

    _onRetypePasswordChanged(value) {
      widget.signUpUser.retypePassword = value;
      if (value == '') {
        widget.signUpUser.invalidRetypePassword = true;
      } else {
        widget.signUpUser.invalidRetypePassword = false;
      }
      widget.signUpUser.passwordsNotMatch = false;
      // setState(() {
      //   _errorMsg = '';
      // });
    }

    _onSubmitTradeLicense() {
      // FocusScope.of(context).requestFocus(_address);
    }

    _onTradeLicenseChanged(value) {
      widget.signUpUser.tradeLicenseNumber = value;
      if (value == '' && widget.isTradeLicenseMandatory) {
        widget.signUpUser.invalidTrade = true;
      } else {
        widget.signUpUser.invalidTrade = false;
      }
    }

    // widget.signUpUser.filesName.add('dcascf');
    // widget.signUpUser.filesName.add('yyyy');
    // widget.signUpUser.filesName.add('jjjj');

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("customer-name".tr),
              GeneralTextFormFieldWidget(
                  "enter-name",
                  customerNameController,
                  widget.isCustomerNameMandatory,
                  '',
                  true,
                  false,
                  null,
                  _onSubmitCustomerName,
                  _onCustomerNameValueChanged,
                  constPadding,
                  _customerName,
                  1,
                  isFullBorder,
                  widget.signUpUser.invalidCustomerName,
                  false,
                  15,
                  TextInputType.text),
            ],
          ),
          SizedBox(height: 10,),
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("address-email".tr),
              GeneralTextFormFieldWidget(
                  "enter-email",
                  usernameController,
                  true,
                  '',
                  true,
                  false,
                  null,
                  _onSubmitUsername,
                  _onUsernameChanged,
                  constPadding,
                  _username,
                  1,
                  isFullBorder,
                  widget.signUpUser.invalidUsername,
                  false,
                  15,
                  TextInputType.text),
            ],
          ),
          SizedBox(height: 10,),

          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("phone".tr),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: InkWell(
                      onTap: (){
                        showCountryPicker(
                          context: context,
                          showPhoneCode: true, // optional. Shows phone code before the country name.
                          onSelect: (Country country) {
                            print('Select country: ${country.displayName}');
                            this.widget.countryselected = country;
                            setState(() {

                            });
                          },
                        );
                      },
                      child: Row(
                        children: [
                          Image.asset(
                            getFlagIcon(this.widget.countryselected.countryCode), // Replace 'us' with any valid country code
                            package: 'country_icons',
                            height: 40,width: 40,
                          ),
                          SizedBox(width: 5,),
                          Icon(Icons.keyboard_arrow_down_rounded)
                        ],
                      ),),
                  ),
                  Expanded(
                    flex: 3,
                    child: GeneralTextFormFieldWidget(
                        "Xxxxxxxxxxxx",
                        phoneController,
                        widget.isPhoneNoMandatory,
                        '',
                        true,
                        false,
                        null,
                        _onSubmitPhoneNumber,
                        _onPhoneValueChanged,
                        constPadding,
                        _phoneNumber,
                        1,
                        isFullBorder,
                        widget.signUpUser.invalidPhoneNumber,
                        false,
                        15,
                        TextInputType.phone),
                  ),
                ],
              ),
            ],
          ),
          // GeneralTextFormFieldWidget(
          //     "password",
          //     passController,
          //     true,
          //     '',
          //     true,
          //     true,
          //     null,
          //     _onSubmitPassword,
          //     _onPasswordChanged,
          //     constPadding,
          //     _password,
          //     1,
          //     isFullBorder,
          //     widget.signUpUser.invalidPassword,
          //     false,
          //     15,
          //     TextInputType.text),
          // GeneralTextFormFieldWidget(
          //     "Re-type-password",
          //     retypePassController,
          //     true,
          //     '',
          //     true,
          //     true,
          //     null,
          //     _onSubmitRetypePassword,
          //     _onRetypePasswordChanged,
          //     constPadding,
          //     _retypePassword,
          //     1,
          //     isFullBorder,
          //     widget.signUpUser.invalidRetypePassword,
          //     false,
          //     15,
          //     TextInputType.text),
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("Trade-License-Number".tr),
              GeneralTextFormFieldWidget(
                  "Trade-License-Number",
                  tradeController,
                  widget.isTradeLicenseMandatory,
                  '',
                  true,
                  false,
                  null,
                  _onSubmitTradeLicense,
                  _onTradeLicenseChanged,
                  constPadding,
                  _tradeLicense,
                  1,
                  isFullBorder,
                  widget.signUpUser.invalidTrade,
                  false,
                  15,
                  TextInputType.text),
            ],
          ),
          if (_errorMsg != '')
            Text(
              _errorMsg.tr,
              style: TextStyle(color: Colors.red),
            ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  children: [
                    Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          IconButton(
                            icon: Image.asset(
                                'assets/imgs/more_icons/document-upload.png',
                                color: Variables.color_primary,
                                height: 25,
                                width: 25), onPressed: () { addingIdentificationFiles(); },
                          ),
                        ])
                  ],
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView.builder(
                //physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (ctx, index) {
                  return widget.signUpUser.filesName.length > 0
                      ? Container(
                          // margin: EdgeInsets.only(bottom: 5),
                          child: Card(
                          elevation: 1,
                          child: ListTile(
                            title: Row(children: <Widget>[
                              Container(
                                child: Row(
                                  children: <Widget>[
                                    Icon(
                                      Icons.file_copy,
                                      color: Variables.color_primary,
                                    ),
                                  ],
                                ),
                              ),
                              Container(
                                width: 200,
                                child: Text(
                                  '   ' + widget.signUpUser.filesName[index].tr,
                                  style: TextStyle(
                                      color: Variables.color_primary,
                                      fontSize: 13),
                                ),
                              ),
                            ]),
                            trailing: IconButton(
                                icon: Icon(Icons.close, color: Colors.red),
                                onPressed: () {
                                  deleteIdentificationFiles(index);
                                }),
                          ),
                        ))
                      : NoDataWidget();
                },
                itemCount: widget.signUpUser.filesName.length),
          ),
        ],
      ),
    );
  }
}
