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.time.LocalDateTime;
import java.util.List;
import java.util.Scanner;

public class OrderService {

    private final MenuItemDao menuItemDao = new MenuItemDao();

    private final OrderDao orderDao = new OrderDao();

    private final OrderDetailDao orderDetailDao = new OrderDetailDao();

    private final Scanner scanner = new Scanner(System.in);

    public void placeOrder(int userId) {

        // TODO:
        // Create order

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

        System.out.println("Available Items:");

        for (MenuItem item : menuItems) {
            System.out.printf("%d. %s - $%.2f%n", item.getId(), item.getName(), item.getPrice());
        }

        List<OrderDetail> cart = new java.util.ArrayList<>();

        double total = 0;

        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;
            }

            MenuItem selected = menuItemDao.findById(itemId);

            if (selected == null) {
                System.out.println("Invalid item ID.");
                continue;
            }

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

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

            OrderDetail detail = new OrderDetail(0, 0, selected.getId(), quantity, selected.getPrice());
            cart.add(detail);

            total += selected.getPrice() * quantity;

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

        if (cart.isEmpty()) {
            System.out.println("No items were added to the order.");
            return;
        }

        Order order = new Order(0, userId, LocalDateTime.now(), total);

        int orderId = orderDao.save(order);

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

        for (OrderDetail detail : cart) {
            detail.setOrderId(orderId);
            orderDetailDao.save(detail);
        }

        System.out.println("Order saved successfully!");

        printReceipt(orderId);
    }

    public void printReceipt(int orderId) {

        // TODO:
        // Print order receipt

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

        System.out.println("---------------------------------------");
        System.out.printf("%-12s %-7s %-9s %-9s%n", "Item", "Qty", "Unit", "Total");
        System.out.println("---------------------------------------");

        double grandTotal = 0;

        for (OrderDetail detail : details) {

            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            double subtotal = detail.getPrice() * detail.getQuantity();
            grandTotal += subtotal;

            System.out.printf("%-12s %-7d $%-8.2f $%-8.2f%n",
                    item.getName(), detail.getQuantity(), detail.getPrice(), subtotal);
        }

        System.out.println("---------------------------------------");
        System.out.printf("Final Total: $%.2f%n", grandTotal);
    }

    public void showOrderHistory(int userId) {

        // TODO:
        // Display user's order history

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

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

        System.out.println("Order History:");

        for (Order order : orders) {
            System.out.printf("Order #%d - %s - Total: $%.2f%n",
                    order.getId(), order.getCreatedAt(), order.getTotalPrice());
        }
    }

}