package org.example.petshopdesktop.controllers.dialogcontrollers;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.example.petshopdesktop.Validator;
import org.example.petshopdesktop.api.dto.user.UserRequest;
import org.example.petshopdesktop.api.dto.user.UserResponse;
import org.example.petshopdesktop.api.endpoints.UserApi;
import org.example.petshopdesktop.api.endpoints.CustomerApi;
import org.example.petshopdesktop.auth.UserSession;
import org.example.petshopdesktop.util.ActivityLogger;

public class StaffEditDialogController {

    @FXML
    private TextField txtFirstName;

    @FXML
    private TextField txtLastName;

    @FXML
    private TextField txtEmail;

    @FXML
    private TextField txtPhone;

    @FXML
    private TextField txtUsername;

    @FXML
    private PasswordField txtPassword;

    @FXML
    private PasswordField txtPasswordConfirm;

    @FXML
    private Label lblError;

    @FXML
    private Button btnSave;

    private UserResponse user;

    public void setUser(UserResponse user) {
        this.user = user;
        String fullName = user.getFullName() == null ? "" : user.getFullName();
        String[] names = splitFullName(fullName);
        txtFirstName.setText(names[0]);
        txtLastName.setText(names[1]);
        txtEmail.setText(user.getEmail());
        txtPhone.setText(user.getPhone());
        txtUsername.setText(user.getUsername());
    }

    private String[] splitFullName(String fullName) {
        if (fullName == null || fullName.trim().isEmpty()) {
            return new String[]{"", ""};
        }
        String[] parts = fullName.trim().split("\\s+", 2);
        String firstName = parts.length > 0 ? parts[0] : "";
        String lastName = parts.length > 1 ? parts[1] : "";
        return new String[]{firstName, lastName};
    }

    @FXML
    void btnSaveClicked(ActionEvent event) {
        lblError.setText("");
        if (user == null) {
            lblError.setText("No user selected.");
            return;
        }

        String firstName = value(txtFirstName);
        String lastName = value(txtLastName);
        String email = value(txtEmail);
        String phone = value(txtPhone);
        String username = value(txtUsername);
        String password = txtPassword.getText() == null ? "" : txtPassword.getText().trim();
        String confirm = txtPasswordConfirm.getText() == null ? "" : txtPasswordConfirm.getText().trim();

        if (firstName.isBlank() || lastName.isBlank()) {
            lblError.setText("First name and last name are required.");
            return;
        }
        if (email.isBlank()) {
            lblError.setText("Email is required.");
            return;
        }
        if (phone.isBlank()) {
            lblError.setText("Phone is required.");
            return;
        }
        String phoneError = Validator.isValidPhoneNumber(phone, "Phone");
        if (!phoneError.isEmpty()) {
            lblError.setText(phoneError.trim());
            return;
        }
        if (username.isBlank()) {
            lblError.setText("Username is required.");
            return;
        }
        if (!password.isEmpty() && password.length() < 6) {
            lblError.setText("Password must be at least 6 characters.");
            return;
        }
        if (!password.equals(confirm)) {
            lblError.setText("Passwords do not match.");
            return;
        }

        btnSave.setDisable(true);

        new Thread(() -> {
            try {
                UserRequest request = new UserRequest();
                request.setUsername(username);
                request.setPassword(password.isEmpty() ? null : password);
                request.setFullName(firstName + " " + lastName);
                request.setEmail(email);
                request.setPhone(phone);
                request.setRole(user.getRole());
                request.setActive(user.getActive());

                UserSession session = UserSession.getInstance();
                if (session.isAdmin()) {
                    UserApi.getInstance().updateUser(user.getId(), request);
                } else {
                    CustomerApi.getInstance().updateCustomer(user.getId(), request);
                }

                Platform.runLater(this::close);
            } catch (Exception e) {
                ActivityLogger.getInstance().logException("StaffEditDialogController.btnSaveClicked", e, "Updating user");
                String msg = e.getMessage() == null ? "Could not update user." : e.getMessage();
                Platform.runLater(() -> {
                    lblError.setText(msg);
                    btnSave.setDisable(false);
                });
            }
        }).start();
    }

    @FXML
    void btnCancelClicked(ActionEvent event) {
        close();
    }

    private void close() {
        Stage stage = (Stage) btnSave.getScene().getWindow();
        stage.close();
    }

    private static String value(TextField tf) {
        return tf.getText() == null ? "" : tf.getText().trim();
    }
}
