import 'dart:io';

import 'package:custom_radio_grouped_button/custom_radio_grouped_button.dart';
import 'package:daciapackete/daciabefehle.dart';
import 'package:daciapackete/globals.dart' as globals;
import 'package:daciapackete/sequenzen.dart';
import "package:daciapackete/speicherdaten.dart";
import 'package:flutter/material.dart';
import 'package:link_text/link_text.dart';
import 'package:springcontrol/showalertdialog.dart';
import "package:springcontrol/ladescreen_service.dart";
import "main.dart";
import "webseitentest.dart";

var items = [
  'AT',
  'DE',
  'SE',
  'GB',
  'IT',
];
//var newValue;



class FormDaciaAnmeldedaten extends StatefulWidget {
  const FormDaciaAnmeldedaten({super.key});

  @override
  State<FormDaciaAnmeldedaten> createState() => _FormDaciaAnmeldedatenState();
}

class _FormDaciaAnmeldedatenState extends State<FormDaciaAnmeldedaten> {
  var daciaAnmeldedaten = globals.daciaAnmeldedaten.copy();
  bool _obscureText = true;
  var abfrageEinValue = globals.config.daciaAbfrageEin;
  datenSpeichern() async {
    //LadescreenService.startLadescreen(context);
    //daciaAnmeldedaten.zyklus = zyklus;
    globals.daciaAnmeldedaten = daciaAnmeldedaten;
    await speicherDaten("daciaAnmeldedaten");
   // LadescreenService.stopLadescreen(context);
  }

  final _formKey = GlobalKey<FormState>();

  //var zyklus = globals.daciaAnmeldedaten.zyklus;

