
import 'package:flutter/material.dart';

import '/models/group.dart';
import '/pages/buy_service.dart';
import '../../constants.dart';
import '../../generated/l10n.dart';
import '../../routes.dart';
import '../../utils/http_util.dart';
import '../../utils/utils.dart';

class CreateOnlineStore1 extends StatefulWidget {
  final int businessId;

  const CreateOnlineStore1(this.businessId, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return CreateOnlineStore1State();
  }

}

class CreateOnlineStore1State extends State<CreateOnlineStore1> {

  TextEditingController groupNumberController = TextEditingController();

  TextEditingController domainController = TextEditingController();

  bool canSubmit = false;

  List<dynamic> stores = [];
  Map<String, dynamic> service;
  dynamic selectedStore;

  Group group;

  String selectedDomain;
  List<dynamic> domainResult = [];

  @override
  Widget build(BuildContext context) {
    Column col = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [],
    );

    col.children.add(
      Container(
        padding: EdgeInsets.only(top: 20, left: 16, right: 16, bottom: 10,),
        child: Text(
          S.of(context).open_online_store,
          style: TextStyle(
            fontSize: 28,
          ),
        ),
      ),
    );
    col.children.add(
        Container(
          padding: EdgeInsets.only(top: 4, bottom: 4, left: 16.0, right: 16.0),
          child: Text(
            S.of(context)
                .select_a_store,
            style: TextStyle(
              color: Colors.black45,
            ),
          ),
        ),
    );
    col.children.add(
      Container(
        padding: EdgeInsets.only(top: 4, bottom: 4, left: 16.0, right: 16.0),
        child: DropdownButton<dynamic>(
          items: stores.map((e) => DropdownMenuItem<dynamic>(
            value: e,
            child: Text(e['name']),
          )).toList(),
          isExpanded: false,
          hint: Text(S.of(context).select_a_store),
          onChanged: (newValue) {
            print('newValue $newValue');
            setState(() {
              selectedStore = newValue;
            });
          },
          value: selectedStore,
        ),
      ),
    );
    col.children.add(
      Container(
        padding: EdgeInsets.only(
            left: 16.0, right: 16.0, top: 20, bottom: 20),
        child: Visibility(
          child: getSearchDomainWidget(),
          visible: selectedStore != null,
        ),
      ),
    );

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: (){
            Navigator.of(context).pop();
          },
        ),
        title: Text(S.of(context).open_online_store),
        backgroundColor: Theme.of(context).primaryColor,
      ),
      body: SingleChildScrollView(
        child: col,
      ),
    );
  }

  Widget getSearchDomainWidget() {
    if (selectedStore == null) {
      return SizedBox.shrink();
    }
    Column col = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [],
    );
    col.children.add(
      Container(
        padding: EdgeInsets.only(bottom: 4,),
        child: Text(selectedStore == null ? '' : selectedStore['name'],
          style: TextStyle(
            fontSize: 28,
          ),
        ),
      ),
    );
    Map<String, dynamic> existing_web_svc;
    if (selectedStore != null && (selectedStore['services'] as List).length > 0) {
      for (Map<String, dynamic>svc in (selectedStore['services'] as List)) {
        if (svc['code'] == Constants.WEB_MINISTORE_SERVICE) {
          existing_web_svc = svc;
          break;
        }
      }
    }
    if (existing_web_svc != null) {
      col.children.add(
        Container(
          padding: EdgeInsets.only(top: 8.0),
          child: Text(
            '${existing_web_svc['description']}',
          ),
        ),
      );
      col.children.add(
        Container(
          padding: EdgeInsets.only(top: 4.0),
          child: Text(
            S.of(context).expiration_date + ": "
                + Utils.utcDatetimeStringToLocalDatetimeString(context, existing_web_svc['expiration_date']),
          ),
        ),
      );
      col.children.add(
        Container(
          padding: EdgeInsets.only(top: 4.0),
          child: Text(
              S.of(context).store + ": " + '${existing_web_svc['store']['name']}'
          ),
        ),
      );
      col.children.add(
        Container(
          padding: EdgeInsets.only(top: 4.0),
          child: Text(
              S.of(context).domain_name + ": " + '${existing_web_svc['domain']}'
          ),
        ),
      );
      col.children.add(
        Container(
          padding: EdgeInsets.only(top: 10.0),
          child: ElevatedButton(
            child: Text(S.of(context).renew_service_now),
            onPressed: () {
              Navigator.pushReplacement(context, MaterialPageRoute(
                builder: (BuildContext context) =>
                    BuyService(group.id, Constants.WEB_MINISTORE_SERVICE,
                      domain: existing_web_svc['domain'],
                      sid: existing_web_svc['store']['id'],
                    ),
              ));
            },
          ),
        ),
      );
    } else {
      col.children.add(
        Container(
          padding: EdgeInsets.only(top: 8.0),
          child: Text(S.of(context).enter_desired_domain),
        ),
      );
      col.children.add(
          Container(
            padding: EdgeInsets.only(top: 0,),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                  child: TextFormField(
                    controller: domainController,
                    decoration: new InputDecoration(
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.black12,
                        ),
                      ),
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.blue,
                        ),
                      ),
                      labelText: S.of(context).domains_separated_comma,
                    ),
                    style: TextStyle(
                        fontSize: 18.0
                    ),
                    autofocus: true,
                    validator: (String? value) {
                      if (value.trim().isEmpty) {
                        return S.of(context).domains_separated_comma;
                      }
                      return null;
                    },
                    onChanged: (string) {
                      if (string.isNotEmpty) {
                        canSubmit = true;
                      } else {
                        canSubmit = false;
                      }
                      setState(() {});
                    },
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(left: 8.0),
                  child: ElevatedButton(
                    child: Text(
                      S.of(context).check_domain_name,
                    ),
                    onPressed: domainController.text.length > 0 ? checkDomainAvailability : null,
                  ),
                ),
              ],
            ),
          )
      );
      if (domainResult.length > 0) {
        for (dynamic dr in domainResult) {
          col.children.add(_getDomain(dr));
        }
      }
      if (selectedDomain != null && service != null) {
        col.children.add(
          Container(
            padding: EdgeInsets.only(top: 8.0),
            child: Text(
              service['description'],
            ),
          ),
        );
        col.children.add(
          Container(
            padding: EdgeInsets.only(top: 8.0),
            child: Text(
              service['options'][0]['name'],
            ),
          ),
        );
        col.children.add(
          Container(
            padding: EdgeInsets.only(top: 8.0),
            child: Text(
              '\$${service['options'][0]['price']}',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.orange,
              ),
            ),
          ),
        );
        col.children.add(
          Container(
            padding: EdgeInsets.only(top: 10.0),
            child: ElevatedButton(
              child: Text(
                S.of(context).place_order_now,
              ),
              onPressed: () {
                Navigator.pushReplacement(context, MaterialPageRoute(
                  builder: (BuildContext context) =>
                      BuyService(group.id, Constants.WEB_MINISTORE_SERVICE,
                        domain: selectedDomain,
                        sid: selectedStore['id'],
                      ),
                ));
              },
            ),
          ),
        );
      }
    }
    return Container(
      padding: EdgeInsets.only(bottom: 4,),
      child: col,
    );
  }

  @override
  void initState() {
    super.initState();
    HttpUtil.httpGet(
        'v1/get-contact-stores',
        queryParameters: {
          'service': Constants.WEB_MINISTORE_SERVICE
        }
    ).then((value) {
      setState(() {
        stores = value['stores'];
        service = value['service'];
        group = Group.fromJson(value['group']);
        print('stores: ${value}');
      });
    }).onError((error, stackTrace) {
      Utils.showMessageDialog(context, error, onOk: () {
        Routes.router.navigateTo(context, '/');
      });
    });
  }

  Future<void> checkDomainAvailability() async {
    Utils.showLoadingDialog(context);
    selectedDomain = null;
    domainResult = [];
    setState(() {});
    HttpUtil.httpGet(
      'v1/check-domain-availability',
      queryParameters: {
        'domain': domainController.text,
      },
    ).then((value) {
      Routes.router.pop(context);
      print('value: $value');
      if (value['status'] == 'OK') {
        domainResult = (value['domain_check_result'] as List);
        setState(() {});
      } else if (value['status'] == 'ERROR') {
        String errors = '';
        for (int i = 0; i < (value['errors'] as List).length; i++) {
          errors += value['errors'][i] + '\n';
        }
        Utils.showMessageDialog(context, errors);
      }
    }).onError((error, stackTrace) {
      Routes.router.pop(context);
      Utils.showMessageDialog(context, error);
    });
  }

  Widget _getDomain(dynamic d) {
    if ((d['available'] as bool)) {
      return Container(
        child: ListTile(
          title: Text(
            d['domain'],
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
          leading: Radio(
            value: d['domain'],
            groupValue: selectedDomain,
            onChanged: (val) {
              setState(() {
                selectedDomain = val;
              });
            },
          ),
        ),
      );
    } else {
      return Container(
        padding: EdgeInsets.only(top: 1.0),
        child: ListTile(
          title: Text(
            d['domain'],
            style: TextStyle(
              color: Colors.black45,
            ),
          ),
          leading: Icon(Icons.clear, color: Colors.red,),
        ),
      );
    }
  }
}