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

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

    private File selectedAvatarFile;

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

        cbRole.setItems(FXCollections.observableArrayList("STAFF", "ADMIN"));
        cbRole.getSelectionModel().select("STAFF");

        cbStaffRole.setItems(FXCollections.observableArrayList(
                "STORE_MANAGER", "SALES_ASSOCIATE", "GROOMER", "VETERINARIAN"));
        cbStaffRole.getSelectionModel().selectFirst();

        cbActive.setItems(FXCollections.observableArrayList("Active", "Inactive"));
        cbActive.getSelectionModel().select("Active");

        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());
        btnRemoveAvatar.setDisable(true);

        loadStores();
    }

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

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

    private void handleRemoveAvatar() {
        selectedAvatarFile = null;
        imgAvatarPreview.setImage(null);
        lblAvatarStatus.setText("No avatar");
        btnRemoveAvatar.setDisable(true);
    }

    @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.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 (cbStaffRole.getValue() == null) {
            lblError.setText("Staff role is required.");
            return;
        }
        if (cbStore.getValue() == null) {
            lblError.setText("Primary store is required.");
            return;
        }

        btnCreate.setDisable(true);

        String role = cbRole.getValue();
        String staffRole = cbStaffRole.getValue();
        boolean active = "Active".equals(cbActive.getValue());
        Long storeId = cbStore.getValue().getId();
        File avatarFile = selectedAvatarFile;

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

                EmployeeResponse created = EmployeeApi.getInstance().createEmployee(request);

                if (avatarFile != null && created.getUserId() != null) {
                    try {
                        UserApi.getInstance().uploadUserAvatar(created.getUserId(), avatarFile.toPath());
                    } catch (Exception ignored) {
                    }
                }

                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("Account Created");
                    alert.setHeaderText(null);
                    alert.setContentText("Staff account created successfully.");
                    alert.showAndWait();
                    close();
                });
            } catch (Exception e) {
                ActivityLogger.getInstance().logException("StaffRegisterDialogController.btnCreateClicked", e, "Creating staff 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();
    }
}
