import 'dart:html';
import 'dart:js' as js;
import 'package:flutter/material.dart';
import 'package:grpc/grpc_web.dart';
import 'package:softplayer_dart_proto/main.dart';
import 'package:softplayer_web/api/grpc/creds.dart';
import 'package:softplayer_web/api/grpc/environments.dart';
import 'package:softplayer_web/helpers/providers/common.dart' as helper;

class CreateEnvForm extends StatefulWidget {
  CreateEnvForm(GrpcWebClientChannel channel, {super.key})
      : environmentsGrpc = EnvironmentsGrpc(channel);
  final EnvironmentsGrpc environmentsGrpc;

  @override
  State<StatefulWidget> createState() => _CreateEnvFormState();
}

class _CreateEnvFormState extends State<CreateEnvForm> {
  final _formKey = GlobalKey<FormState>();
  final String defaultProvider = Provider.PROVIDER_HETZNER.toString();
  late helper.Provider provider =
      helper.ProviderHelper().getProvider(defaultProvider);
  late String defaultLocation = provider.defaultLocation();
  final nameCtl = TextEditingController();
  final descriptionCtl = TextEditingController();
  late String? serverLocation = defaultLocation;
  late String? serverType = ServerType.SERVER_TYPE_REGULAR.toString();

  void createEnvironment() {
    // Validate returns true if the form is valid, or false otherwise.
    if (_formKey.currentState!.validate()) {
      final name = nameCtl.text;
      final description = descriptionCtl.text;
      widget.environmentsGrpc
          .create(
              EnvironmentLocalData(
                  serverType: serverType!,
                  serverLocation: serverLocation!,
                  provider: defaultProvider,
                  name: name,
                  description: description),
              SoftplayerCredsHelpers().fromLocalStorage())
          .then((rs) {
        Navigator.pop(context);
      }).catchError((e) {
        GrpcError error = e;
        String msg;
        if (error.message != null) {
          msg = error.message!;
        } else {
          msg = error.toString();
        }
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(msg),
          backgroundColor: Colors.red,
          showCloseIcon: true,
          behavior: SnackBarBehavior.floating,
        ));
      });
    }
  }

  String defaultServerType = "Regular";
  Widget createEnvForm() => SingleChildScrollView(
      child: SizedBox(
          width: 420,
          child: Form(
              key: _formKey,
              child: Center(
                  child: Column(children: [
                TextFormField(
                  autofocus: true,
                  controller: nameCtl,
                  decoration: const InputDecoration(
                    hintText: "Enter the environment name",
                    icon: Icon(Icons.computer),
                    label: Text("Name"),
                  ),
                  cursorWidth: 1,
                  cursorHeight: 18,
                  cursorRadius: const Radius.circular(10),
                ),
                TextFormField(
                  autofocus: false,
                  controller: descriptionCtl,
                  decoration: const InputDecoration(
                    hintText: "Enter the environment description",
                    icon: Icon(Icons.description),
                    label: Text("Description"),
                  ),
                  maxLength: 360,
                  cursorWidth: 1,
                  cursorHeight: 18,
                  cursorRadius: const Radius.circular(10),
                ),
                DropdownButtonFormField(
                  decoration: const InputDecoration(
                    hintText: "Enter the environment description",
                    icon: Icon(Icons.computer),
                    label: Text("Type of the server"),
                  ),
                  value: ServerType.SERVER_TYPE_REGULAR.toString(),
                  isDense: true,
                  items: ServerType.values
                      .where((element) =>
                          element != ServerType.SERVER_TYPE_CUSTOM &&
                          element != ServerType.SERVER_TYPE_UNSPECIFIED)
                      .map((serverType) {
                    return DropdownMenuItem(
                      value: serverType.toString(),
                      child: Text(helper.ProviderHelper()
                          .getServerType(serverType.toString())),
                    );
                  }).toList(),
                  onChanged: (value) => setState(() {
                    serverType = value;
                  }),
                ),
                TextButton(
                  onPressed: () => js.context.callMethod(
                      'open', ['https://stackoverflow.com/questions/ask']),
                  child: Text("Read more about environment types here"),
                ),
                DropdownButtonFormField(
                  decoration: const InputDecoration(
                    hintText: "Enter the environment location",
                    icon: Icon(Icons.location_on),
                    label: Text("Location of the server"),
                  ),
                  value: defaultLocation,
                  isDense: true,
                  items: Location.values
                      .where((element) => element
                          .toString()
                          .contains(provider.getProviderName().toUpperCase()))
                      .map((serverType) {
                    return DropdownMenuItem(
                      value: serverType.toString(),
                      child: Text(
                          provider.getServerLocation(serverType.toString())),
                    );
                  }).toList(),
                  onChanged: (value) => setState(() {
                    serverLocation = value;
                  }),
                ),
              ])))));
  List<Widget> createEnvActions() => [
        TextButton(
          onPressed: createEnvironment,
          child: const Text('OK'),
        ),
      ];

  @override
  Widget build(BuildContext context) => AlertDialog(
        title: const Text("Create a new environment"),
        content: createEnvForm(),
        actions: createEnvActions(),
      );
}
