package org.example.petshopdesktop.controllers.dialogcontrollers;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import org.example.petshopdesktop.Validator;
import org.example.petshopdesktop.api.dto.common.DropdownOption;
import org.example.petshopdesktop.api.dto.employee.EmployeeRequest;
import org.example.petshopdesktop.api.dto.employee.EmployeeResponse;
import org.example.petshopdesktop.api.endpoints.DropdownApi;
import org.example.petshopdesktop.api.endpoints.EmployeeApi;
import org.example.petshopdesktop.api.endpoints.UserApi;
import org.example.petshopdesktop.util.ActivityLogger;
import org.example.petshopdesktop.util.DesktopImageSupport;
import org.example.petshopdesktop.util.FilePickerSupport;
import org.example.petshopdesktop.util.TextFieldFormatSupport;

import java.io.File;
import java.util.List;

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 ComboBox<String> cbRole;
    @FXML private ComboBox<String> cbActive;
    @FXML private ComboBox<DropdownOption> cbStore;
    @FXML private Label lblError;
    @FXML private Button btnSave;

    @FXML private ImageView imgAvatarPreview;
    @FXML private Label lblAvatarStatus;
    @FXML private Button btnChangeAvatar;
    @FXML private Button btnRemoveAvatar;

    private EmployeeResponse employee;
    private Long pendingStoreId = null;
    private File selectedAvatarFile;
    private String currentAvatarUrl;
    private boolean removeAvatarRequested;

    @FXML
    void initialize() {
        TextFieldFormatSupport.applyPhoneNumberFormat(txtPhone);

        cbRole.setItems(FXCollections.observableArrayList("STAFF", "ADMIN"));
        cbActive.setItems(FXCollections.observableArrayList("Active", "Inactive"));

        cbStore.setCellFactory(param -> new ListCell<>() {
            @Override protected void updateItem(DropdownOption o, boolean empty) {
                super.updateItem(o, empty);
                setText(empty || o == null ? null : o.getLabel());
            }
        });
        cbStore.setButtonCell(new ListCell<>() {
            @Override protected void updateItem(DropdownOption o, boolean empty) {
                super.updateItem(o, empty);
                setText(empty || o == null ? null : o.getLabel());
            }
        });

        btnChangeAvatar.setOnMouseClicked(e -> handleChangeAvatar());
        btnRemoveAvatar.setOnMouseClicked(e -> handleRemoveAvatar());

        loadStores();
    }

    private void loadStores() {
        new Thread(() -> {
            try {
                List<DropdownOption> stores = DropdownApi.getInstance().getStores();
                Platform.runLater(() -> {
                    cbStore.setItems(FXCollections.observableArrayList(stores));
                    applyPendingStore();
                });
            } catch (Exception e) {
                ActivityLogger.getInstance().logException("StaffEditDialogController.loadStores", e, "Loading stores");
                Platform.runLater(() -> {
                    cbStore.setDisable(true);
                    cbStore.setPromptText("Unable to load stores");
                });
            }
        }).start();
    }

    private void applyPendingStore() {
        if (pendingStoreId == null) return;
        for (DropdownOption opt : cbStore.getItems()) {
            if (opt.getId() != null && opt.getId().equals(pendingStoreId)) {
                cbStore.setValue(opt);
                pendingStoreId = null;
                return;
            }
        }
    }

    public void setEmployee(EmployeeResponse emp) {
        this.employee = emp;
        String fullName = emp.getFullName() != null ? emp.getFullName() : "";
        if (fullName.isEmpty() && emp.getFirstName() != null) {
            fullName = emp.getFirstName() + (emp.getLastName() != null ? " " + emp.getLastName() : "");
        }
        String[] names = splitFullName(fullName);
        txtFirstName.setText(names[0]);
        txtLastName.setText(names[1]);
        txtEmail.setText(emp.getEmail());
        txtPhone.setText(emp.getPhone());
        txtUsername.setText(emp.getUsername());

        if (emp.getRole() != null) cbRole.setValue(emp.getRole());
        cbActive.setValue(Boolean.TRUE.equals(emp.getActive()) ? "Active" : "Inactive");

        pendingStoreId = emp.getPrimaryStoreId();
        applyPendingStore();

        currentAvatarUrl = emp.getAvatarUrl();
        refreshAvatarPreview();
    }

    private void handleChangeAvatar() {
        File file = FilePickerSupport.pickImageFile(btnSave.getScene().getWindow());
        if (file == null) return;
        selectedAvatarFile = file;
        removeAvatarRequested = false;
        lblAvatarStatus.setText("Selected: " + file.getName());
        DesktopImageSupport.loadImageInto(imgAvatarPreview, file.toURI().toString(), 90, 90);
        btnRemoveAvatar.setDisable(false);
    }

    private void handleRemoveAvatar() {
        selectedAvatarFile = null;
        removeAvatarRequested = true;
        currentAvatarUrl = null;
        refreshAvatarPreview();
    }

    private void applyAvatarChanges(Long userId) throws Exception {
        String previousAvatarUrl = currentAvatarUrl;
        if (removeAvatarRequested) {
            try {
                UserApi.getInstance().deleteUserAvatar(userId);
            } catch (Exception ignored) {
            }
        }
        if (selectedAvatarFile != null) {
            UserApi.getInstance().uploadUserAvatar(userId, selectedAvatarFile.toPath());
            currentAvatarUrl = "/api/v1/users/" + userId + "/avatar/file";
        } else if (removeAvatarRequested) {
            currentAvatarUrl = null;
        }
        DesktopImageSupport.evict(previousAvatarUrl);
        DesktopImageSupport.evict(currentAvatarUrl);
        selectedAvatarFile = null;
        removeAvatarRequested = false;
    }

    private void refreshAvatarPreview() {
        if (imgAvatarPreview == null || lblAvatarStatus == null || btnRemoveAvatar == null) return;
        imgAvatarPreview.setImage(null);
        if (selectedAvatarFile != null) {
            lblAvatarStatus.setText("Selected: " + selectedAvatarFile.getName());
            DesktopImageSupport.loadImageInto(imgAvatarPreview, selectedAvatarFile.toURI().toString(), 90, 90);
            btnRemoveAvatar.setDisable(false);
            return;
        }
        if (currentAvatarUrl != null && !currentAvatarUrl.isBlank()) {
            lblAvatarStatus.setText("Current avatar loaded");
            DesktopImageSupport.loadImageInto(imgAvatarPreview, currentAvatarUrl, 90, 90);
            btnRemoveAvatar.setDisable(false);
            return;
        }
        lblAvatarStatus.setText("No avatar");
        btnRemoveAvatar.setDisable(true);
    }

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

    @FXML
    void btnSaveClicked(ActionEvent event) {
        lblError.setText("");
        if (employee == null) {
            lblError.setText("No employee 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;
        }
        if (cbRole.getValue() == null) {
            lblError.setText("Role is required.");
            return;
        }
        if (cbStore.getValue() == null) {
            lblError.setText("Primary store is required.");
            return;
        }

        btnSave.setDisable(true);

        String role = cbRole.getValue();
        boolean active = "Active".equals(cbActive.getValue());
        Long storeId = cbStore.getValue().getId();

        new Thread(() -> {
            try {
                EmployeeRequest request = new EmployeeRequest();
                request.setUsername(username);
                request.setPassword(password.isEmpty() ? null : password);
                request.setFirstName(firstName);
                request.setLastName(lastName);
                request.setFullName(firstName + " " + lastName);
                request.setEmail(email);
                request.setPhone(phone);
                request.setRole(role);
                request.setActive(active);
                request.setPrimaryStoreId(storeId);

                EmployeeApi.getInstance().updateEmployee(employee.getId(), request);
                applyAvatarChanges(employee.getUserId());

                Platform.runLater(this::close);
            } catch (Exception e) {
                ActivityLogger.getInstance().logException("StaffEditDialogController.btnSaveClicked", e, "Updating employee");
                String msg = e.getMessage() == null ? "Could not update employee." : 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();
    }
}