  titelText() {
    if (abfrageEinValue == true) {
      return "Abfrage ist ein";
    } else {
      return "Abfrage ist aus";
    }
  }
  @override
  //final _formKey = GlobalKey<FormState>();
  Widget build(BuildContext context) {
    return PopScope(
        onPopInvokedWithResult: (didPop, result) async {
          await datenSpeichern();
          //dispose();
        },
        child: Scaffold(
          //return Scaffold(
          appBar: AppBar(
            title: Text(titelText()),
            //##################################
            actions: [
              Switch(
                activeColor: Colors.green,
                activeTrackColor: Colors.grey.shade400,
                inactiveThumbColor: Colors.red.shade600,
                inactiveTrackColor: Colors.grey.shade400,

                value: abfrageEinValue,
                onChanged: (value) async {
                  if (abfrageEinValue == true) {
                    globals.config.daciaAbfrageEin = false;
                    abfrageEinValue = false;
                    await speicherDaten("config");
                  } else {
                      abfrageEinValue = true;
                      globals.config.daciaAbfrageEin = true;
                      await speicherDaten("config");
                    }
                     setState(() {});
                  },

                //},
              ),
            ],
            //####################################


            centerTitle: true,
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          ),
          body: Center(
            child: SingleChildScrollView(
              child: Form(
                key: _formKey,
                child: Column(
                  //mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(8),
                        child: Column(
                          children: <Widget>[
                            ListTile(
                              title: Text(context.sp.daciaAnmeldedaten),
                            ),
                            TextFormField(
                              autocorrect: false,
                              keyboardType: TextInputType.emailAddress,
                              decoration:  InputDecoration(
                                  labelText: context.sp.loginName),
                              initialValue: ("${daciaAnmeldedaten.daciaName}"),
                              validator: (dn) {
                                if (dn!.isEmpty) {
                                  return context.sp.bitteEinenBenutzernamenEingeben;
                                }
                                return null;
                              },
                              onChanged: (dn) => setState(
                                  () => daciaAnmeldedaten.daciaName = dn),
                            ),
                            TextFormField(
                              obscureText: _obscureText,
                              autocorrect: false,
                              keyboardType: TextInputType.text,
                              initialValue:
                                  ("${daciaAnmeldedaten.daciaPasswort}"),
                              validator: (dp) {
                                if (dp!.isEmpty) {
                                  return context.sp.bitteEinPasswortEingeben;
                                }
                                return null;
                              },
                              decoration: InputDecoration(
                                labelText: context.sp.passwort,
                                suffixIcon: IconButton(
                                  icon: Icon(
                                    _obscureText
                                        ? Icons.visibility
                                        : Icons.visibility_off,
                                  ),
                                  onPressed: () {
                                    setState(() {
                                      _obscureText = !_obscureText;
                                    });
                                  },
                                ),
                              ),
                              onChanged: (dp) => setState(
                                  () => daciaAnmeldedaten.daciaPasswort = dp),
                            ),
                            TextFormField(
                              autocorrect: false,
                              keyboardType: TextInputType.text,
                              decoration:
                                  const InputDecoration(labelText: "VIN"),
                              initialValue: ("${daciaAnmeldedaten.vin}"),
                              validator: (vin) {
                                if (vin!.isEmpty) {
                                  return context.sp.bitteVINEingeben;
                                }
                                return null;
                              },
                              onChanged: (vin) =>
                                  setState(() => daciaAnmeldedaten.vin = vin),
                            ),
                            Row(
                              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(context.sp.land),
                                DropdownButton(
                                  // Initial Value
                                  value: daciaAnmeldedaten.country,
                                  // Down Arrow Icon
                                  icon: const Icon(Icons.keyboard_arrow_down),

                                  // Array list of items
                                  items: items.map((String items) {
                                    return DropdownMenuItem(
                                      value: items,
                                      child: Text(items),
                                    );
                                  }).toList(),
                                  // After selecting the desired option,it will
                                  // change button value to selected value
                                  onChanged: (newValue) {
                                    setState(() {
                                      daciaAnmeldedaten.country = newValue;
                                    });
                                  },
                                ),
                              ],
                            ),

/*
                        TextFormField(
                          autocorrect: false,
                          keyboardType: TextInputType.text,
                          decoration: const InputDecoration(
                              labelText: "Land (DE für Deutschland)"),
                          initialValue: ("${daciaAnmeldedaten.country}"),
                          validator: (country) {
                            if (country!.isEmpty) {
                              return 'Bitte Land eingeben';
                            }
                            return null;
                          },
                          onChanged: (country) => setState(
                              () => daciaAnmeldedaten.country = country),
                        ),

  */

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                            ElevatedButton(
                              child: Text(context.sp.testAnmeldung),
                              onPressed: () async {
                                /*
                            print("Anmeldedaten");
                            print (daciaAnmeldedaten.daciaName);
                            print(daciaAnmeldedaten.daciaPasswort);
                            print(daciaAnmeldedaten.country);
                            print(daciaAnmeldedaten.vin);

                            */
                                LadescreenService.startLadescreen(context);
                                var globalDaciaAnmeldedaten =
                                    globals.daciaAnmeldedaten;
                                globals.daciaAnmeldedaten = daciaAnmeldedaten;
                                var ergebnis = await DaciaBefehle().anmeldung();
                                globals.daciaAnmeldedaten =
                                    globalDaciaAnmeldedaten;
                                speicherDaten("daciaAnmeldedaten");
                                LadescreenService.stopLadescreen(context);
                                switch (ergebnis) {
                                  case "gigya1 Fehler":
                                    showDialog<String>(
                                      context: context,
                                      builder: (BuildContext context) =>
                                          AlertDialog(
                                        title: Text(context.sp.anmeldeProbleme),
                                        content: Text(
                                            context.sp.gigya1AnmeldeFehler),
                                        actions: <Widget>[
                                          TextButton(
                                            onPressed: () =>
                                                Navigator.pop(context, context.sp.ok),
                                            child: Text(context.sp.ok),
                                          ),
                                        ],
                                      ),
                                    );
                                  case "gigya2 Fehler":
                                    showDialog<String>(
                                      context: context,
                                      builder: (BuildContext context) =>
                                          AlertDialog(
                                        title: Text(context.sp.anmeldeProbleme),
                                        content: Text(
                                            context.sp.gigya2AnmeldungFehlerGigya1Anmeldungok),
                                        actions: <Widget>[
                                          TextButton(
                                            onPressed: () =>
                                                Navigator.pop(context, context.sp.ok),
                                            child: Text(context.sp.ok),
                                          ),
                                        ],
                                      ),
                                    );

                                  case "kamereon Fehler":
                                    showDialog<String>(
                                      context: context,
                                      builder: (BuildContext context) =>
                                          AlertDialog(
                                        title: Text(context.sp.anmeldeProbleme),
                                        content:  Text(
                                            context.sp.kamereonAnmeldungFehlerGigya1UndGigya2AnmeldungOk),
                                        actions: <Widget>[
                                          TextButton(
                                            onPressed: () =>
                                                Navigator.pop(context, context.sp.ok),
                                            child: Text(context.sp.ok),
                                          ),
                                        ],
                                      ),
                                    );
                                  case "ok":
                                    showDialog<String>(
                                      context: context,
                                      builder: (BuildContext context) =>
                                          AlertDialog(
                                        title: Text(context.sp.daciaAnmeldung),
                                        content: Text(context.sp.allesOk),
                                        actions: <Widget>[
                                          TextButton(
                                            onPressed: () =>
                                                Navigator.pop(context, context.sp.ok),
                                            child:  Text(context.sp.ok),
                                          ),
                                        ],
                                      ),
                                    );
                                }
                              },
                             // child: const Text("Test Anmeldung"),
                            ),
/*
                            ElevatedButton(
                                child: Text(context.sp.changeToken),

                                onPressed: () async {
                                  LadescreenService.startLadescreen(context);
                                  bool erg =await changeTokenClient();
                                  LadescreenService.stopLadescreen(context);
                                  String text ="";
                                    if (erg)  {
                                      if (globals.configProxyServer.proxyBenutzen == false) {
                                        text = context.sp.ausgefuehrt;
                                      } else {
                                        text = context.sp.anProxyGesendet;
                                      }
                                    } else {
                                      text = context.sp.problemeBeimProxyReset;
                                    }
                                  showAlertDialog(
                                      context, context.sp.changeToken, text, context.sp.ok);

                                }
                            ),
                  */
                            ],
              ),

              //########################################
                            Card(
                              child: Padding(
                                padding: const EdgeInsets.all(8),
                                child: Column(
                                  children: <Widget>[
                                    ListTile(
                                      title: Text("Anmeldeserver"),
                                    ),
                            CustomRadioButton(
                              buttonTextStyle: const ButtonTextStyle(
                                selectedColor: Colors.white,
                                unSelectedColor: Colors.black,
                                textStyle: TextStyle(
                                  fontSize: 15,
                                ),
                              ),
                              autoWidth: true,
                              enableButtonWrap: true,
                              wrapAlignment: WrapAlignment.center,
                              unSelectedColor: Theme.of(context).canvasColor,
                              buttonLables: const [
                                "Auto",
                                "Server 1",
                                "Server 2",
                              ],
                              buttonValues: const [
                                0,
                                1,
                                2,
                              ],
                              radioButtonValue: (values) {
                                daciaAnmeldedaten.loginServerAuswahl = values;
                              },
                              defaultSelected: daciaAnmeldedaten.loginServerAuswahl,
                              horizontal: false,
                              // width: 120,
                              // hight: 50,
                              selectedColor:
                              Theme.of(context).colorScheme.secondary,
                              padding: 5,
                              enableShape: true,
                            ),
                            const SizedBox(
                              height: 10,
                            ),
],
                                ),
                              ),
                            ),
                            //##################################


                            Card(
                              child: Padding(
                                padding: const EdgeInsets.all(8),
                                child: Column(
                                  children: <Widget>[
                                    ListTile(
                                      title: Text("Tokenerneuerung"),
                                    ),
                                    CustomRadioButton(
                                      buttonTextStyle: const ButtonTextStyle(
                                        selectedColor: Colors.white,
                                        unSelectedColor: Colors.black,
                                        textStyle: TextStyle(
                                          fontSize: 15,
                                        ),
                                      ),
                                      autoWidth: true,
                                      enableButtonWrap: true,
                                      wrapAlignment: WrapAlignment.center,
                                      unSelectedColor: Theme.of(context).canvasColor,
                                      buttonLables: const [
                                        //"Auto",
                                        "Alle 12 Std.",
                                        "Nach Zyklus",
                                        "Nach Aktion"
                                      ],
                                      buttonValues: const [
                                       // 0,
                                        1,
                                        2,
                                        3,
                                      ],
                                      radioButtonValue: (values) {
                                        daciaAnmeldedaten.tokenModeAuswahl = values;
                                      },
                                      defaultSelected: daciaAnmeldedaten.tokenModeAuswahl,
                                      horizontal: false,
                                      // width: 120,
                                      // hight: 50,
                                      selectedColor:
                                      Theme.of(context).colorScheme.secondary,
                                      padding: 5,
                                      enableShape: true,
                                    ),
                                    const SizedBox(
                                      height: 10,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            //##################################

/*

              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  ElevatedButton(
                      child: Text("Test\nWebseite"),

                      onPressed: () async {
                        await checkDaciaLogin(context);
                        /*
                        if (success) {
                          showAlertDialog(
                              context, "Webseitentest", "Anmeldung ok", "ok");
                        }
                        else
                        {
                          showAlertDialog(  context, "Webseitentest", "Anmeldung nicht ok", "ok");
                        }
*/

                      }
                  ),
                  ]
              ),
*/


                          ],
                        ),
                      ),
                    ),


/*
                    if (Platform.isAndroid)
                      Card(
                          child: Padding(
                              padding: const EdgeInsets.all(8),
                              child: Column(children: <Widget>[
                                ListTile(
                                  title: Text(context.sp.androidEinstellungen),
                                ),
                                Text(
                                    context.sp.achtungBitteDieEnergieeinstellungenFuerDieAppBeachtenSiehe),
                                LinkText(
                                    "https://www.springforum.de/threads/neue-lade-app-fuer-den-spring.4066/post-110426"),
                              ]))),
                    */
                  ],
                ),
              ),
            ),
          ),
        ));
  }
}
