package dev.ui;

import dev.dao.MenuItemDao;
import dev.model.MenuItem;
import dev.model.OrderDetail;
import dev.model.User;
import dev.service.AuthService;
import dev.service.MenuService;
import dev.service.OrderService;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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();

    private User loggedInUser = null;

    public void start() {

        while (true) {
            if (loggedInUser == null) {
                showMainMenu();
            } else {
                showUserMenu();
            }
        }

    }

    private void showMainMenu()
    {
        System.out.println();
        System.out.println("=======================================");
        System.out.println("      🍕 WELCOME TO JAVA PIZZERIA 🍕");
        System.out.println("=======================================");
        System.out.println("1. Login");
        System.out.println("2. Register New Account");
        System.out.println("3. Exit");
        System.out.println("=======================================");
        System.out.print("Choose an option: ");

        int choice = getIntInput();
        switch (choice)
        {
            case 1 -> login();
            case 2 -> register();
            case 3 -> {
                System.out.println("goodbye");
                System.exit(0);
            }
            default -> System.out.println("invalid choice.");
        }
    }

    private void showUserMenu()
    {
        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");
        System.out.println("=======================================");
        System.out.print("Choose an option: ");

        int choice = getIntInput();
        switch (choice)
        {
            case 1 -> menuService.showMenu();
            case 2 -> placeOrder();
            case 3 -> orderService.showOrderHistory(loggedInUser.getId());
            case 4 -> {
                loggedInUser = null;
                System.out.println("logged out.");
            }
            default -> System.out.println("invalid choice.");
        }
    }

    private void login()
    {
        System.out.println("\n[Login]");
        System.out.print("Enter username: ");
        String username = scanner.nextLine().trim();
        System.out.print("Enter password: ");
        String password = scanner.nextLine().trim();

        User user = authService.login(username, password);
        if (user != null)
        {
            loggedInUser = user;
        }
    }

    private void register()
    {
        System.out.println("\n[Register]");
        System.out.print("Enter username: ");
        String username = scanner.nextLine().trim();
        System.out.print("Enter password: ");
        String password = scanner.nextLine().trim();
        System.out.print("Enter email (optional, press Enter to skip): ");
        String email = scanner.nextLine().trim();
        if (email.isEmpty()) email = null;

        boolean success = authService.register(username, password, email);
        if (success)
        {
            System.out.println("registration successful. Please login.");
        }
    }

    private void placeOrder()
    {
        System.out.println("\n[Placing Order]");
        menuService.showMenu();

        List<OrderDetail> cart = new ArrayList<>();
        while (true)
        {
            System.out.print("\nEnter the ID of the item to add (or 0 to finish): ");
            int itemId = getIntInput();
            if (itemId == 0) break;

            MenuItem item = new MenuItemDao().findById(itemId);
            if (item == null)
            {
                System.out.println("item not found.");
                continue;
            }

            System.out.print("Enter quantity: ");
            int quantity = getIntInput();
            if (quantity <= 0)
            {
                System.out.println("quantity must be greater than 0.");
                continue;
            }

            OrderDetail detail = new OrderDetail();
            detail.setMenuItemId(itemId);
            detail.setQuantity(quantity);
            cart.add(detail);

            System.out.printf("Added %dx %s to your cart.%n", quantity, item.getName());
        }

        if (cart.isEmpty())
        {
            System.out.println("cart is empty. Order cancelled.");
            return;
        }

        int orderId = orderService.placeOrder(loggedInUser.getId(), cart);
        if (orderId != -1)
        {
            orderService.printReceipt(orderId);
        }
    }

    private int getIntInput() {
        while (true) {
            try {
                return Integer.parseInt(scanner.nextLine().trim());
            } catch (NumberFormatException e) {
                System.out.print("please enter a number: ");
            }
        }
    }
}