import 'package:ambito/src/entity/_general/id_value/id_value.dart';
import 'package:ambito/src/packages/ambito_api/base_api.dart';
import 'package:ambito/src/widgets/buttons/edit_button.dart';
import 'package:ambito/src/widgets/buttons/outline_button.dart';
import 'package:ambito/src/widgets/buttons/save_buttons_group_with_cancel_action.dart';
import 'package:ambito/src/widgets/buttons/upload_image_button.dart';
import 'package:ambito/src/widgets/form/form_builder_fields/fbf_dropdown.dart';
import 'package:ambito/src/widgets/form/form_builder_fields/fbf_text.dart';
import 'package:ambito/src/widgets/form/form_builder_fields/fbf_textfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';
import 'package:screen_breakpoints/screen_breakpoints.dart';
import 'package:toggle_switch/toggle_switch.dart';

import '../../../consts/consts.dart';
import '../../../entity/business/business.dart';
import '../../../entity/login/login.dart';
import '../../../packages/ambito_theme/ambito_theme.dart';
import '../../../widgets/form/form_builder_fields/fbf_password.dart';
import '../../../widgets/page/base_page.dart';

class MasterDataPage extends StatefulWidget {
  const MasterDataPage(
      {super.key, required this.businessId, required this.userId});

  final int businessId;
  final int userId;

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

class MasterDataPageState extends State<MasterDataPage> {
  Login? login;
  Business? business;
  bool editMode = false;

  final formKeyPersonal = GlobalKey<FormBuilderState>();
  final formKeyBusiness = GlobalKey<FormBuilderState>();

  int display = 0;

