package dev.ui;

import java.util.Scanner;
import dev.model.MenuItem;
import dev.model.User;
import dev.service.AuthService;
import dev.service.MenuService;
import dev.service.OrderService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConsoleMenu {

    private final Scanner scanner =
            new Scanner(System.in);
    private final AuthService authService = new AuthService();
    private final MenuService menuService = new MenuService();
    private final OrderService orderService = new OrderService();
    public void start() {

        while (true) {

            System.out.println();
            System.out.println("===== JAVA PIZZERIA =====");
            System.out.println("1. Login");
            System.out.println("2. Register");
            System.out.println("3. Exit");

            int choice = scanner.nextInt();

            switch (choice) {

                case 1:
                    // TODO
                    handleLogin();
                    break;

                case 2:
                    // TODO
                    handleRegister();
                    break;

                case 3:
                    return;

                default:
                    System.out.println("Invalid choice");

            }

        }

    }
    private void handleRegister() {

        System.out.println();
        System.out.println("[Register New Account]");
        System.out.print("Choose a username: ");
        String username = scanner.next();
        System.out.print("Choose a password: ");
        String password = scanner.next();
        scanner.nextLine();
        System.out.print("Email (optional, press enter to skip): ");
        String email = scanner.nextLine();

        if (email.isBlank()) {
            email = null;
        }

        boolean success = authService.register(username, password, email);

        if (success) {
            System.out.println("Registration successful! You can now login.");
        } else {
            System.out.println("Registration failed. Username may already be taken.");
        }
    }

    private void handleLogin() {

        System.out.println();
        System.out.println("[Login]");
        System.out.print("Enter username: ");
        String username = scanner.next();
        System.out.print("Enter password: ");
        String password = scanner.next();

        User user = authService.login(username, password);

        if (user == null) {
            System.out.println("Invalid username or password.");
            return;
        }

        System.out.println("Welcome, " + user.getUsername() + "!");
        showMainMenu(user);
    }

    private void showMainMenu(User user) {

        boolean loggedIn = true;

        while (loggedIn) {

            System.out.println();
            System.out.println("=======================================");
            System.out.println("          MAIN MENU");
            System.out.println("=======================================");
            System.out.println("1. View Menu");
            System.out.println("2. Place a New Order");
            System.out.println("3. View Order History");
            System.out.println("4. Logout");

            int choice = scanner.nextInt();

            switch (choice) {

                case 1:
                    menuService.showMenu();
                    break;

                case 2:
                    handlePlaceOrder(user);
                    break;

                case 3:
                    orderService.showOrderHistory(user.getId());
                    break;

                case 4:
                    loggedIn = false;
                    System.out.println("Logged out.");
                    break;

                default:
                    System.out.println("Invalid choice");
            }
        }
    }

    private void handlePlaceOrder(User user) {

        menuService.showMenu();

        Map<Integer, Integer> itemQuantities = new HashMap<>();

        System.out.println();
        System.out.println("[Placing Order]");

        while (true) {
            System.out.print("Enter the ID of the item to add (or 0 to finish): ");
            int itemId = scanner.nextInt();

            if (itemId == 0) {
                break;
            }

            System.out.print("Enter quantity: ");
            int quantity = scanner.nextInt();

            if (quantity <= 0) {
                System.out.println("Quantity must be greater than zero.");
                continue;
            }

            itemQuantities.merge(itemId, quantity, Integer::sum);
            System.out.println("Added " + quantity + "x item #" + itemId + " to your cart.");
        }

        if (itemQuantities.isEmpty()) {
            System.out.println("No items added. Order cancelled.");
            return;
        }

        int orderId = orderService.placeOrder(user.getId(), itemQuantities);

        if (orderId == -1) {
            System.out.println("Failed to place order.");
            return;
        }

        System.out.println();
        System.out.println("[Order Summary / Receipt]");
        orderService.printReceipt(orderId);
        System.out.println("Order saved successfully!");
    }

}