// ignore_for_file: non_constant_identifier_names
import 'package:fforte/db_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:latlong2/latlong.dart';
import 'package:shared_preferences/shared_preferences.dart';

// * Collection of All widgets displayed in the add_cam section

// ! Sort!!

//
// * Step 1  place, camera, terretory
//

// CamId == ID of the camera

class CamId extends StatefulWidget {
  final TextEditingController id;

  const CamId({super.key, required this.id});

  @override
  State<CamId> createState() => _CamIdState();
}

class _CamIdState extends State<CamId> {
  bool error = false;
  String? selectedID;
  late Future<List<Map<String, dynamic>>> ids;

  @override
  void initState() {
    super.initState();
    ids = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          flex: 2,
          child: TextField(
            decoration: InputDecoration(
              hintText: AppLocalizations.of(context)!.camLink,
              enabledBorder: widget.id.text.isEmpty
                  ? const UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.red))
                  : const UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.green)),
              focusedBorder: widget.id.text.isEmpty
                  ? const UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.red))
                  : const UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.green)),
            ),
            controller: widget.id,
            onChanged: (value) {
              setState(() {
                widget.id.text = value;
              });
            },
          ),
        ),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: ids,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) => buildMenuItem(item['CID'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedID = value;
                          widget.id.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// Rudel == Rudel or Terretory or Animal species

class Rudel extends StatefulWidget {
  final TextEditingController rudelC;

  const Rudel({super.key, required this.rudelC});

  @override
  State<Rudel> createState() => _RudelState();
}

class _RudelState extends State<Rudel> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> rudel;

  @override
  void initState() {
    super.initState();
    rudel = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                hintText: AppLocalizations.of(context)!.rudel,
                enabledBorder: widget.rudelC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
                focusedBorder: widget.rudelC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
              ),
              controller: widget.rudelC,
              onChanged: (value) => setState(() {
                widget.rudelC.text = value;
              }),
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: rudel,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) => buildMenuItem(item['Rudel'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.rudelC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

//
// * Step 2  Date, contact, place
//

//
//
//
//
//
//
//
//
//
//
// Karte
// ! completely new page

class Karte extends StatefulWidget {
  final Position currentPosition;
  final Function(Position) onPositionChange;

  const Karte(
      {super.key,
      required this.currentPosition,
      required this.onPositionChange});

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

class KarteState extends State<Karte> {
  List<Marker> markers = [Marker(point: LatLng(0, 0), child: Icon(Icons.location_on))];
  LatLng? selectedPosition;
  Position? updatedPosition;
  bool saveVisible = false;

  @override
  void initState() {
    super.initState();
    markers = [Marker(point: LatLng(widget.currentPosition.latitude, widget.currentPosition.longitude), child: const Icon(Icons.location_on, color: Colors.red,))];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context)!.map),
        actions: [
          Visibility(
            visible: saveVisible,
            child: Row(
              children: [
                Text(AppLocalizations.of(context)!.saveMap),
                TextButton(
                  onPressed: () {
                    if (selectedPosition != null) {
                      setState(() {
                        updatedPosition = Position(
                            longitude: selectedPosition!.longitude,
                            latitude: selectedPosition!.latitude,
                            timestamp: DateTime.now(),
                            accuracy: 0.0,
                            altitude: 0.0,
                            altitudeAccuracy: 0.0,
                            heading: 0.0,
                            headingAccuracy: 0.0,
                            speed: 0.0,
                            speedAccuracy: 0.0);
                        widget.onPositionChange(updatedPosition!);
                      });
                    }
                    Navigator.pop(context);
                  },
                  child: const Icon(Icons.save),
                ),
              ],
            ),
          ),
        ],
      ),
      body: FlutterMap(
        mapController: MapController(),
          options: MapOptions(
                interactionOptions: const InteractionOptions(flags:  InteractiveFlag.pinchZoom | InteractiveFlag.drag | InteractiveFlag.pinchMove),
            initialCenter: LatLng(widget.currentPosition.latitude,
                widget.currentPosition.longitude),
            initialZoom: 16.0,
            onTap: _handleTap,
          ),
          children: [
            TileLayer(
              urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
              userAgentPackageName: 'com.example.app',
            ),
            MarkerLayer(markers: markers),
          ]),
    );
  }

  _handleTap(TapPosition position, LatLng latlng) {
    setState(() {
      markers.clear();
      markers.add(
        Marker(
          width: 80.0,
          height: 80.0,
          point: latlng,
          child: const Icon(
            Icons.location_on,
            color: Colors.red,
          ),
        ),
      );
      selectedPosition = latlng;
      saveVisible = true;
    });
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(
            "${AppLocalizations.of(context)!.markerSet}\n${selectedPosition!.latitude}\n${selectedPosition!.longitude}")));
  }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

