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.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.router.BeforeEvent;
import com.vaadin.flow.router.HasDynamicTitle;
import com.vaadin.flow.router.HasUrlParameter;
import com.vaadin.flow.router.Route;
import de.assecutor.votianlt.model.Customer;
import de.assecutor.votianlt.pages.base.ui.component.DialogStylingHelper;
import de.assecutor.votianlt.pages.service.CustomerService;
import jakarta.annotation.security.RolesAllowed;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.flow.component.orderedlayout.FlexComponent;

@Route(value = "edit-customer", layout = de.assecutor.votianlt.pages.base.ui.view.MainLayout.class)
@RolesAllowed({ "USER", "ADMIN" })
public class EditCustomerView extends VerticalLayout implements HasUrlParameter<String>, HasDynamicTitle {

    private final CustomerService customerService;
    private Customer customer;
    private final Binder<Customer> binder = new Binder<>(Customer.class);

    // Form fields - labels set in constructor via setLabel()
    private final TextField titleField = new TextField();
    private final TextField companyNameField = new TextField();
    private final TextField firstnameField = new TextField();
    private final TextField lastNameField = new TextField();
    private final TextField telephoneField = new TextField();
    private final TextField faxField = new TextField();
    private final EmailField mailField = new EmailField();
    private final TextField streetField = new TextField();
    private final TextField houseNumberField = new TextField();
    private final TextField addressAdditionField = new TextField();
    private final TextField zipField = new TextField();
    private final TextField cityField = new TextField();

    @Autowired
    public EditCustomerView(CustomerService customerService) {
        this.customerService = customerService;
        setSizeFull();
        setPadding(true);
        addClassName("form-page");
        setSpacing(true);
        setJustifyContentMode(FlexComponent.JustifyContentMode.START);
        setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.STRETCH);
        getStyle().set("overflow", "auto");

        // Set field labels via i18n
        titleField.setLabel(getTranslation("addjob.address.salutation"));
        companyNameField.setLabel(getTranslation("profile.company"));
        firstnameField.setLabel(getTranslation("profile.firstname"));
        lastNameField.setLabel(getTranslation("profile.lastname"));
        telephoneField.setLabel(getTranslation("profile.phone"));
        faxField.setLabel(getTranslation("profile.fax"));
        mailField.setLabel(getTranslation("profile.email"));
        streetField.setLabel(getTranslation("profile.street"));
        houseNumberField.setLabel(getTranslation("profile.housenr"));
        addressAdditionField.setLabel(getTranslation("profile.addressadd"));
        zipField.setLabel(getTranslation("profile.zip"));
        cityField.setLabel(getTranslation("profile.city"));

