package de.votian.web.view;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.H3;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.IntegerField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import de.votian.web.model.SessionData;
import de.votian.web.service.RestClientService;

import java.util.LinkedHashMap;
import java.util.Map;

@Route(value = "headquarters-admin", layout = MainLayout.class)
@PageTitle("Votian - Niederlassung")
public class HeadquartersAdminView extends VerticalLayout {

    private final RestClientService restClient;
    private final SessionData sessionData;

    private final TextField mnemonicField = new TextField("Kuerzel");
    private final TextField nameField = new TextField("Name");
    private final IntegerField workmodeField = new IntegerField("Workmode");
    private final TextField companyNameField = new TextField("Firma");
    private final TextField companyName2Field = new TextField("Firma 2");
    private final TextField companyName3Field = new TextField("Firma 3");
    private final TextField companyName4Field = new TextField("Firma 4");
    private final TextField streetField = new TextField("Strasse");
    private final TextField hsnoField = new TextField("Hausnummer");
    private final TextField zipcodeField = new TextField("PLZ");
    private final TextField cityField = new TextField("Ort");
    private final TextField bwvPhoneField = new TextField("BWV-Hotline");
    private final TextField glnField = new TextField("GLN");
    private final TextField dunsField = new TextField("DUNS");

    public HeadquartersAdminView(RestClientService restClient, SessionData sessionData) {
        this.restClient = restClient;
        this.sessionData = sessionData;

        setPadding(true);
        setSpacing(true);

        FormLayout form = new FormLayout();
        form.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1),
                new FormLayout.ResponsiveStep("700px", 2));
        form.add(
                mnemonicField, nameField, workmodeField, companyNameField, companyName2Field,
                companyName3Field, companyName4Field, streetField, hsnoField, zipcodeField,
                cityField, bwvPhoneField, glnField, dunsField
        );

        Button saveButton = new Button("Speichern", event -> save());
        saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        saveButton.setEnabled(sessionData.canManageHeadquarters());

        add(new H3("Niederlassung"), form, new HorizontalLayout(saveButton));
        load();
    }

    @SuppressWarnings("unchecked")
    private void load() {
        if (sessionData.getHeadquartersId() == null) {
            return;
        }
        try {
            Map<String, Object> data = restClient.get("/headquarters/" + sessionData.getHeadquartersId(), LinkedHashMap.class);
            mnemonicField.setValue(str(data.get("mnemonic")));
            nameField.setValue(str(data.get("name")));
            workmodeField.setValue(data.get("workmode") instanceof Number ? ((Number) data.get("workmode")).intValue() : null);
            companyNameField.setValue(str(data.get("companyName")));
            companyName2Field.setValue(str(data.get("companyName2")));
            companyName3Field.setValue(str(data.get("companyName3")));
            companyName4Field.setValue(str(data.get("companyName4")));
            streetField.setValue(str(data.get("street")));
            hsnoField.setValue(str(data.get("hsno")));
            zipcodeField.setValue(str(data.get("zipcode")));
            cityField.setValue(str(data.get("city")));
            bwvPhoneField.setValue(str(data.get("bwvPhone")));
            glnField.setValue(str(data.get("gln")));
            dunsField.setValue(str(data.get("duns")));
        } catch (Exception e) {
            Notification.show("Niederlassung konnte nicht geladen werden.", 4000, Notification.Position.MIDDLE)
                    .addThemeVariants(NotificationVariant.LUMO_ERROR);
        }
    }

    private void save() {
        if (!sessionData.canManageHeadquarters()) {
            Notification.show("Keine Berechtigung zum Bearbeiten der Niederlassung.", 4000, Notification.Position.MIDDLE)
                    .addThemeVariants(NotificationVariant.LUMO_ERROR);
            return;
        }
        if (sessionData.getHeadquartersId() == null) {
            return;
        }
        try {
            Map<String, Object> request = new LinkedHashMap<>();
            Map<String, Object> headquarters = new LinkedHashMap<>();
            headquarters.put("mnemonic", mnemonicField.getValue());
            headquarters.put("name", nameField.getValue());
            headquarters.put("workmode", workmodeField.getValue());
            request.put("headquarters", headquarters);

            Map<String, Object> company = new LinkedHashMap<>();
            company.put("comp", companyNameField.getValue());
            company.put("comp2", companyName2Field.getValue());
            company.put("comp3", companyName3Field.getValue());
            company.put("comp4", companyName4Field.getValue());
            company.put("hsno", hsnoField.getValue());
            request.put("company", company);

            Map<String, Object> address = new LinkedHashMap<>();
            address.put("street", streetField.getValue());
            address.put("zipcode", zipcodeField.getValue());
            address.put("city", cityField.getValue());
            address.put("country", "DE");
            request.put("address", address);

            request.put("bwvPhone", bwvPhoneField.getValue());
            request.put("gln", glnField.getValue());
            request.put("duns", dunsField.getValue());

            restClient.put("/headquarters/" + sessionData.getHeadquartersId(), request);
            Notification.show("Niederlassung gespeichert.", 3000, Notification.Position.MIDDLE)
                    .addThemeVariants(NotificationVariant.LUMO_SUCCESS);
            load();
        } catch (Exception e) {
            Notification.show("Niederlassung konnte nicht gespeichert werden.", 5000, Notification.Position.MIDDLE)
                    .addThemeVariants(NotificationVariant.LUMO_ERROR);
        }
    }

    private String str(Object value) {
        return value != null ? value.toString() : "";
    }
}