// Datum == Datum der Aufstellung
// datum is the variable where the chosen date is stored

class Datum extends StatefulWidget {
  final DateTime? datum;

  const Datum({super.key, required this.datum});

  @override
  State<Datum> createState() => _DatumState();
}

class _DatumState extends State<Datum> {
  DateTime? datum = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Row(children: [
          SizedBox(
            width: 125,
            child: ElevatedButton(
                onPressed: () async {
                  final date = await pickDate();
                  if (date == null) return;
                  setState(() => datum = date);
                },
                child: Text(AppLocalizations.of(context)!.pickDate)),
          ),
          const SizedBox(
            width: 10,
          ),
          Text(
            '${datum?.day}. ${datum?.month}. ${datum?.year}',
          ),
        ]),
      ],
    );
  }

  Future<DateTime?> pickDate() async {
    final date = await showDatePicker(
        context: context,
        initialDate: datum!,
        firstDate: DateTime(2000),
        lastDate: DateTime(5000));
    if (date == null) return null;
    setState(() => datum = date);

    var place = {'Datum': DateFormat('yyyy-MM-dd').format(datum!)};

    await DBHelper().addPlace(place);

    return datum;
  }
}

// Adresse1

class Adresse1 extends StatefulWidget {
  final TextEditingController adresse1C;

  const Adresse1({super.key, required this.adresse1C});

  @override
State<Adresse1> createState() => _Adresse1State();
}