        // Create main content container
        VerticalLayout contentContainer = new VerticalLayout();
        contentContainer.setWidthFull();
        contentContainer.setMaxWidth("100%");
        contentContainer.setSpacing(true);
        contentContainer.setPadding(true);
        contentContainer.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.STRETCH);
        contentContainer.addClassNames("form-shell", "form-card");

        // Header
        H2 header = new H2(getTranslation("editcustomer.title"));
        header.addClassName("form-title");
        header.getStyle().set("text-align", "center");
        contentContainer.add(header);

        // Form layout
        FormLayout formLayout = new FormLayout();
        formLayout.setWidthFull();
        formLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1));

        // Add fields to form - all fields in single column
        formLayout.add(titleField);
        formLayout.add(companyNameField);
        formLayout.add(firstnameField);
        formLayout.add(lastNameField);
        formLayout.add(telephoneField);
        formLayout.add(faxField);
        formLayout.add(mailField);
        formLayout.add(streetField);
        formLayout.add(houseNumberField);
        formLayout.add(addressAdditionField);
        formLayout.add(zipField);
        formLayout.add(cityField);

        contentContainer.add(formLayout);

        // Buttons
        HorizontalLayout buttonLayout = new HorizontalLayout();
        buttonLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.CENTER);
        buttonLayout.setWidthFull();

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

        Button cancelButton = new Button(getTranslation("button.cancel"), e -> navigateBack());
        Button deleteButton = new Button(getTranslation("button.delete"), e -> deleteCustomer());
        deleteButton.addThemeVariants(ButtonVariant.LUMO_ERROR);

        buttonLayout.add(saveButton, cancelButton, deleteButton);
        buttonLayout.setSpacing(true);
        contentContainer.add(buttonLayout);

        // Add content container to main layout
        add(contentContainer);

        // Bind fields to customer properties
        setupBinder();
    }

    private void setupBinder() {
        binder.forField(titleField).bind(Customer::getTitle, Customer::setTitle);
        binder.forField(companyNameField).bind(Customer::getCompanyName, Customer::setCompanyName);
        binder.forField(firstnameField).bind(Customer::getFirstname, Customer::setFirstname);
        binder.forField(lastNameField).bind(Customer::getLastName, Customer::setLastName);
        binder.forField(telephoneField).bind(Customer::getTelephone, Customer::setTelephone);
        binder.forField(faxField).bind(Customer::getFax, Customer::setFax);
        binder.forField(mailField).bind(Customer::getMail, Customer::setMail);
        binder.forField(streetField).bind(Customer::getStreet, Customer::setStreet);
        binder.forField(houseNumberField).bind(Customer::getHouseNumber, Customer::setHouseNumber);
        binder.forField(addressAdditionField).bind(Customer::getAddressAddition, Customer::setAddressAddition);
        binder.forField(zipField).bind(Customer::getZip, Customer::setZip);
        binder.forField(cityField).bind(Customer::getCity, Customer::setCity);
    }

    @Override
    public void setParameter(BeforeEvent event, String parameter) {
        try {
            ObjectId customerId = new ObjectId(parameter);
            customer = customerService.findById(customerId);

            if (customer == null) {
                Notification.show(getTranslation("editcustomer.notification.notfound"), 3000,
                        Notification.Position.MIDDLE);
                navigateBack();
                return;
            }

            // Load customer data into form
            binder.readBean(customer);

        } catch (IllegalArgumentException e) {
            Notification.show(getTranslation("editcustomer.notification.invalid.id"), 3000,
                    Notification.Position.MIDDLE);
            navigateBack();
        }
    }

    private void saveCustomer() {
        try {
            binder.writeBean(customer);
            customerService.save(customer);
            Notification.show(getTranslation("editcustomer.notification.saved"), 3000, Notification.Position.MIDDLE);
            navigateBack();
        } catch (ValidationException e) {
            Notification.show(getTranslation("editcustomer.notification.check"), 3000, Notification.Position.MIDDLE);
        }
    }

    private void deleteCustomer() {
        // Show confirmation dialog
        Dialog confirmDialog = DialogStylingHelper
                .createStyledDialog(getTranslation("editcustomer.dialog.delete.confirm"), "460px");
        confirmDialog.setCloseOnOutsideClick(false);

        VerticalLayout dialogContent = DialogStylingHelper.createContentLayout("320px");
        dialogContent.add(new Span(getTranslation("editcustomer.dialog.delete.text")));

        Button confirmDeleteButton = new Button(getTranslation("editcustomer.dialog.delete.confirm"), e -> {
            if (customer != null && customer.getId() != null) {
                customerService.deleteById(customer.getId());
                Notification.show(getTranslation("editcustomer.notification.deleted"), 3000,
                        Notification.Position.MIDDLE);
                confirmDialog.close();
                navigateBack();
            }
        });
        confirmDeleteButton.addThemeVariants(ButtonVariant.LUMO_ERROR);

        Button cancelDeleteButton = new Button(getTranslation("button.cancel"), e -> confirmDialog.close());
        cancelDeleteButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);

        confirmDialog.add(DialogStylingHelper.wrapContent(dialogContent));
        confirmDialog.getFooter().add(cancelDeleteButton, confirmDeleteButton);

        confirmDialog.open();
    }

    private void navigateBack() {
        getUI().ifPresent(ui -> ui.navigate("customers"));
    }

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