package de.assecutor.votianlt.pages.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.Div;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextArea;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.HasDynamicTitle;
import com.vaadin.flow.router.Route;
import de.assecutor.votianlt.model.SystemCompanyProfile;
import de.assecutor.votianlt.pages.base.ui.component.ViewToolbar;
import de.assecutor.votianlt.pages.base.ui.view.AdminLayout;
import de.assecutor.votianlt.service.SystemCompanyProfileService;
import jakarta.annotation.security.RolesAllowed;
import lombok.extern.slf4j.Slf4j;

/**
 * Admin profile page for editing the company data of the system operator.
 * These values are used as issuer data on system invoices to the users.
 */
@Route(value = "admin-profile", layout = AdminLayout.class)
@RolesAllowed("ADMIN")
@Slf4j
public class AdminProfileView extends VerticalLayout implements HasDynamicTitle {

    private final SystemCompanyProfileService profileService;

    private final TextField companyName = new TextField();
    private final TextField companySubtitle = new TextField();
    private final TextField companyStreet = new TextField();
    private final TextField companyCity = new TextField();
    private final TextField companyPhone = new TextField();
    private final TextField companyFax = new TextField();
    private final TextField companyEmail = new TextField();
    private final TextField companyWebsite = new TextField();
    private final TextField senderLine = new TextField();
    private final TextArea paymentTerms = new TextArea();
    private final TextArea footerText = new TextArea();

    private SystemCompanyProfile profile;

    public AdminProfileView(SystemCompanyProfileService profileService) {
        this.profileService = profileService;

        setSpacing(false);
        setPadding(false);
        setWidthFull();
        addClassName("admin-form-view");
        add(new ViewToolbar(getTranslation("adminprofile.title")));

        companyName.setLabel(getTranslation("adminprofile.field.companyname"));
        companySubtitle.setLabel(getTranslation("adminprofile.field.companysubtitle"));
        companyStreet.setLabel(getTranslation("adminprofile.field.street"));
        companyCity.setLabel(getTranslation("adminprofile.field.city"));
        companyPhone.setLabel(getTranslation("adminprofile.field.phone"));
        companyFax.setLabel(getTranslation("adminprofile.field.fax"));
        companyEmail.setLabel(getTranslation("adminprofile.field.email"));
        companyWebsite.setLabel(getTranslation("adminprofile.field.website"));
        senderLine.setLabel(getTranslation("adminprofile.field.senderline"));
        senderLine.setHelperText(getTranslation("adminprofile.field.senderline.helper"));
        paymentTerms.setLabel(getTranslation("adminprofile.field.paymentterms"));
        paymentTerms.setMinHeight("80px");
        footerText.setLabel(getTranslation("adminprofile.field.footer"));
        footerText.setHelperText(getTranslation("adminprofile.field.footer.helper"));
        footerText.setMinHeight("120px");

        FormLayout form = new FormLayout();
        form.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1), new FormLayout.ResponsiveStep("600px", 2));
        form.add(companyName, companySubtitle, companyStreet, companyCity, companyPhone, companyFax, companyEmail,
                companyWebsite);
        form.add(senderLine, 2);
        form.add(paymentTerms, 2);
        form.add(footerText, 2);

        VerticalLayout fieldsLayout = new VerticalLayout(form);
        fieldsLayout.setSpacing(true);
        fieldsLayout.setPadding(false);
        fieldsLayout.addClassNames("form-shell", "form-card");
        add(fieldsLayout);

        Button saveButton = new Button(getTranslation("button.savechanges"), e -> saveProfile());
        saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        Div actions = new Div(saveButton);
        actions.addClassNames("form-shell", "simple-card");
        add(actions);

        loadProfile();
    }

    private void loadProfile() {
        try {
            profile = profileService.getOrCreateProfile();
            companyName.setValue(nvl(profile.getCompanyName()));
            companySubtitle.setValue(nvl(profile.getCompanySubtitle()));
            companyStreet.setValue(nvl(profile.getCompanyStreet()));
            companyCity.setValue(nvl(profile.getCompanyCity()));
            companyPhone.setValue(nvl(profile.getCompanyPhone()));
            companyFax.setValue(nvl(profile.getCompanyFax()));
            companyEmail.setValue(nvl(profile.getCompanyEmail()));
            companyWebsite.setValue(nvl(profile.getCompanyWebsite()));
            senderLine.setValue(nvl(profile.getSenderLine()));
            paymentTerms.setValue(nvl(profile.getPaymentTerms()));
            // Footer is stored with <br> line breaks; edit it as multi-line text
            footerText.setValue(nvl(profile.getFooterText()).replace("<br>", "\n"));
        } catch (Exception ex) {
            log.error("Error loading system company profile: {}", ex.getMessage(), ex);
            Notification
                    .show(getTranslation("adminprofile.notification.load.error", ex.getMessage()), 5000,
                            Notification.Position.BOTTOM_CENTER)
                    .addThemeVariants(NotificationVariant.LUMO_ERROR);
        }
    }

    private void saveProfile() {
        try {
            profile.setCompanyName(companyName.getValue().trim());
            profile.setCompanySubtitle(companySubtitle.getValue().trim());
            profile.setCompanyStreet(companyStreet.getValue().trim());
            profile.setCompanyCity(companyCity.getValue().trim());
            profile.setCompanyPhone(companyPhone.getValue().trim());
            profile.setCompanyFax(companyFax.getValue().trim());
            profile.setCompanyEmail(companyEmail.getValue().trim());
            profile.setCompanyWebsite(companyWebsite.getValue().trim());
            profile.setSenderLine(senderLine.getValue().trim());
            profile.setPaymentTerms(paymentTerms.getValue().trim());
            profile.setFooterText(footerText.getValue().trim().replace("\n", "<br>"));

            profile = profileService.save(profile);
            Notification
                    .show(getTranslation("adminprofile.notification.saved"), 3000,
                            Notification.Position.BOTTOM_CENTER)
                    .addThemeVariants(NotificationVariant.LUMO_SUCCESS);
        } catch (Exception ex) {
            log.error("Error saving system company profile: {}", ex.getMessage(), ex);
            Notification
                    .show(getTranslation("adminprofile.notification.save.error", ex.getMessage()), 5000,
                            Notification.Position.BOTTOM_CENTER)
                    .addThemeVariants(NotificationVariant.LUMO_ERROR);
        }
    }

    private String nvl(String value) {
        return value != null ? value : "";
    }

    @Override
    public String getPageTitle() {
        return getTranslation("page.title.admin.profile");
    }
}