  @override
  void initState() {
    login = isar.logins.where().idEqualTo(widget.userId).findFirst();

    if (login != null) {
      int businessId = login!.business!.first.id!;
      business = isar.business.where().idEqualTo(businessId).findFirst();
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final AmbitoTheme theme = getTheme(context);

    return BasePage().getPage(
      context,
      SingleChildScrollView(
        child: Align(
          alignment: Alignment.topCenter,
          child: Padding(
            padding: context.breakpoint.padding,
            child: SizedBox(
              width: 1152,
              height: MediaQuery.of(context).size.height - 80,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  theme.verticalSpacer,
                  Text(
                    'Stammdaten',
                    style: theme.titleMedium,
                  ),
                  theme.verticalSpacer,
                  Row(
                    children: [
                      ToggleSwitch(
                        initialLabelIndex: display,
                        totalSwitches: 2,
                        minWidth: 200,
                        borderWidth: 1,
                        labels: const ['Persönliches', 'Betriebsstätte'],
                        activeBgColor: [theme.currentColorScheme.secondary],
                        borderColor: [theme.currentColorScheme.secondary],
                        inactiveBgColor: Colors.white,
                        activeFgColor: theme.currentColorScheme.onSecondary,
                        customTextStyles: [theme.bodyMedium],
                        onToggle: (index) {
                          setState(() {
                            display = index ?? 0;
                          });
                        },
                      ),
                      const Spacer(),
                      (editMode == false)
                          ? EditButton(onPressed: () {
                              setState(() {
                                editMode = true;
                              });
                            })
                          : SaveButtonsGroupWithCancelAction(
                              onPressedCancel: () {
                                setState(() {
                                  editMode = false;
                                });
                              },
                              onPressedSave: () async {
                                await prefs.setBool('extended_json', false);
                                if (display == 0) {
                                  Login changedlogin = Login()
                                    ..id = widget.userId
                                    ..username = login!.username
                                    ..images = []
                                    ..salutation = formKeyPersonal.currentState!
                                            .fields['salutation']!.value ??
                                        ''
                                    ..salutation = formKeyPersonal.currentState!
                                            .fields['salutation']!.value ??
                                        ''
                                    ..title = formKeyPersonal.currentState!
                                            .fields['title']!.value ??
                                        ''
                                    ..firstName = formKeyPersonal.currentState!
                                            .fields['firstName']!.value ??
                                        ''
                                    ..lastName = formKeyPersonal.currentState!
                                            .fields['lastName']!.value ??
                                        ''
                                    ..email = formKeyPersonal.currentState!
                                            .fields['email']!.value ??
                                        ''
                                    ..phone = formKeyPersonal.currentState!
                                            .fields['phone']!.value ??
                                        ''
                                    ..password = formKeyPersonal.currentState!
                                            .fields['password']!.value ??
                                        ''
                                    ..business = [
                                      IdValue()
                                        ..id = business!.id
                                        ..value = business!.name
                                    ];

                                  await BaseApi().patchContent(
                                    'login',
                                    login!.id,
                                    changedlogin.toJson(),
                                    true,
                                  );
                                }
                                setState(() {
                                  editMode = false;
                                });
                                await prefs.setBool('extended_json', true);
                                Get.to(() => MasterDataPage(
                                    businessId: business!.id,
                                    userId: widget.userId));
                              },
                            ),
                    ],
                  ),
                  theme.verticalSpacer,
                  (display == 0)
                      ? personalWidget(context, theme, login!, formKeyPersonal)
                      : businessWidget(
                          context, theme, business!, formKeyBusiness),
                  theme.verticalSpacer,
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget personalWidget(BuildContext context, AmbitoTheme theme, Login login,
      GlobalKey<FormBuilderState> formKey) {
    return SizedBox(
      width: 1152,
      child: Card(
        elevation: 0,
        color: theme.currentColorScheme.tertiary,
        child: Padding(
          padding: EdgeInsets.all(20),
          child: (editMode == false)
              ? personalDisplay(context, theme, login)
              : personalEdit(context, theme, login, formKey),
        ),
      ),
    );
  }

  Widget personalDisplay(BuildContext context, AmbitoTheme theme, Login login) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Persönliches',
          style: theme.headlineSmall,
        ),
        theme.verticalSpacer,
        ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          child: login.getImage() != null
              ? login.getImage()!
              : Icon(
                  Icons.camera_alt_outlined,
                  size: 100,
                ),
        ),
        theme.verticalSpacerSmall,
        Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 20,
          children: [
            Row(
              children: [
                Text(
                  login.salutation ?? '',
                  style: theme.bodyMedium,
                ),
                theme.horizontalSpacerSmall,
                Text(
                  login.title ?? '',
                  style: theme.bodyMedium,
                ),
              ],
            ),
            Row(
              children: [
                Text(
                  login.firstName ?? '',
                  style: theme.bodyMedium,
                ),
                theme.horizontalSpacerSmall,
                Text(
                  login.lastName ?? '',
                  style: theme.bodyMedium,
                ),
              ],
            ),
            Row(
              children: [
                Icon(Icons.email_outlined),
                theme.horizontalSpacerSmall,
                Text(
                  login.email ?? '',
                  style: theme.bodyMedium,
                ),
              ],
            ),
            Row(
              children: [
                Icon(Icons.phone_outlined),
                theme.horizontalSpacerSmall,
                Text(
                  login.phone ?? '',
                  style: theme.bodyMedium,
                ),
              ],
            ),
          ],
        ),
      ],
    );
  }

  Widget personalEdit(BuildContext context, AmbitoTheme theme, Login login,
      GlobalKey<FormBuilderState> formKey) {
    List<String> salutationOptions = ['Herr', 'Frau', 'Ohne Anrede'];

    return FormBuilder(
      key: formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Persönliches',
            style: theme.headlineSmall,
          ),
          theme.verticalSpacer,
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                child: login.getImage() != null
                    ? login.getImage()!
                    : Icon(
                        Icons.camera_alt_outlined,
                        size: 100,
                      ),
              ),
              theme.horizontalSpacer,
              UploadImageButton(
                onPressed: () {},
              ),
            ],
          ),
          theme.verticalSpacer,
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                spacing: 20,
                children: [
                  FormBuilderFieldsDropDown.build(
                    theme,
                    'salutation',
                    'Anrede',
                    login.salutation,
                    salutationOptions,
                  ),
                  FormBuilderFieldsText.build(
                    theme,
                    'firstName',
                    'Vorname',
                    login.firstName,
                  ),
                  FormBuilderFieldsText.build(
                    theme,
                    'email',
                    'E-Mail',
                    login.email,
                  ),
                  FormBuilderFieldsPassword.build(
                    theme,
                    'password',
                    'Passwort',
                    login.password,
                  ),
                ],
              )),
              theme.horizontalSpacer,
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  spacing: 20,
                  children: [
                    FormBuilderFieldsText.build(
                      theme,
                      'title',
                      'Titel',
                      login.title,
                    ),
                    FormBuilderFieldsText.build(
                      theme,
                      'lastName',
                      'Nachname',
                      login.lastName,
                    ),
                    FormBuilderFieldsText.build(
                      theme,
                      'phone',
                      'Telefon',
                      login.phone,
                    ),
                    WidgetOutlineButton(
                      onPressed: () {},
                      title: 'Passwort ändern',
                      backgroundColor: theme.currentColorScheme.onPrimary,
                      foregroundColor: theme.currentColorScheme.secondary,
                      borderColor: theme.currentColorScheme.secondary,
                    )
                  ],
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  Widget businessWidget(BuildContext context, AmbitoTheme theme,
      Business business, GlobalKey<FormBuilderState> formKey) {
    return SizedBox(
      width: 1152,
      child: Card(
        elevation: 0,
        color: theme.currentColorScheme.tertiary,
        child: Padding(
          padding: EdgeInsets.all(20),
          child: (editMode == false)
              ? businessDisplay(context, theme, business)
              : businessEdit(context, theme, business, formKey),
        ),
      ),
    );
  }

  Widget businessDisplay(
      BuildContext context, AmbitoTheme theme, Business business) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Betriebsstätte',
          style: theme.headlineSmall,
        ),
        theme.verticalSpacer,
        Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 20,
          children: [
            Row(
              children: [
                Text(
                  business.name ?? '',
                  style: theme.bodyMedium,
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Icon(Icons.location_city_outlined),
                theme.horizontalSpacerSmall,
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  spacing: 10,
                  children: [
                    Text(
                      business.addressStreet ?? '',
                      style: theme.bodyMedium,
                    ),
                    Row(
                      spacing: 10,
                      children: [
                        Text(
                          business.addressPostalCode ?? '',
                          style: theme.bodyMedium,
                        ),
                        Text(
                          business.addressCity ?? '',
                          style: theme.bodyMedium,
                        ),
                      ],
                    ),
                    Text(
                      business.addressRegion ?? '',
                      style: theme.bodyMedium,
                    ),
                    Text(
                      business.addressFederalState ?? '',
                      style: theme.bodyMedium,
                    ),
                  ],
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Icon(Icons.note_alt_outlined),
                theme.horizontalSpacerSmall,
                Expanded(
                  child: Text(
                    business.notice ?? '',
                    style: theme.bodyMedium,
                  ),
                ),
              ],
            ),
          ],
        ),
      ],
    );
  }

  Widget businessEdit(BuildContext context, AmbitoTheme theme,
      Business business, GlobalKey<FormBuilderState> formKey) {
    List<String> regions = [
      'Ahr',
      'Baden',
      'Franken',
      'Hessische Bergtraße',
      'Mittelrhein',
      'Mosel',
      'Nahe',
      'Pfalz',
      'Rheingau',
      'Rheinhessen',
      'Saale-Unstrut',
      'Sachsen',
      'Württemberg',
    ];
    List<String> bundeslaender = [
      'Baden-Württemberg',
      'Bayern',
      'Berlin',
      'Brandenburg',
      'Bremen',
      'Hamburg',
      'Hessen',
      'Mecklenburg-Vorpommern',
      'Niedersachsen',
      'Nordrhein-Westfalen',
      'Rheinland-Pfalz',
      'Saarland',
      'Sachsen',
      'Sachsen-Anhalt',
      'Schleswig-Holstein',
      'Thüringen'
    ];

    return FormBuilder(
      key: formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Betriebsstätte',
            style: theme.headlineSmall,
          ),
          theme.verticalSpacer,
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                spacing: 20,
                children: [
                  FormBuilderFieldsText.build(
                    theme,
                    'name',
                    'Bezeichnung',
                    business.name,
                  ),
                  FormBuilderFieldsText.build(
                    theme,
                    'postalCode',
                    'PLZ',
                    business.addressPostalCode,
                  ),
                  FormBuilderFieldsDropDown.build(
                    theme,
                    'federalState',
                    'Bundesland',
                    business.addressFederalState,
                    bundeslaender,
                  ),
                ],
              )),
              theme.horizontalSpacer,
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  spacing: 20,
                  children: [
                    FormBuilderFieldsText.build(
                      theme,
                      'addressStreet',
                      'Adresse',
                      business.addressStreet,
                    ),
                    FormBuilderFieldsText.build(
                      theme,
                      'addressCity',
                      'Stadt',
                      business.addressCity,
                    ),
                    FormBuilderFieldsDropDown.build(
                      theme,
                      'region',
                      'Region',
                      business.addressRegion,
                      regions,
                    ),
                  ],
                ),
              ),
            ],
          ),
          theme.verticalSpacer,
          FormBuilderFieldsTextField.build(
            theme,
            'notice',
            'Notiz',
            business.notice,
          ),
        ],
      ),
    );
  }
}
