package dev.service;

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

import java.util.*;

public class OrderService {

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

    public void placeOrder(int userId) {
        menuService.showMenu();
        
        Map<Integer, int[]> cart = new LinkedHashMap<>();  // int[] = {quantity}
        Map<Integer, MenuItem> itemMap = new HashMap<>();

        while (true) {
            System.out.print("\nEnter item ID to add (0 to finish): ");
            int id = scanner.nextInt();
            if (id == 0) break;

            MenuItem item = menuItemDao.findById(id);
            if (item == null) {
                System.out.println("Item not found, try again.");
                continue;
            }
            System.out.print("Enter quantity: ");
            int qty = scanner.nextInt();
            if (qty <= 0) { System.out.println("Quantity must be > 0."); continue; }

            cart.merge(id, new int[]{qty}, (a, b) -> new int[]{a[0] + b[0]});
            itemMap.put(id, item);
            System.out.printf("Added %dx %s%n", qty, item.getName());
        }

        if (cart.isEmpty()) { System.out.println("No items selected."); return; }

        // Calculate total
        double total = cart.entrySet().stream()
                .mapToDouble(e -> itemMap.get(e.getKey()).getPrice() * e.getValue()[0])
                .sum();

        // Save order
        Order order = new Order(userId, total);
        int orderId = orderDao.save(order);
        if (orderId == -1) { System.out.println("Failed to save order."); return; }

        // Save order details
        for (Map.Entry<Integer, int[]> entry : cart.entrySet()) {
            MenuItem item = itemMap.get(entry.getKey());
            OrderDetail detail = new OrderDetail(orderId, item.getId(), entry.getValue()[0], item.getPrice());
            orderDetailDao.save(detail);
        }

        printReceipt(orderId);
    }

    public void printReceipt(int orderId) {
        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
        System.out.println("\n--- RECEIPT ---");
        System.out.printf("%-20s %5s  %8s  %8s%n", "Item", "Qty", "Unit", "Total");
        System.out.println("-".repeat(47));

        double grandTotal = 0;
        for (OrderDetail d : details) {
            MenuItem item = menuItemDao.findById(d.getMenuItemId());
            String name = (item != null) ? item.getName() : "Unknown";
            double subtotal = d.getPrice() * d.getQuantity();
            grandTotal += subtotal;
            System.out.printf("%-20s %5d  $%7.2f  $%7.2f%n",
                    name, d.getQuantity(), d.getPrice(), subtotal);
        }

        System.out.println("-".repeat(47));
        System.out.printf("%-20s %18s $%7.2f%n", "TOTAL", "", grandTotal);
        System.out.println("Order saved successfully!");
    }

    public void showOrderHistory(int userId) {
        List<Order> orders = orderDao.findByUserId(userId);
        if (orders.isEmpty()) { System.out.println("No past orders."); return; }

        System.out.println("\n--- ORDER HISTORY ---");
        System.out.printf("%-8s %-25s %s%n", "Order#", "Date", "Total");
        System.out.println("-".repeat(45));
        for (Order o : orders) {
            System.out.printf("%-8d %-25s $%.2f%n",
                    o.getId(), o.getCreatedAt().toString().replace("T", " "), o.getTotalPrice());
        }
        System.out.println("-".repeat(45));
    }
}