class _Adresse1State extends State<Adresse1> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> Adresse1;

  @override
  void initState() {
    super.initState();

    _loadPref();

    Adresse1 = DBHelper().getPlace();
  }

  void _loadPref() {
    Future.delayed(Duration.zero, () async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String adresse1 = prefs.getString('adresse1') ?? "";
      setState(() {
        widget.adresse1C.text = adresse1;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                hintText: AppLocalizations.of(context)!.adresse1,
                enabledBorder: widget.adresse1C.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
                focusedBorder: widget.adresse1C.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
              ),
              controller: widget.adresse1C,
              onChanged: (value) => setState(() {
                widget.adresse1C.text = value;
              }),
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: Adresse1,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['Adresse1'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.adresse1C.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// Adresse2

class Adresse2 extends StatefulWidget {
  final TextEditingController adresse2C;

  const Adresse2({super.key, required this.adresse2C});

  @override
  State<Adresse2> createState() => _Adresse2State();
}

class _Adresse2State extends State<Adresse2> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> Adresse2;

  @override
  void initState() {
    super.initState();
    Adresse2 = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.adresse2),
              controller: widget.adresse2C,
              onChanged: (value) => setState(() {
                widget.adresse2C.text = value;
              }),
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: Adresse2,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) => buildMenuItem(item['Adresse2'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.adresse2C.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// Adresse3

class Adresse3 extends StatefulWidget {
  final TextEditingController adresse3C;

  const Adresse3({super.key, required this.adresse3C});

  @override
  State<Adresse3> createState() => _Adresse3State();
}

class _Adresse3State extends State<Adresse3> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> Adresse3;

  @override
  void initState() {
    super.initState();
    Adresse3 = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.adresse3),
              controller: widget.adresse3C,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: Adresse3,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['Adresse3'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.adresse3C.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// BLand

class BLand extends StatefulWidget {
  final TextEditingController bLandC;

  const BLand({super.key, required this.bLandC});

  @override
  State<BLand> createState() => _BLandState();
}

class _BLandState extends State<BLand> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> BLand;

  @override
  void initState() {
    super.initState();

    if (widget.bLandC.text == "") _loadPref();

    BLand = DBHelper().getPlace();
  }

  void _loadPref() {
    Future.delayed(Duration.zero, () async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String bLand = prefs.getString('bLand') ?? "";
      setState(() {
        widget.bLandC.text = bLand;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                hintText: AppLocalizations.of(context)!.bland,
                enabledBorder: widget.bLandC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
                focusedBorder: widget.bLandC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
              ),
              controller: widget.bLandC,
              onChanged: (value) => setState(() {
                widget.bLandC.text = value;
              }),
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: BLand,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) => buildMenuItem(item['BLand'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.bLandC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// Lkr

class Lkr extends StatefulWidget {
  final TextEditingController lkrC;

  const Lkr({super.key, required this.lkrC});

  @override
  State<Lkr> createState() => _LkrState();
}

class _LkrState extends State<Lkr> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> Lkr;

  @override
  void initState() {
    super.initState();
    Lkr = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                hintText: AppLocalizations.of(context)!.lkr,
                enabledBorder: widget.lkrC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
                focusedBorder: widget.lkrC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
              ),
              controller: widget.lkrC,
              onChanged: (value) => setState(() {
                widget.lkrC.text = value;
              }),
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: Lkr,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) => buildMenuItem(item['Lkr'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.lkrC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// BeiOrt

class BeiOrt extends StatefulWidget {
  final TextEditingController beiOrtC;

  const BeiOrt({super.key, required this.beiOrtC});

  @override
  State<BeiOrt> createState() => _BeiOrtState();
}

class _BeiOrtState extends State<BeiOrt> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> BeiOrt;

  @override
  void initState() {
    super.initState();
    BeiOrt = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                hintText: AppLocalizations.of(context)!.beiort,
                enabledBorder: widget.beiOrtC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
                focusedBorder: widget.beiOrtC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
              ),
              controller: widget.beiOrtC,
              onChanged: (value) => setState(() {
                widget.beiOrtC.text = value;
              }),
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: BeiOrt,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) => buildMenuItem(item['BeiOrt'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.beiOrtC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// OrtInfo

class OrtInfo extends StatefulWidget {
  final TextEditingController ortInfoC;

  const OrtInfo({super.key, required this.ortInfoC});

  @override
  State<OrtInfo> createState() => _OrtInfoState();
}

class _OrtInfoState extends State<OrtInfo> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> OrtInfo;

  @override
  void initState() {
    super.initState();
    OrtInfo = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                hintText: AppLocalizations.of(context)!.ortinfo,
              ),
              controller: widget.ortInfoC,
              onChanged: (value) => setState(() {
                widget.ortInfoC.text = value;
              }),
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: OrtInfo,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map(
                            (item) => buildMenuItem(item['OrtInfo'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.ortInfoC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// Status

class Status extends StatefulWidget {
  final Function(String) onStatusChanged;
  final String initialStatus;

  const Status(
      {super.key, required this.onStatusChanged, this.initialStatus = 'Aktiv'});

  @override
  State<Status> createState() => _StatusState();
}

class _StatusState extends State<Status> {
  String? _selectedStatus;

  @override
  void initState() {
    super.initState();
    _selectedStatus = widget.initialStatus;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.aktiv),
          leading: Radio<String>(
            value: 'aktiv',
            groupValue: _selectedStatus,
            onChanged: (value) {
              setState(() {
                _selectedStatus = value;
                widget.onStatusChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.inaktiv),
          leading: Radio<String>(
            value: 'anaktiv',
            groupValue: _selectedStatus,
            onChanged: (value) {
              setState(() {
                _selectedStatus = value;
                widget.onStatusChanged(value!);
              });
            },
          ),
        ),
      ],
    );
  }
}

// STTyp

class STTyp extends StatefulWidget {
  final Function(String) onSTTypChanged;
  final String initialSTTyp;

  const STTyp(
      {super.key,
      required this.onSTTypChanged,
      this.initialSTTyp = 'opportunistisch'});

  @override
  State<STTyp> createState() => _STTypState();
}

class _STTypState extends State<STTyp> {
  String? _selectedSTTyp;

  @override
  void initState() {
    super.initState();
    _selectedSTTyp = widget.initialSTTyp;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.opportunistisch),
          leading: Radio<String>(
            value: 'opportunistisch',
            groupValue: _selectedSTTyp,
            onChanged: (value) {
              setState(() {
                _selectedSTTyp = value;
                widget.onSTTypChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.systematisch),
          leading: Radio<String>(
            value: 'systematisch',
            groupValue: _selectedSTTyp,
            onChanged: (value) {
              setState(() {
                _selectedSTTyp = value;
                widget.onSTTypChanged(value!);
              });
            },
          ),
        ),
      ],
    );
  }
}

// FFTyp

class FFTyp extends StatefulWidget {
  final TextEditingController ffTypC;

  const FFTyp({super.key, required this.ffTypC});

  @override
  State<FFTyp> createState() => _FFTypState();
}

class _FFTypState extends State<FFTyp> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> FFTyp;

  @override
  void initState() {
    super.initState();
    FFTyp = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                hintText: AppLocalizations.of(context)!.fftyp,
                enabledBorder: widget.ffTypC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
                focusedBorder: widget.ffTypC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
              ),
              controller: widget.ffTypC,
              onChanged: (value) => setState(() {
                widget.ffTypC.text = value;
              }),
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: FFTyp,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) => buildMenuItem(item['FFTyp'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.ffTypC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// platzung

class Platzung extends StatefulWidget {
  final Function(String) onPlatzungChanged;
  final String initialPlatzung;

  const Platzung(
      {super.key,
      required this.onPlatzungChanged,
      this.initialPlatzung = 'kirrung'});

  @override
  State<Platzung> createState() => _PlatzungState();
}

class _PlatzungState extends State<Platzung> {
  String? _selectedPlatzung;

  @override
  void initState() {
    super.initState();
    _selectedPlatzung = widget.initialPlatzung;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.kirrung),
          leading: Radio<String>(
            value: 'Kirrung',
            groupValue: _selectedPlatzung,
            onChanged: (value) {
              setState(() {
                _selectedPlatzung = value;
                widget.onPlatzungChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.wasserstelle),
          leading: Radio<String>(
            value: 'Wasserstelle',
            groupValue: _selectedPlatzung,
            onChanged: (value) {
              setState(() {
                _selectedPlatzung = value;
                widget.onPlatzungChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.wald),
          leading: Radio<String>(
            value: 'Wald',
            groupValue: _selectedPlatzung,
            onChanged: (value) {
              setState(() {
                _selectedPlatzung = value;
                widget.onPlatzungChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.wildwechsel),
          leading: Radio<String>(
            value: 'Wildwechsel',
            groupValue: _selectedPlatzung,
            onChanged: (value) {
              setState(() {
                _selectedPlatzung = value;
                widget.onPlatzungChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.wegstrasse),
          leading: Radio<String>(
            value: 'Weg/Straße',
            groupValue: _selectedPlatzung,
            onChanged: (value) {
              setState(() {
                _selectedPlatzung = value;
                widget.onPlatzungChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.hofgarten),
          leading: Radio<String>(
            value: 'Hof/Garten',
            groupValue: _selectedPlatzung,
            onChanged: (value) {
              setState(() {
                _selectedPlatzung = value;
                widget.onPlatzungChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.wiesefeld),
          leading: Radio<String>(
            value: 'Wiese/Feld/Offenfläche',
            groupValue: _selectedPlatzung,
            onChanged: (value) {
              setState(() {
                _selectedPlatzung = value;
                widget.onPlatzungChanged(value!);
              });
            },
          ),
        ),
      ],
    );
  }
}

// FotoFilm

class FotoFilm extends StatefulWidget {
  final Function(String) onFotoFilmChanged;
  final String initialFotoFilm;

  const FotoFilm(
      {super.key,
      required this.onFotoFilmChanged,
      this.initialFotoFilm = 'foto'});

  @override
  State<FotoFilm> createState() => _FotoFilmState();
}

class _FotoFilmState extends State<FotoFilm> {
  String? _selectedFotoFilm;

  @override
  void initState() {
    super.initState();
    _selectedFotoFilm = widget.initialFotoFilm;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.foto),
          leading: Radio<String>(
            value: 'Foto',
            groupValue: _selectedFotoFilm,
            onChanged: (value) {
              setState(() {
                _selectedFotoFilm = value;
                widget.onFotoFilmChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.film),
          leading: Radio<String>(
            value: 'Film',
            groupValue: _selectedFotoFilm,
            onChanged: (value) {
              setState(() {
                _selectedFotoFilm = value;
                widget.onFotoFilmChanged(value!);
              });
            },
          ),
        ),
      ],
    );
  }
}

// MEZ

class MEZ extends StatefulWidget {
  final Function(String) onMEZChanged;
  final String initialMEZ;

  const MEZ(
      {super.key, required this.onMEZChanged, this.initialMEZ = 'sommerzeit'});

  @override
  State<MEZ> createState() => _MEZState();
}

class _MEZState extends State<MEZ> {
  String? _selectedMEZ;

  @override
  void initState() {
    super.initState();
    _selectedMEZ = widget.initialMEZ;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.sommerzeit),
          leading: Radio<String>(
            value: 'Sommerzeit',
            groupValue: _selectedMEZ,
            onChanged: (value) {
              setState(() {
                _selectedMEZ = value;
                widget.onMEZChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.winterzeit),
          leading: Radio<String>(
            value: 'Winterzeit',
            groupValue: _selectedMEZ,
            onChanged: (value) {
              setState(() {
                _selectedMEZ = value;
                widget.onMEZChanged(value!);
              });
            },
          ),
        ),
      ],
    );
  }
}

// KSchloNr

class KSchloNr extends StatefulWidget {
  final TextEditingController kSchloNrC;

  const KSchloNr({super.key, required this.kSchloNrC});

  @override
  State<KSchloNr> createState() => _KSchloNrState();
}

class _KSchloNrState extends State<KSchloNr> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> KSchloNr;

  @override
  void initState() {
    super.initState();
    KSchloNr = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.kschlonr),
              controller: widget.kSchloNrC,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: KSchloNr,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['KSchloNr'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.kSchloNrC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// Bearsafe

class Bearsafe extends StatefulWidget {
  final Function(String) onBearsafeChanged;
  final String initialBearsafe;

  const Bearsafe(
      {super.key,
      required this.onBearsafeChanged,
      this.initialBearsafe = 'Nein'});

  @override
  State<Bearsafe> createState() => _BearsafeState();
}

class _BearsafeState extends State<Bearsafe> {
  String? _selectedBearsafe;

  @override
  void initState() {
    super.initState();
    _selectedBearsafe = widget.initialBearsafe;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.nein),
          leading: Radio<String>(
            value: 'Nein',
            groupValue: _selectedBearsafe,
            onChanged: (value) {
              setState(() {
                _selectedBearsafe = value;
                widget.onBearsafeChanged(value!);
              });
            },
          ),
        ),
        ListTile(
          visualDensity: const VisualDensity(vertical: -4),
          title: Text(AppLocalizations.of(context)!.ja),
          leading: Radio<String>(
            value: 'Ja',
            groupValue: _selectedBearsafe,
            onChanged: (value) {
              setState(() {
                _selectedBearsafe = value;
                widget.onBearsafeChanged(value!);
              });
            },
          ),
        ),
      ],
    );
  }
}

// KontDat

class KontDat extends StatefulWidget {
  final DateTime? kontDat;

  const KontDat({super.key, required this.kontDat});

  @override
  State<KontDat> createState() => _KontDatState();
}

class _KontDatState extends State<KontDat> {
  DateTime? kontDat = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Row(children: [
          SizedBox(
            width: 125,
            child: ElevatedButton(
                onPressed: () async {
                  final date = await pickDate();
                  if (date == null) return;
                  setState(() => kontDat = date);
                },
                child: Text(AppLocalizations.of(context)!.pickkontdat)),
          ),
          const SizedBox(
            width: 10,
          ),
          Text(
            '${kontDat?.day}. ${kontDat?.month}. ${kontDat?.year}',
          ),
        ]),
      ],
    );
  }

  Future<DateTime?> pickDate() async {
    final date = await showDatePicker(
        context: context,
        initialDate: kontDat!,
        firstDate: DateTime(2000),
        lastDate: DateTime(5000));
    if (date == null) return null;
    setState(() => kontDat = date);

    var place = {'KontDat': DateFormat('yyyy-MM-dd').format(kontDat!)};

    await DBHelper().addPlace(place);

    return kontDat;
  }
}

// AbbauDat

class AbbauDat extends StatefulWidget {
  final DateTime? abbauDat;

  const AbbauDat({super.key, required this.abbauDat});

  @override
  State<AbbauDat> createState() => _AbbauDatState();
}

class _AbbauDatState extends State<AbbauDat> {
  DateTime? abbauDat;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Row(children: [
          SizedBox(
            width: 125,
            child: ElevatedButton(
                onPressed: () async {
                  final date = await pickDate();
                  if (date == null) return;
                  setState(() => abbauDat = date);
                },
                child: Text(AppLocalizations.of(context)!.pickabbaudat)),
          ),
          const SizedBox(
            width: 10,
          ),
          Builder(builder: (context) {
            if (abbauDat != null) {
              return Text('${abbauDat?.day}. ${abbauDat?.month}. ${abbauDat?.year}');
            } else {
              return Text(AppLocalizations.of(context)!.nichts);
            }
          }),
        ]),
      ],
    );
  }

  Future<DateTime?> pickDate() async {
    final date = await showDatePicker(
        context: context,
        initialDate: abbauDat!,
        firstDate: DateTime(2000),
        lastDate: DateTime(5000));
    if (date == null) return null;
    setState(() => abbauDat = date);

    var place = {'AbbauDat': DateFormat('yyyy-MM-dd').format(abbauDat!)};

    await DBHelper().addPlace(place);

    return abbauDat;
  }
}

// Auftrag

class Auftrag extends StatefulWidget {
  final TextEditingController auftragC;

  const Auftrag({super.key, required this.auftragC});

  @override
  State<Auftrag> createState() => _AuftragState();
}

class _AuftragState extends State<Auftrag> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> Auftrag;

  @override
  void initState() {
    super.initState();
    Auftrag = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.auftrag),
              controller: widget.auftragC,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: Auftrag,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map(
                            (item) => buildMenuItem(item['Auftrag'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.auftragC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// KontAbsp

class KontAbsp extends StatefulWidget {
  final TextEditingController kontAbspC;

  const KontAbsp({super.key, required this.kontAbspC});

  @override
  State<KontAbsp> createState() => _KontAbspState();
}

class _KontAbspState extends State<KontAbsp> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> KontAbsp;

  @override
  void initState() {
    super.initState();
    KontAbsp = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.kontabsp),
              controller: widget.kontAbspC,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: KontAbsp,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['KontAbsp'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.kontAbspC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// SonstBem

class SonstBem extends StatefulWidget {
  final TextEditingController sonstBemC;

  const SonstBem({super.key, required this.sonstBemC});

  @override
  State<SonstBem> createState() => _SonstBemState();
}

class _SonstBemState extends State<SonstBem> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> SonstBem;

  @override
  void initState() {
    super.initState();
    SonstBem = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.sonstbemerkungen),
              controller: widget.sonstBemC,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: SonstBem,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['SonstBem'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.sonstBemC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// FKontakt1

class FKontakt1 extends StatefulWidget {
  final TextEditingController fKontakt1C;

  const FKontakt1({super.key, required this.fKontakt1C});

  @override
  State<FKontakt1> createState() => _FKontakt1State();
}

class _FKontakt1State extends State<FKontakt1> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> FKontakt1;

  @override
  void initState() {
    super.initState();
    FKontakt1 = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.fkontakt1),
              controller: widget.fKontakt1C,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: FKontakt1,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['FKontakt1'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.fKontakt1C.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// FKontakt2

class FKontakt2 extends StatefulWidget {
  final TextEditingController fKontakt2C;

  const FKontakt2({super.key, required this.fKontakt2C});

  @override
  State<FKontakt2> createState() => _FKontakt2State();
}

class _FKontakt2State extends State<FKontakt2> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> FKontakt2;

  @override
  void initState() {
    super.initState();
    FKontakt2 = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.fkontakt2),
              controller: widget.fKontakt2C,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: FKontakt2,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['FKontakt2'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.fKontakt2C.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// FKontakt3

class FKontakt3 extends StatefulWidget {
  final TextEditingController fKontakt3C;

  const FKontakt3({super.key, required this.fKontakt3C});

  @override
  State<FKontakt3> createState() => _FKontakt3State();
}

class _FKontakt3State extends State<FKontakt3> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> FKontakt3;

  @override
  void initState() {
    super.initState();
    FKontakt3 = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 3,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.fkontakt3),
              controller: widget.fKontakt3C,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: FKontakt3,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['FKontakt3'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.fKontakt3C.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// Standort

class Standort extends StatefulWidget {
  final TextEditingController standortC;

  const Standort({super.key, required this.standortC});

  @override
  State<Standort> createState() => _StandortState();
}

class _StandortState extends State<Standort> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> Standort;

  @override
  void initState() {
    super.initState();
    Standort = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 3,
            child: TextField(
              decoration: InputDecoration(
                hintText: AppLocalizations.of(context)!.altstort,
                enabledBorder: widget.standortC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
                focusedBorder: widget.standortC.text.isEmpty
                    ? const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))
                    : const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green)),
              ),
              controller: widget.standortC,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: Standort,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map((item) =>
                            buildMenuItem(item['Standort'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.standortC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// AusVon

class AusVon extends StatefulWidget {
  final DateTime? ausVon;

  const AusVon({super.key, required this.ausVon});

  @override
  State<AusVon> createState() => _AusVonState();
}

class _AusVonState extends State<AusVon> {
  DateTime? ausVon;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Row(children: [
          SizedBox(
            width: 125,
            child: ElevatedButton(
                onPressed: () async {
                  final date = await pickDate();
                  if (date == null) return;
                  setState(() => ausVon = date);
                },
                child: Text(AppLocalizations.of(context)!.ausvon)),
          ),
          const SizedBox(
            width: 10,
          ),
          Builder(builder: (context) {
            if (ausVon != null) {
              return Text('${ausVon?.day}. ${ausVon?.month}. ${ausVon?.year}');
            } else {
              return Text(AppLocalizations.of(context)!.nichts);
            }
          }),
        ]),
      ],
    );
  }

  Future<DateTime?> pickDate() async {
    final date = await showDatePicker(
        context: context,
        initialDate: ausVon,
        firstDate: DateTime(2000),
        lastDate: DateTime(5000));
    if (date == null) return null;
    setState(() => ausVon = date);

    var place = {'AusVon': DateFormat('yyyy-MM-dd').format(ausVon!)};

    await DBHelper().addPlace(place);

    return ausVon;
  }
}

// AusBis

class AusBis extends StatefulWidget {
  final DateTime? ausBis;

  const AusBis({super.key, required this.ausBis});

  @override
  State<AusBis> createState() => _AusBisState();
}

class _AusBisState extends State<AusBis> {
  DateTime? ausBis;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Row(children: [
          SizedBox(
            width: 125,
            child: ElevatedButton(
                onPressed: () async {
                  final date = await pickDate();
                  if (date == null) return;
                  setState(() => ausBis = date);
                },
                child: Text(AppLocalizations.of(context)!.ausbis)),
          ),
          const SizedBox(
            width: 10,
          ),
          Builder(builder: (context) {
            if (ausBis != null) {
              return Text('${ausBis?.day}. ${ausBis?.month}. ${ausBis?.year}');
            } else {
              return Text(AppLocalizations.of(context)!.nichts);
            }
          }),
        ]),
      ],
    );
  }

  Future<DateTime?> pickDate() async {
    final date = await showDatePicker(
        context: context,
        initialDate: ausBis,
        firstDate: DateTime(2000),
        lastDate: DateTime(5000));
    if (date == null) return null;
    setState(() => ausBis = date);

    var place = {'ausBis': DateFormat('yyyy-MM-dd').format(ausBis!)};

    await DBHelper().addPlace(place);

    return ausBis;
  }
}

// KTage1

class KTage1 extends StatefulWidget {
  final TextEditingController kTage1C;

  const KTage1({super.key, required this.kTage1C});

  @override
  State<KTage1> createState() => _KTage1State();
}

class _KTage1State extends State<KTage1> {
  @override
  void initState() {
    super.initState();
    widget.kTage1C.text = '28';
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      keyboardType: TextInputType.number,
      controller: widget.kTage1C,
      onChanged: (value) => setState(() {
        widget.kTage1C.text = value;
      }),
      decoration: InputDecoration(
        hintText: AppLocalizations.of(context)!.ktage1,
        enabledBorder: widget.kTage1C.text.isEmpty
            ? const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.red))
            : const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green)),
        focusedBorder: widget.kTage1C.text.isEmpty
            ? const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.red))
            : const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green)),
      ),
    );
  }
}

// KTage2

class KTage2 extends StatefulWidget {
  final TextEditingController kTage2C;

  const KTage2({super.key, required this.kTage2C});

  @override
  State<KTage2> createState() => _KTage2State();
}

class _KTage2State extends State<KTage2> {
  @override
  void initState() {
    super.initState();
    widget.kTage2C.text = '42';
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      keyboardType: TextInputType.number,
      controller: widget.kTage2C,
      onChanged: (value) => setState(() {
        widget.kTage2C.text = value;
      }),
      decoration: InputDecoration(
        hintText: AppLocalizations.of(context)!.ktage2,
        enabledBorder: widget.kTage2C.text.isEmpty
            ? const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.red))
            : const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green)),
        focusedBorder: widget.kTage2C.text.isEmpty
            ? const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.red))
            : const UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green)),
      ),
    );
  }
}

// IntKomm

class IntKomm extends StatefulWidget {
  final TextEditingController intKommC;

  const IntKomm({super.key, required this.intKommC});

  @override
  State<IntKomm> createState() => _IntKommState();
}

class _IntKommState extends State<IntKomm> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> IntKomm;

  @override
  void initState() {
    super.initState();
    IntKomm = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 2,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.intkomm),
              controller: widget.intKommC,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: IntKomm,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map(
                            (item) => buildMenuItem(item['IntKomm'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.intKommC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}

// KontSum

class Betreuung extends StatefulWidget {
  final TextEditingController betreuungC;

  const Betreuung({super.key, required this.betreuungC});

  @override
  State<Betreuung> createState() => _BetreuungState();
}

class _BetreuungState extends State<Betreuung> {
  String? selectedRudel;
  late Future<List<Map<String, dynamic>>> KontSum;

  @override
  void initState() {
    super.initState();
    KontSum = DBHelper().getPlace();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            flex: 3,
            child: TextField(
              decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.betreuung),
              controller: widget.betreuungC,
            )),
        Expanded(
          flex: 1,
          child: Align(
            alignment: Alignment.bottomLeft,
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: KontSum,
              builder: (BuildContext context,
                  AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                if (snapshot.hasData) {
                  return DropdownButton<String>(
                    items: snapshot.data!
                        .map(
                            (item) => buildMenuItem(item['KontSum'].toString()))
                        .toList(),
                    onChanged: (value) {
                      setState(
                        () {
                          selectedRudel = value;
                          widget.betreuungC.text = value ?? '';
                        },
                      );
                    },
                    value: null,
                    underline: const SizedBox(),
                  );
                } else if (snapshot.hasError) {
                  return Text('Fehler: ${snapshot.error}');
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
          ),
        )
      ],
    );
  }

  DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
        value: item,
        child: Text(item),
      );
}
