package dev.service;

import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;

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


public class OrderService {

    private final static OrderDetailDao orderDetailDao = new OrderDetailDao();
    private final static OrderDao orderDao = new OrderDao();
    private final static MenuService menuService = new MenuService();
    private final static Scanner scanner = new Scanner(System.in);

    public void placeOrder(int userId) {

        List<MenuItem> menuItems = MenuService.menuItemDao.findAll();

        if (menuItems.isEmpty()) {
            System.out.println("No menu items available.");
            return;
        }

        // Display menu
        System.out.println("========== MENU ==========");
        for (MenuItem item : menuItems) {
            System.out.printf("%-4d %-25s %10.2f%n",
                    item.getId(), item.getName(), item.getPrice());
        }
        System.out.println("===========================");


        Order order = new Order(userId, LocalDateTime.now(), 0);
        int orderId = orderDao.save(order);

        double totalPrice = 0;
        boolean addingItems = true;

        while (addingItems) {

            System.out.print("Enter menu item id to add (0 to finish): ");
            int menuId = Integer.parseInt(scanner.nextLine().trim());

            if (menuId == 0) {
                addingItems = false;
                continue;
            }

            MenuItem selected = MenuService.menuItemDao.findById(menuId);

            if (selected == null) {
                System.out.println("Invalid item id, try again.");
                continue;
            }

            System.out.print("Enter quantity: ");
            int quantity = Integer.parseInt(scanner.nextLine().trim());

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

            OrderDetail detail = new OrderDetail(
                    orderId,
                    selected.getId(),
                    quantity,
                    selected.getPrice()
            );

            orderDetailDao.save(detail);

            totalPrice += selected.getPrice() * quantity;

            System.out.println(selected.getName() + " x" + quantity + " added.");
        }

        if (totalPrice == 0) {
            System.out.println("No items were added. Order canceled.");
            return;
        }

        order.setId(orderId);
        order.setTotalPrice((int) totalPrice);
        orderDao.save(order);

        System.out.println("Order placed successfully. Order ID: " + orderId);
        printReceipt(orderId);
    }

    public void printReceipt(int orderId) {

        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);

        if(details.isEmpty())
            return;

        System.out.println("Order ID: " + orderId);
        double total = 0;
        for (OrderDetail detail : details) {
            double subtotal = detail.getPrice() * detail.getQuantity();
            total += subtotal;
            System.out.printf("%-20s %dx  $%.2f%n",
                    MenuService.menuItemDao.findById(detail.getMenuItemId()).getName(),
                    detail.getQuantity(),
                    subtotal
            );
        }

        System.out.println("---------------------------");
        System.out.printf("Total: $%.2f%n", total);
        System.out.println("===========================\n");

    }

    public void showOrderHistory(int userId) {

        List<Order> orders = orderDao.findByUserId(userId);

        if (orders.isEmpty()){
            System.err.println("No orders found.");
            return;
        }

        for (Order order : orders){
            System.out.println("Order ID: " + order.getId());
            System.out.println("Date: " + order.getCreatedAt());
            System.out.printf("Total: $%.2f%n", order.getTotalPrice());
            System.out.println("---------------------------------");
            printReceipt(order.getId());
        }

    }

}