package org.example.petshopdesktop.controllers;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.example.petshopdesktop.api.ApiClient;
import org.example.petshopdesktop.api.dto.auth.LoginRequest;
import org.example.petshopdesktop.api.dto.auth.LoginResponse;
import org.example.petshopdesktop.api.dto.auth.UserInfoResponse;
import org.example.petshopdesktop.api.endpoints.AuthApi;
import org.example.petshopdesktop.auth.Role;
import org.example.petshopdesktop.auth.UserSession;
import org.example.petshopdesktop.ui.SvgWebViewFactory;
import org.example.petshopdesktop.util.ActivityLogger;

public class LoginController {

    @FXML
    private TextField txtUsername;

    @FXML
    private PasswordField txtPassword;

    @FXML
    private Label lblError;

    @FXML
    private StackPane logoContainer;

    @FXML
    public void initialize() {
        lblError.setText("");
        logoContainer.getChildren().setAll(SvgWebViewFactory.build("/org/example/petshopdesktop/images/leons-pet-store-badge-text-light.svg", 142));
    }

    @FXML
    void btnLoginClicked(ActionEvent event) {
        String username = txtUsername.getText().trim();
        String password = txtPassword.getText();

        if (username.isEmpty() || password.isEmpty()) {
            lblError.setText("Please enter username and password.");
            return;
        }

        try {
            ApiClient apiClient = ApiClient.getInstance();

            LoginRequest loginRequest = new LoginRequest(username, password);
            LoginResponse loginResponse = apiClient.post("/api/v1/auth/login", loginRequest, LoginResponse.class);

            if (loginResponse == null) {
                throw new IllegalStateException("Login response is null");
            }

            String token = loginResponse.getToken();
            String roleStr = loginResponse.getRole();
            if (token == null || roleStr == null) {
                throw new IllegalStateException("Token or role is null");
            }

            if ("CUSTOMER".equalsIgnoreCase(roleStr)) {
                lblError.setText("Access Denied: Customer accounts cannot access the desktop application.");
                txtPassword.clear();
                return;
            }

            Role role = Role.valueOf(roleStr.toUpperCase());

            UserSession.getInstance().login(null, username, role, token);

            UserInfoResponse userInfo = apiClient.get("/api/v1/auth/me", UserInfoResponse.class);
            if (userInfo == null) {
                throw new IllegalStateException("User info is null");
            }
            UserSession.getInstance().login(userInfo.getId(), username, role, token);
            UserSession.getInstance().setStoreId(userInfo.getStoreId());
            UserSession.getInstance().setEmployeeName(userInfo.getFullName() == null || userInfo.getFullName().isBlank() ? username : userInfo.getFullName());
            UserSession.getInstance().setAvatarUrl(userInfo.getAvatarUrl());

            openMainLayout();

        } catch (Exception e) {
            ActivityLogger.getInstance().logException(
                "LoginController.btnLoginClicked",
                e,
                "Authentication attempt for username: " + username);

            String errorMsg = e.getMessage();
            if (errorMsg != null && errorMsg.contains("Authentication failed")) {
                lblError.setText("Invalid username or password.");
                txtPassword.clear();
            } else if (e.getCause() instanceof java.net.ConnectException ||
                       e instanceof java.net.http.HttpConnectTimeoutException) {
                lblError.setText("Backend is not reachable, check backend docker compose and port 8080.");
            } else {
                lblError.setText(errorMsg != null ? errorMsg : "Login failed. Please try again.");
            }
        }
    }

    @FXML
    void lnkForgotPasswordClicked(ActionEvent event) {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("Forgot Password");
        dialog.setHeaderText("Reset your password");
        dialog.setContentText("Enter your username or email:");

        dialog.showAndWait().ifPresent(input -> {
            if (input.trim().isEmpty()) return;
            new Thread(() -> {
                try {
                    AuthApi.getInstance().forgotPassword(input.trim());
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("Reset Link Sent");
                        alert.setHeaderText(null);
                        alert.setContentText("If this account exists, a password reset link has been sent to the associated email.");
                        alert.showAndWait();
                    });
                } catch (Exception e) {
                    ActivityLogger.getInstance().logException(
                        "LoginController.lnkForgotPasswordClicked",
                        e,
                        "Forgot password request for: " + input.trim());
                    Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.ERROR);
                        alert.setTitle("Error");
                        alert.setHeaderText(null);
                        alert.setContentText("Could not send reset link. Please try again.");
                        alert.showAndWait();
                    });
                }
            }).start();
        });
    }

    private void openMainLayout() {
        try {
            FXMLLoader loader = new FXMLLoader(
                    getClass().getResource("/org/example/petshopdesktop/main-layout-view.fxml"));
            Scene scene = new Scene(loader.load());
            Stage stage = (Stage) txtUsername.getScene().getWindow();
            stage.setScene(scene);
            stage.setTitle("Pet Shop Manager");
        } catch (Exception e) {
            ActivityLogger.getInstance().logException(
                "LoginController.openMainLayout",
                e,
                "Loading main application layout after successful login");
            lblError.setText("Error loading application: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
