package org.example.petshopdesktop.controllers.dialogcontrollers;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
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.api.dto.user.UserRequest;
import org.example.petshopdesktop.api.endpoints.UserApi;
import org.example.petshopdesktop.api.endpoints.CustomerApi;
import org.example.petshopdesktop.auth.UserSession;
import org.example.petshopdesktop.Validator;
import org.example.petshopdesktop.util.ActivityLogger;

public class StaffRegisterDialogController {

    @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 btnCreate;

    @FXML
    void btnCreateClicked(ActionEvent event) {
        lblError.setText("");

        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();
        String confirm = txtPasswordConfirm.getText() == null ? "" : txtPasswordConfirm.getText();

        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.isBlank()) {
            lblError.setText("Password is required.");
            return;
        }
        if (!password.equals(confirm)) {
            lblError.setText("Passwords do not match.");
            return;
        }

        btnCreate.setDisable(true);

        new Thread(() -> {
            try {
                UserSession session = UserSession.getInstance();
                UserRequest request = new UserRequest();
                request.setUsername(username);
                request.setPassword(password);
                request.setFullName(firstName + " " + lastName);
                request.setEmail(email);
                request.setPhone(phone);
                request.setActive(true);

                if (session.isAdmin()) {
                    request.setRole("STAFF");
                    UserApi.getInstance().createUser(request);
                } else {
                    request.setRole("CUSTOMER");
                    CustomerApi.getInstance().createCustomer(request);
                }

                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("Account Created");
                    alert.setHeaderText(null);
                    alert.setContentText("Account created successfully.");
                    alert.showAndWait();
                    close();
                });
            } catch (Exception e) {
                ActivityLogger.getInstance().logException("StaffRegisterDialogController.btnCreateClicked", e, "Creating account");
                String msg = e.getMessage() == null ? "Could not create account." : e.getMessage();
                Platform.runLater(() -> {
                    if (msg.toLowerCase().contains("duplicate") || msg.toLowerCase().contains("unique")) {
                        lblError.setText("Username already exists.");
                    } else {
                        lblError.setText(msg);
                    }
                    btnCreate.setDisable(false);
                });
            }
        }).start();
    }

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

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

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